Bắt đầu với Gemini API — Interactions API
Nguồn: https://ai.google.dev/gemini-api/docs/quickstart Tiêu đề gốc: Getting started - Interactions API | Google AI for Developers Ngôn ngữ gốc: tiếng Anh · Ngày tải: 2026-09-05 Phạm vi dịch: toàn văn trang, giữ nguyên toàn bộ code mẫu của cả bốn ngôn ngữ (Python, JavaScript, Java, REST); bỏ mục lục tự sinh "On this page", ô "Was this helpful?" và băng quảng cáo phiên bản mới ở đầu trang
Ghi chú người dịch: trong bản lưu, tab Java của mọi mục đều là cùng một đoạn code — ví dụ cơ bản của mục 2, chứ không phải ví dụ riêng cho từng mục. Bản dịch chép lại đúng như bản gốc, không sửa hộ.
Tóm tắt 30 giây
- Bài này đưa bạn từ chỗ chưa có gì tới lệnh gọi Gemini API đầu tiên trong chưa đầy một phút, qua Interactions API.
- Interactions API dùng được qua SDK Python, SDK JavaScript và REST; ví dụ trong bài có đủ bốn biến thể Python, JavaScript, Java, REST.
- Mười một mục lần lượt đi qua: lấy API key, gọi lần đầu, stream phản hồi, hội thoại nhiều lượt, hiểu nội dung đa phương thức, tạo nội dung đa phương thức, đầu ra có cấu trúc, dùng công cụ, gọi hàm của chính bạn, chạy agent quản lý sẵn, chạy tác vụ nền.
- Hội thoại nhiều lượt có hai kiểu: giữ trạng thái trên server (nối bằng
previous_interaction_id, Google khuyến nghị) và không trạng thái (store=false, bạn tự giữ lịch sử ở phía client). - Mỗi phản hồi là một tài nguyên
Interactionđầy đủ: metadata, thống kê token và lịch sử từng bước của lượt đó. SDK thêm các thuộc tính tiện lợi nhưinteraction.output_textvàinteraction.output_image.
Giới thiệu
Bài này giúp bạn bắt đầu với Gemini API qua Interactions API. Bạn sẽ gọi API lần đầu trong chưa đầy một phút. Sau đó, bạn lần lượt thử tạo văn bản, hiểu nội dung đa phương thức (multimodal), tạo ảnh và đầu ra có cấu trúc. Bạn cũng thử dùng công cụ, gọi hàm, agent và chạy nền.
Interactions API dùng được qua SDK Python và JavaScript, cũng như qua REST.
1. Lấy API key
Muốn dùng Gemini API, bạn cần một API key để xác thực yêu cầu và áp giới hạn an toàn. Key cũng giúp ghi nhận mức dùng vào tài khoản của bạn.
- Google AI Studio tự tạo sẵn một project và một API key cho người dùng mới. Bạn chép key đó ở trang API keys.
- Cần key mới thì bấm Create API key trong AI Studio rồi làm theo hộp thoại để thêm một cặp key–project mới.
Đặt key thành biến môi trường:
export GEMINI_API_KEY="YOUR_API_KEY"Nâng lên gói trả phí
Nâng lên gói trả phí làm hạn mức tần suất (rate limit) của bạn cao hơn, và đòi bạn thiết lập Cloud Billing.
- Bấm Set up billing ở trang API keys hoặc Projects trong AI Studio.
- Làm theo hộp thoại Cloud Billing để tạo hoặc liên kết một tài khoản thanh toán, thêm phương thức thanh toán, và trả trước tối thiểu $5 (hoặc số tiền tương đương theo đơn vị tiền tệ của bạn) dưới dạng credit trả phí.
- Xem mức dùng API của bạn trong Google AI Studio, mục Dashboard > Usage.
Xem thêm ở trang Billing.
2. Cài SDK và gọi lần đầu
Cài SDK rồi sinh văn bản bằng một lệnh gọi API duy nhất.
Python
Cài SDK:
pip install -U google-genaiKhởi tạo client và gửi một yêu cầu:
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Explain how AI works in a few words"
)
print(interaction.output_text)JavaScript
Cài SDK:
npm install @google/genaiKhởi tạo client và gửi một yêu cầu:
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Explain how AI works in a few words",
});
console.log(interaction.output_text);Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "Explain how AI works in a few words"
}'Phản hồi:
{
"id": "v1_ChdpQUFvYXI...",
"status": "completed",
"usage": {
"total_tokens": 197,
"total_input_tokens": 8,
"total_output_tokens": 12
},
"created": "2026-06-09T12:01:25Z",
"steps": [
{
"type": "thought",
"signature": "EvEFCu4FAQw..."
},
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "AI learns patterns from data, then uses those patterns to make predictions or decisions on new data."
}
]
}
],
"object": "interaction",
"model": "gemini-3.8-flash",
}Khi dùng REST, API trả về trọn tài nguyên Interaction: metadata, thống kê mức dùng, và lịch sử từng bước của lượt đó.
SDK cũng cho bạn xem toàn bộ phản hồi. Các thuộc tính tiện lợi như interaction.output_text và interaction.output_image giúp lấy thẳng kết quả cuối. Đọc thêm về cấu trúc phản hồi trong Tổng quan Interactions. Bạn có thể đọc hướng dẫn tạo văn bản để biết thêm về hướng dẫn nền (system prompt) và cấu hình sinh nội dung.
3. Stream phản hồi
Muốn tương tác mượt hơn thì hãy stream phản hồi ngay khi model sinh ra. Mỗi sự kiện step.delta mang về một mẩu văn bản, bạn hiển thị được ngay.
Python
from google import genai
client = genai.Client()
stream = client.interactions.create(
model="gemini-3.8-flash",
input="Explain how AI works",
stream=True
)
for event in stream:
print(event)JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const stream = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Explain how AI works",
stream: true,
});
for await (const event of stream) {
console.log(event);
}Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
--no-buffer \
-d '{
"model": "gemini-3.8-flash",
"input": "Explain how AI works",
"stream": true
}'Khi stream, server trả về một luồng sự kiện server-sent events (SSE). Mỗi sự kiện gồm một kiểu và phần dữ liệu JSON.
Phản hồi:
event: interaction.created
data: {"interaction":{"id":"v1_Chd...","status":"in_progress","model":"gemini-3.8-flash"},"event_type":"interaction.created"}
event: step.start
data: {"index":0,"step":{"type":"thought"},"event_type":"step.start"}
event: step.delta
data: {"index":0,"delta":{"signature":"EvEFCu4F...","type":"thought_signature"},"event_type":"step.delta"}
event: step.stop
data: {"index":0,"event_type":"step.stop"}
event: step.start
data: {"index":1,"step":{"type":"model_output"},"event_type":"step.start"}
event: step.delta
data: {"index":1,"delta":{"text":"AI ","type":"text"},"event_type":"step.delta"}
event: step.delta
data: {"index":1,"delta":{"text":"works ","type":"text"},"event_type":"step.delta"}
event: step.stop
data: {"index":1,"event_type":"step.stop"}
event: interaction.completed
data: {"interaction":{"id":"v1_Chd...","status":"completed","usage":{"total_tokens":197}},"event_type":"interaction.completed"}Muốn xem kỹ cách xử lý sự kiện stream và các kiểu delta, đọc hướng dẫn streaming interactions.
4. Hội thoại nhiều lượt
Interactions API hỗ trợ hội thoại nhiều lượt theo hai cách:
- Có trạng thái (khuyến nghị): nối tiếp hội thoại ngay trên server bằng
previous_interaction_id. Hợp với hầu hết luồng chat và luồng agent, khi bạn muốn server tự giữ lịch sử và tối ưu bộ nhớ đệm. - Không trạng thái: bạn tự giữ lịch sử hội thoại ở phía client, gửi lại toàn bộ các lượt trước (kể cả các bước trung gian là suy nghĩ của model và các bước gọi công cụ) trong mỗi yêu cầu.
Có trạng thái (khuyến nghị)
Nối các interaction lại bằng cách truyền previous_interaction_id. Server giữ trọn lịch sử hội thoại giúp bạn.
Python
from google import genai
client = genai.Client()
# Trạng thái giữ trên server (khuyến nghị)
interaction1 = client.interactions.create(
model="gemini-3.8-flash",
input="I have 2 dogs in my house.",
)
print("Response 1:", interaction1.output_text)
interaction2 = client.interactions.create(
model="gemini-3.8-flash",
input="How many paws are in my house?",
previous_interaction_id=interaction1.id,
)
print("Response 2:", interaction2.output_text)JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
// Trạng thái giữ trên server (khuyến nghị)
const interaction1 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "I have 2 dogs in my house.",
});
console.log("Response 1:", interaction1.output_text);
const interaction2 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "How many paws are in my house?",
previous_interaction_id: interaction1.id,
});
console.log("Response 2:", interaction2.output_text);Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "I have 2 dogs in my house."
}')
INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')
echo "Interaction 1 ID: $INTERACTION_ID"
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "How many paws are in my house?",
"previous_interaction_id": "'$INTERACTION_ID'"
}'Không trạng thái
Đặt store=false rồi tự quản lý lịch sử hội thoại ở phía client. Bạn phải giữ và gửi lại đúng y nguyên mọi bước do model sinh ra (kể cả bước thought và bước function_call).
Python
from google import genai
client = genai.Client()
history = [
{
"type": "user_input",
"content": [{"type": "text", "text": "I have 2 dogs in my house."}]
}
]
interaction1 = client.interactions.create(
model="gemini-3.8-flash",
store=False,
input=history
)
print("Response 1:", interaction1.steps[-1].content[0].text)
for step in interaction1.steps:
history.append(step.model_dump())
history.append({
"type": "user_input",
"content": [{"type": "text", "text": "How many paws are in my house?"}]
})
interaction2 = client.interactions.create(
model="gemini-3.8-flash",
store=False,
input=history
)
print("Response 2:", interaction2.steps[-1].content[0].text)JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const history = [
{
type: "user_input",
content: [{ type: "text", text: "I have 2 dogs in my house." }]
}
];
const interaction1 = await ai.interactions.create({
model: "gemini-3.8-flash",
store: false,
input: history
});
console.log("Response 1:", interaction1.steps.at(-1).content[0].text);
history.push(...interaction1.steps);
history.push({
type: "user_input",
content: [{ type: "text", text: "How many paws are in my house?" }]
});
const interaction2 = await ai.interactions.create({
model: "gemini-3.8-flash",
store: false,
input: history
});
console.log("Response 2:", interaction2.steps.at(-1).content[0].text);Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
# Lượt 1: gửi kèm store: false
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"store": false,
"input": [
{
"type": "user_input",
"content": "I have 2 dogs in my house."
}
]
}')
MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')
# Lượt 2: dựng lại toàn bộ lịch sử
HISTORY=$(jq -n \
--argjson first_input '[{"type": "user_input", "content": "I have 2 dogs in my house."}]' \
--argjson model_steps "$MODEL_STEPS" \
--argjson second_input '[{"type": "user_input", "content": "How many paws are in my house?"}]' \
'$first_input + $model_steps + $second_input')
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d "{
\"model\": \"gemini-3.8-flash\",
\"store\": false,
\"input\": $HISTORY
}"Phản hồi:
{
"id": "v2_Chd...",
"status": "completed",
"usage": {
"total_tokens": 240,
"total_input_tokens": 60,
"total_output_tokens": 20
},
"steps": [
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "There are 8 paws in your house. 2 dogs \u00d7 4 paws = 8 paws."
}
]
}
],
"object": "interaction",
"model": "gemini-3.8-flash"
}Interaction thứ hai trả về một object phản hồi hoàn chỉnh, chỉ chứa các bước mới, nhưng vẫn neo vào ngữ cảnh của lượt trước. Đọc thêm cách giữ trạng thái trong hướng dẫn hội thoại nhiều lượt. Bạn cũng có thể tìm hiểu chế độ không trạng thái để tự quản lý lịch sử ở phía client.
5. Hiểu nội dung đa phương thức
Model Gemini hiểu ảnh, âm thanh, video và tài liệu ngay trong model. Bạn truyền media cùng với văn bản trong một yêu cầu duy nhất.
Python
import base64
from google import genai
client = genai.Client()
# Nạp một ảnh trên máy
with open("sample.jpg", "rb") as f:
image_bytes = f.read()
image_b64 = base64.b64encode(image_bytes).decode("utf-8")
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=[
{"type": "text", "text": "Compare this local image and this remote audio file."},
{
"type": "image",
"data": image_b64,
"mime_type": "image/jpeg"
},
{
"type": "audio",
"uri": "https://storage.googleapis.com/generativeai-downloads/data/sample.mp3",
"mime_type": "audio/mp3"
}
]
)
print(interaction.output_text)JavaScript
import fs from "fs";
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
// Nạp một ảnh trên máy
const imageBytes = fs.readFileSync("sample.jpg");
const imageB64 = imageBytes.toString("base64");
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: [
{ type: "text", text: "Compare this local image and this remote audio file." },
{
type: "image",
data: imageB64,
mime_type: "image/jpeg"
},
{
type: "audio",
uri: "https://storage.googleapis.com/generativeai-downloads/data/sample.mp3",
mime_type: "audio/mp3"
}
],
});
console.log(interaction.output_text);Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
# Mã hóa base64 ảnh trên máy
BASE64_IMAGE=$(base64 -w 0 sample.jpg)
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" -H "x-goog-api-key: $GEMINI_API_KEY" -H 'Content-Type: application/json' -H "Api-Revision: 2026-05-20" -d '{
"model": "gemini-3.8-flash",
"input": [
{
"type": "text",
"text": "Compare this local image and this remote audio file."
},
{
"type": "image",
"data": "'$BASE64_IMAGE'",
"mime_type": "image/jpeg"
},
{
"type": "audio",
"uri": "https://storage.googleapis.com/generativeai-downloads/data/sample.mp3",
"mime_type": "audio/mp3"
}
]
}'Phản hồi:
{
"id": "v1_Chd...",
"status": "completed",
"usage": {
"total_tokens": 300
},
"steps": [
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "The local image displays a pipe organ while the remote audio file is a sample MP3 clip..."
}
]
}
],
"object": "interaction",
"model": "gemini-3.8-flash",
}Xem cách truyền ảnh, video và file âm thanh trong hướng dẫn hiểu ảnh.
- Hiểu âm thanh: gỡ băng, tóm tắt, hoặc trả lời câu hỏi về file âm thanh.
- Hiểu video: phân tích nội dung video, định vị sự kiện, và mô tả hành động.
- Xử lý tài liệu: rút thông tin từ PDF và các định dạng tài liệu khác.
6. Tạo nội dung đa phương thức
Gemini tạo được ảnh ngay trong model, nhờ các model ảnh Nano Banana.
Python
import base64
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.1-flash-image",
input="Generate an image of a futuristic city skyline at sunset",
)
with open("generated_image.png", "wb") as f:
f.write(base64.b64decode(interaction.output_image.data))JavaScript
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: "gemini-3.1-flash-image",
input: "Generate an image of a futuristic city skyline at sunset",
});
const generatedImage = interaction.output_image;
if (generatedImage) {
const buffer = Buffer.from(generatedImage.data, "base64");
fs.writeFileSync("generated_image.png", buffer);
}Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.1-flash-image",
"input": [
{"type": "text", "text": "Generate an image of a futuristic city skyline at sunset"}
]
}'Phản hồi:
{
"id": "v1_Chd...",
"status": "completed",
"steps": [
{
"type": "model_output",
"content": [
{
"type": "image",
"data": "BASE64_ENCODED_IMAGE",
"mime_type": "image/png"
}
]
}
],
"object": "interaction",
"model": "gemini-3.1-flash-image",
}Khi tạo ảnh, model trả dữ liệu ảnh mã hóa base64 trong một bước thuộc mảng steps. Dữ liệu cũng được trả qua thuộc tính tiện lợi output_image. Xem hướng dẫn tạo ảnh để biết về tỷ lệ khung hình, chỉnh sửa ảnh và ảnh tham chiếu.
- Tạo giọng nói: tạo giọng nói giàu biểu cảm, nhiều người nói, với Gemini 3.1 Flash TTS.
- Tạo nhạc: tạo đoạn nhạc ngắn và bài hát trọn vẹn với Lyria 3.5.
7. Dùng đầu ra có cấu trúc
Cấu hình để model trả về JSON khớp một schema do bạn định nghĩa. Structured output làm việc được với Pydantic (Python) và Zod (JavaScript).
Python
from google import genai
from pydantic import BaseModel, Field
from typing import List, Optional
class Recipe(BaseModel):
recipe_name: str = Field(description="Name of the recipe.")
ingredients: List[str] = Field(description="List of ingredients.")
prep_time_minutes: Optional[int] = Field(description="Prep time in minutes.")
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Give me a recipe for banana bread",
response_format={
"type": "text",
"mime_type": "application/json",
"schema": Recipe.model_json_schema()
},
)
recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe)JavaScript
import { GoogleGenAI } from "@google/genai";
import * as z from "zod";
const ai = new GoogleGenAI({});
const recipeJsonSchema = {
type: "object",
properties: {
recipe_name: { type: "string", description: "Name of the recipe." },
ingredients: {
type: "array",
items: { type: "string" },
description: "List of ingredients."
},
prep_time_minutes: {
type: "integer",
description: "Prep time in minutes."
}
},
required: ["recipe_name", "ingredients"]
};
const recipeSchema = z.fromJSONSchema(recipeJsonSchema);
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Give me a recipe for banana bread",
response_format: {
type: "text",
mime_type: "application/json",
schema: recipeJsonSchema
},
});
const recipe = recipeSchema.parse(JSON.parse(interaction.output_text));
console.log(recipe);Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "Give me a recipe for banana bread",
"response_format": {
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "object",
"properties": {
"recipe_name": { "type": "string", "description": "Name of the recipe." },
"ingredients": {
"type": "array",
"items": { "type": "string" },
"description": "List of ingredients."
},
"prep_time_minutes": {
"type": "integer",
"description": "Prep time in minutes."
}
},
"required": ["recipe_name", "ingredients"]
}
}
}'Phản hồi:
{
"id": "v1_Chd...",
"status": "completed",
"steps": [
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "{\n \"recipe_name\": \"Classic Banana Bread\",\n \"ingredients\": [\n \"3 ripe bananas, mashed\",\n \"1/3 cup melted butter\",\n \"3/4 cup sugar\",\n \"1 egg, beaten\",\n \"1 teaspoon vanilla extract\",\n \"1 teaspoon baking soda\",\n \"Pinch of salt\",\n \"1.5 cups all-purpose flour\"\n ],\n \"prep_time_minutes\": 15\n}"
}
]
}
],
"object": "interaction",
"model": "gemini-3.8-flash",
}Khối văn bản đầu ra chứa một chuỗi JSON hợp lệ, khớp chính xác schema bạn yêu cầu. Muốn biết cách định nghĩa cấu trúc phức tạp hơn và schema đệ quy, xem hướng dẫn đầu ra có cấu trúc.
8. Dùng công cụ
Neo phản hồi của model vào thông tin thời gian thực bằng Google Search. API tự tìm kiếm, xử lý kết quả, và trả về trích dẫn có địa chỉ (citation).
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Who won the euro 2024?",
tools=[{"type": "google_search"}]
)
print(interaction.output_text)
# In các trích dẫn
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text" and content_block.annotations:
print("\nCitations:")
for annotation in content_block.annotations:
if annotation.type == "url_citation":
print(f" [{annotation.title}]({annotation.url})")JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Who won the euro 2024?",
tools: [{ type: "google_search" }]
});
console.log(interaction.output_text);
// In các trích dẫn
for (const step of interaction.steps) {
if (step.type === "model_output") {
for (const contentBlock of step.content) {
if (contentBlock.type === "text" && contentBlock.annotations) {
console.log("\nCitations:");
for (const annotation of contentBlock.annotations) {
if (annotation.type === "url_citation") {
console.log(` [${annotation.title}](${annotation.url})`);
}
}
}
}
}
}Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "Who won the euro 2024?",
"tools": [{"type": "google_search"}]
}'Phản hồi:
{
"id": "v1_Chd...",
"status": "completed",
"steps": [
{
"type": "thought",
"signature": "EvEFCu4F..."
},
{
"type": "google_search_call",
"arguments": {
"queries": ["UEFA Euro 2024 winner"]
}
},
{
"type": "google_search_result",
"call_id": "search_001",
"result": [
{
"search_suggestions": "<!-- HTML and CSS search widget -->"
}
]
},
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "Spain won Euro 2024, defeating England 2-1 in the final.",
"annotations": [
{
"type": "url_citation",
"url": "https://www.uefa.com/euro2024",
"title": "uefa.com",
"start_index": 0,
"end_index": 56
}
]
}
]
}
],
"object": "interaction",
"model": "gemini-3.8-flash",
}Các bước tìm kiếm nằm chi tiết trong lịch sử của interaction. Kết quả cuối kèm trích dẫn ngay trong dòng, trỏ về nguồn trên web.
Bạn xem cách rút trích dẫn tìm kiếm trong hướng dẫn neo vào Google Search. Cách kết hợp nhiều công cụ nằm trong hướng dẫn kết hợp công cụ.
- Chạy code: chạy code Python trong môi trường sandbox Borg an toàn.
- URL context: truyền thẳng URL web công khai để neo phản hồi vào nội dung trang.
- File search: lập chỉ mục và tìm kiếm trong các tài liệu và file media đã tải lên.
- Google Maps: neo phản hồi vào dữ liệu không gian địa lý và vị trí ngoài đời thực.
- Computer use: tự động hóa trình duyệt và thao tác trên màn hình.
9. Gọi hàm của chính bạn
Gọi hàm (function calling) nối model với code của bạn. Bạn khai báo tên hàm và tham số. Model tự quyết khi nào gọi và trả về đối số có cấu trúc. Bạn chạy hàm ở máy mình rồi gửi kết quả ngược lại.
Có trạng thái (khuyến nghị)
Python
import json
from google import genai
client = genai.Client()
weather_tool = {
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
available_functions = {
"get_current_temperature": lambda location: {
"location": location, "temperature": "22", "unit": "celsius"
},
}
user_input = "What is the temperature in London?"
previous_id = None
while True:
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=user_input,
tools=[weather_tool],
previous_interaction_id=previous_id,
)
function_results = []
for step in interaction.steps:
if step.type == "function_call":
result = available_functions[step.name](**step.arguments)
print(f"Called {step.name}({step.arguments}) → {result}")
function_results.append({
"type": "function_result",
"name": step.name,
"call_id": step.id,
"result": [{"type": "text", "text": json.dumps(result)}],
})
if not function_results:
break
user_input = function_results
previous_id = interaction.id
print(interaction.output_text)JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const weatherTool = {
type: "function",
name: "get_current_temperature",
description: "Gets the current temperature for a given location.",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city name, e.g. San Francisco",
},
},
required: ["location"],
},
};
const availableFunctions = {
get_current_temperature: ({ location }) => ({
location, temperature: "22", unit: "celsius"
}),
};
let input = "What is the temperature in London?";
let previousId = null;
let interaction;
while (true) {
interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input,
tools: [weatherTool],
previous_interaction_id: previousId,
});
const functionResults = [];
for (const step of interaction.steps) {
if (step.type === "function_call") {
const result = availableFunctions[step.name](step.arguments);
console.log(`Called ${step.name}(${JSON.stringify(step.arguments)}) →`, result);
functionResults.push({
type: "function_result",
name: step.name,
call_id: step.id,
result: [{ type: "text", text: JSON.stringify(result) }],
});
}
}
if (functionResults.length === 0) break;
input = functionResults;
previousId = interaction.id;
}
console.log(interaction.output_text);Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
# Lượt 1: gửi prompt kèm khai báo hàm
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "What is the temperature in London?",
"tools": [{
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city name"}
},
"required": ["location"]
}
}]
}')
INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')
FC_NAME=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .name')
FC_ID=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .id')
echo "Function: $FC_NAME, Call ID: $FC_ID"
# Lượt 2: gửi kết quả hàm ngược lại
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"previous_interaction_id": "'$INTERACTION_ID'",
"input": [{
"type": "function_result",
"name": "'$FC_NAME'",
"call_id": "'$FC_ID'",
"result": [{"type": "text", "text": "{\"location\": \"London\", \"temperature\": \"22\", \"unit\": \"celsius\"}"}]
}],
"tools": [{
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city name"}
},
"required": ["location"]
}
}]
}'Không trạng thái
Bạn cũng dùng được gọi hàm ở chế độ không trạng thái: tự giữ lịch sử hội thoại ở phía client và đặt store=false. Ở chế độ này, bạn phải truyền trọn lịch sử hội thoại trong trường input của mỗi yêu cầu sau đó. Lịch sử ấy phải gồm:
- Bước
user_inputban đầu. - Mọi bước do model sinh ra ở Lượt 1 (kể cả bước
thoughtvàfunction_call), giữ đúng y nguyên như lúc nhận. - Bước
function_resultchứa kết quả của hàm bạn đã chạy.
Python
import json
from google import genai
client = genai.Client()
weather_tool = {
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
available_functions = {
"get_current_temperature": lambda location: {
"location": location, "temperature": "22", "unit": "celsius"
},
}
history = [
{
"type": "user_input",
"content": [{"type": "text", "text": "What is the temperature in London?"}]
}
]
while True:
interaction = client.interactions.create(
model="gemini-3.8-flash",
store=False,
input=history,
tools=[weather_tool],
)
function_results = []
for step in interaction.steps:
history.append(step.model_dump())
if step.type == "function_call":
result = available_functions[step.name](**step.arguments)
print(f"Called {step.name}({step.arguments}) → {result}")
fn_result = {
"type": "function_result",
"name": step.name,
"call_id": step.id,
"result": [{"type": "text", "text": json.dumps(result)}],
}
function_results.append(fn_result)
history.append(fn_result)
if not function_results:
break
print(interaction.output_text)JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const weatherTool = {
type: "function",
name: "get_current_temperature",
description: "Gets the current temperature for a given location.",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city name, e.g. San Francisco",
},
},
required: ["location"],
},
};
const availableFunctions = {
get_current_temperature: ({ location }) => ({
location, temperature: "22", unit: "celsius"
}),
};
const history = [
{
type: "user_input",
content: [{ type: "text", text: "What is the temperature in London?" }]
}
];
let interaction;
while (true) {
interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
store: false,
input: history,
tools: [weatherTool],
});
const functionResults = [];
for (const step of interaction.steps) {
history.push(step);
if (step.type === "function_call") {
const result = availableFunctions[step.name](step.arguments);
console.log(`Called ${step.name}(${JSON.stringify(step.arguments)}) →`, result);
const fnResult = {
type: "function_result",
name: step.name,
call_id: step.id,
result: [{ type: "text", text: JSON.stringify(result) }],
};
functionResults.push(fnResult);
history.push(fnResult);
}
}
if (functionResults.length === 0) break;
}
console.log(interaction.output_text);Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
# Lượt 1: gửi yêu cầu kèm tools và store: false
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"store": false,
"input": [
{
"type": "user_input",
"content": "What is the temperature in London?"
}
],
"tools": [{
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city name"}
},
"required": ["location"]
}
}]
}')
# Rút các bước của model (thought, function_call)
MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')
FC_NAME=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .name')
FC_ID=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .id')
echo "Function: $FC_NAME, Call ID: $FC_ID"
# Giả sử chạy hàm ở máy trả về:
RESULT="{\"location\": \"London\", \"temperature\": \"22\", \"unit\": \"celsius\"}"
# Dựng lại lịch sử cho Lượt 2
HISTORY=$(jq -n \
--argjson first_input '[{"type": "user_input", "content": "What is the temperature in London?"}]' \
--argjson model_steps "$MODEL_STEPS" \
--arg fc_name "$FC_NAME" \
--arg fc_id "$FC_ID" \
--arg result "$RESULT" \
'$first_input + $model_steps + [{"type": "function_result", "name": $fc_name, "call_id": $fc_id, "result": [{"type": "text", "text": $result}]}]')
# Lượt 2: gửi trọn lịch sử
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d "{
\"model\": \"gemini-3.8-flash\",
\"store\": false,
\"input\": $HISTORY,
\"tools\": [{
\"type\": \"function\",
\"name\": \"get_current_temperature\",
\"description\": \"Gets the current temperature for a given location.\",
\"parameters\": {
\"type\": \"object\",
\"properties\": {
\"location\": {\"type\": \"string\", \"description\": \"The city name\"}
},
\"required\": [\"location\"]
}
}]
}"Phản hồi:
Ở Lượt 1, model trả về phản hồi có trạng thái requires_action kèm bước function_call:
{
"id": "v1_Chd...",
"status": "requires_action",
"steps": [
{
"type": "function_call",
"id": "call_abc123",
"name": "get_current_temperature",
"arguments": {
"location": "London"
}
}
],
"object": "interaction",
"model": "gemini-3.8-flash"
}Sau khi bạn chạy hàm ở máy mình và gửi kết quả (Lượt 2), interaction hoàn tất trả về:
{
"id": "v1_Chd...",
"status": "completed",
"steps": [
{
"type": "function_call",
"id": "call_abc123",
"name": "get_current_temperature",
"arguments": {
"location": "London"
}
},
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "The temperature in London is currently 22°C."
}
]
}
],
"object": "interaction",
"model": "gemini-3.8-flash",
}Muốn dùng các tính năng nâng cao như gọi hàm song song hay các chế độ chọn hàm, xem hướng dẫn gọi hàm.
10. Chạy một agent quản lý sẵn
Agent quản lý sẵn (managed agent) chạy trong một sandbox từ xa, dùng được các công cụ như chạy code và quản lý file. Bạn truyền agent thay cho model, và đặt environment="remote".
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
environment="remote",
)
print(f"Environment: {interaction.environment_id}")
print(interaction.output_text)JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
environment: "remote",
});
console.log(`Environment: ${interaction.environment_id}`);
console.log(interaction.output_text);Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
"environment": "remote"
}'Bạn cũng định nghĩa và lưu được agent tùy chỉnh với hướng dẫn, kỹ năng và nguồn dữ liệu của riêng mình.
- Quickstart: gọi agent lần đầu, stream phản hồi, và dựng một agent tùy chỉnh.
- Antigravity Agent: khả năng, công cụ, đầu vào đa phương thức và giá của agent mặc định.
- Agents trong AI Studio: sân chơi trực quan để thử agent mà không cần viết code.
11. Chạy tác vụ nền
Đặt background=True để chạy tác vụ dài theo kiểu bất đồng bộ. Bạn hỏi kết quả định kỳ bằng interactions.get(). Xem chi tiết ở hướng dẫn chạy nền.
Python
import time
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Write a detailed analysis of the impact of artificial intelligence on modern healthcare.",
background=True,
)
print(f"Started background task: {interaction.id}")
print(f"Status: {interaction.status}")
# Hỏi định kỳ tới khi xong
while True:
result = client.interactions.get(interaction.id)
print(f"Status: {result.status}")
if result.status == "completed":
print(f"\nResult:\n{result.output_text}")
break
elif result.status == "failed":
print(f"Failed: {result.error}")
break
time.sleep(5)JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Write a detailed analysis of the impact of artificial intelligence on modern healthcare.",
background: true,
});
console.log(`Started background task: ${interaction.id}`);
console.log(`Status: ${interaction.status}`);
// Hỏi định kỳ tới khi xong
while (true) {
const result = await ai.interactions.get(interaction.id);
console.log(`Status: ${result.status}`);
if (result.status === "completed") {
console.log(`\nResult:\n${result.output_text}`);
break;
} else if (result.status === "failed") {
console.log(`Failed: ${result.error}`);
break;
}
await new Promise(r => setTimeout(r, 5000));
}Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain how AI works in a few sentences."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));REST
# Khởi động một tác vụ nền
RESPONSE=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "Write a detailed analysis of the impact of artificial intelligence on modern healthcare.",
"background": true
}')
INTERACTION_ID=$(echo "$RESPONSE" | jq -r '.id')
echo "Started background task: $INTERACTION_ID"
# Hỏi định kỳ tới khi xong
while true; do
RESULT=$(curl -s "https://generativelanguage.googleapis.com/v1beta/interactions/$INTERACTION_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20")
STATUS=$(echo "$RESULT" | jq -r '.status')
echo "Status: $STATUS"
if [ "$STATUS" = "completed" ]; then
echo "$RESULT" | jq -r '.steps[] | select(.type=="model_output") | .content[] | select(.type=="text") | .text'
break
elif [ "$STATUS" = "failed" ]; then
echo "Failed"
break
fi
sleep 5
donePhản hồi:
Phản hồi đầu tiên trả về ngay lập tức với trạng thái in_progress:
{
"id": "v1_abc123",
"status": "in_progress",
"object": "interaction",
"model": "gemini-3.8-flash"
}Khi tác vụ nền chạy xong, kiểm tra lại trạng thái của interaction sẽ thấy:
{
"id": "v1_abc123",
"status": "completed",
"steps": [
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "Artificial intelligence has transformed modern healthcare in several..."
}
]
}
],
"object": "interaction",
"model": "gemini-3.8-flash",
}Đọc thêm về cách chạy model và agent bất đồng bộ trong hướng dẫn chạy nền.
Đọc tiếp
- Chạy nền: chạy tác vụ dài theo kiểu bất đồng bộ và quản lý trạng thái.
- Tạo văn bản: hướng dẫn nền, cấu hình sinh nội dung, và các mẫu xử lý văn bản nâng cao.
- Tạo ảnh: tỷ lệ khung hình, chỉnh sửa ảnh, và ảnh tham chiếu phong cách.
- Hiểu ảnh: phân loại, nhận diện vật thể, và hỏi đáp trên ảnh.
- Thinking: dùng chế độ suy nghĩ (thinking) theo chuỗi lập luận cho tác vụ phức tạp.
- Gọi hàm: gọi hàm song song, gọi hàm kết hợp, và các chế độ ràng buộc.
- Google Search: neo vào nguồn, trích dẫn, và gợi ý tìm kiếm.
- Managed Agents: agent dựng sẵn, có chạy code và quản lý file.
- Deep Research: nghiên cứu nhiều bước tự chủ, có lập kế hoạch và tổng hợp.
- Structured output: JSON schema, enum, và định nghĩa kiểu đệ quy.
Giấy phép và ngày cập nhật
Trừ khi có ghi chú khác, nội dung trang này phát hành theo Creative Commons Attribution 4.0 License. Code mẫu phát hành theo Apache 2.0 License. Chi tiết xem Google Developers Site Policies. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các công ty liên kết.
Cập nhật lần cuối 2026-09-04 UTC.