Interactions API là một giao diện hợp nhất để tương tác với các mô hình và tác nhân Gemini. Nền tảng này giúp đơn giản hoá việc quản lý trạng thái, điều phối công cụ và các tác vụ kéo dài. Để xem toàn bộ giản đồ API, hãy xem Tài liệu tham khảo API.
Ví dụ sau đây minh hoạ cách gọi Interactions API bằng một câu lệnh dạng văn bản.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-pro-preview",
input="Tell me a short joke about programming."
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-pro-preview',
input: 'Tell me a short joke about programming.',
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-pro-preview",
"input": "Tell me a short joke about programming."
}'
Tương tác cơ bản
Interactions API có sẵn thông qua các SDK hiện có của chúng tôi. Cách đơn giản nhất để tương tác với mô hình là cung cấp một câu lệnh bằng văn bản. input có thể là một chuỗi, một danh sách chứa các đối tượng nội dung hoặc một danh sách các lượt có vai trò và đối tượng nội dung.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="Tell me a short joke about programming."
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'Tell me a short joke about programming.',
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "Tell me a short joke about programming."
}'
Cuộc trò chuyện
Bạn có thể tạo cuộc trò chuyện nhiều lượt theo 2 cách:
- Có trạng thái bằng cách tham chiếu một lượt tương tác trước đó
- Không trạng thái bằng cách cung cấp toàn bộ nhật ký trò chuyện
Cuộc trò chuyện có trạng thái
Truyền id từ lượt tương tác trước đó đến tham số previous_interaction_id để tiếp tục cuộc trò chuyện.
Python
from google import genai
client = genai.Client()
# 1. First turn
interaction1 = client.interactions.create(
model="gemini-2.5-flash",
input="Hi, my name is Phil."
)
print(f"Model: {interaction1.outputs[-1].text}")
# 2. Second turn (passing previous_interaction_id)
interaction2 = client.interactions.create(
model="gemini-2.5-flash",
input="What is my name?",
previous_interaction_id=interaction1.id
)
print(f"Model: {interaction2.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. First turn
const interaction1 = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'Hi, my name is Phil.'
});
console.log(`Model: ${interaction1.outputs[interaction1.outputs.length - 1].text}`);
// 2. Second turn (passing previous_interaction_id)
const interaction2 = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'What is my name?',
previous_interaction_id: interaction1.id
});
console.log(`Model: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
REST
# 1. First turn
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "Hi, my name is Phil."
}'
# 2. Second turn (Replace INTERACTION_ID with the ID from the previous interaction)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
# "model": "gemini-2.5-flash",
# "input": "What is my name?",
# "previous_interaction_id": "INTERACTION_ID"
# }'
Truy xuất các hoạt động tương tác có trạng thái trước đây
Sử dụng lượt tương tác id để truy xuất các lượt trước đó của cuộc trò chuyện.
Python
previous_interaction = client.interactions.get("<YOUR_INTERACTION_ID>")
print(previous_interaction)
JavaScript
const previous_interaction = await client.interactions.get("<YOUR_INTERACTION_ID>");
console.log(previous_interaction);
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/<YOUR_INTERACTION_ID>" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Cuộc trò chuyện không trạng thái
Bạn có thể quản lý nhật ký trò chuyện theo cách thủ công ở phía máy khách.
Python
from google import genai
client = genai.Client()
conversation_history = [
{
"role": "user",
"content": "What are the three largest cities in Spain?"
}
]
interaction1 = client.interactions.create(
model="gemini-2.5-flash",
input=conversation_history
)
print(f"Model: {interaction1.outputs[-1].text}")
conversation_history.append({"role": "model", "content": interaction1.outputs})
conversation_history.append({
"role": "user",
"content": "What is the most famous landmark in the second one?"
})
interaction2 = client.interactions.create(
model="gemini-2.5-flash",
input=conversation_history
)
print(f"Model: {interaction2.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const conversationHistory = [
{
role: 'user',
content: "What are the three largest cities in Spain?"
}
];
const interaction1 = await client.interactions.create({
model: 'gemini-2.5-flash',
input: conversationHistory
});
console.log(`Model: ${interaction1.outputs[interaction1.outputs.length - 1].text}`);
conversationHistory.push({ role: 'model', content: interaction1.outputs });
conversationHistory.push({
role: 'user',
content: "What is the most famous landmark in the second one?"
});
const interaction2 = await client.interactions.create({
model: 'gemini-2.5-flash',
input: conversationHistory
});
console.log(`Model: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": [
{
"role": "user",
"content": "What are the three largest cities in Spain?"
},
{
"role": "model",
"content": "The three largest cities in Spain are Madrid, Barcelona, and Valencia."
},
{
"role": "user",
"content": "What is the most famous landmark in the second one?"
}
]
}'
Khả năng đa phương thức
Bạn có thể sử dụng Interactions API cho các trường hợp sử dụng đa phương thức, chẳng hạn như hiểu hình ảnh hoặc tạo video.
Hiểu biết đa phương thức
Bạn có thể cung cấp dữ liệu đa phương thức dưới dạng dữ liệu được mã hoá base64 nội dòng hoặc sử dụng Files API cho các tệp lớn hơn.
Hiểu hình ảnh
Python
import base64
from pathlib import Path
from google import genai
client = genai.Client()
# Read and encode the image
with open(Path(__file__).parent / "car.png", "rb") as f:
base64_image = base64.b64encode(f.read()).decode('utf-8')
interaction = client.interactions.create(
model="gemini-2.5-flash",
input=[
{"type": "text", "text": "Describe the image."},
{"type": "image", "data": base64_image, "mime_type": "image/png"}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const base64Image = fs.readFileSync('car.png', { encoding: 'base64' });
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: [
{ type: 'text', text: 'Describe the image.' },
{ type: 'image', data: base64Image, mime_type: 'image/png' }
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": [
{"type": "text", "text": "Describe the image."},
{"type": "image", "data": "'"$(base64 -w0 car.png)"'", "mime_type": "image/png"}
]
}'
Hiểu được âm thanh
Python
import base64
from pathlib import Path
from google import genai
client = genai.Client()
# Read and encode the audio
with open(Path(__file__).parent / "speech.wav", "rb") as f:
base64_audio = base64.b64encode(f.read()).decode('utf-8')
interaction = client.interactions.create(
model="gemini-2.5-flash",
input=[
{"type": "text", "text": "What does this audio say?"},
{"type": "audio", "data": base64_audio, "mime_type": "audio/wav"}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const base64Audio = fs.readFileSync('speech.wav', { encoding: 'base64' });
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: [
{ type: 'text', text: 'What does this audio say?' },
{ type: 'audio', data: base64Audio, mime_type: 'audio/wav' }
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": [
{"type": "text", "text": "What does this audio say?"},
{"type": "audio", "data": "'"$(base64 -w0 speech.wav)"'", "mime_type": "audio/wav"}
]
}'
Hiểu video
Python
import base64
from pathlib import Path
from google import genai
client = genai.Client()
# Read and encode the video
with open(Path(__file__).parent / "video.mp4", "rb") as f:
base64_video = base64.b64encode(f.read()).decode('utf-8')
print("Analyzing video...")
interaction = client.interactions.create(
model="gemini-2.5-flash",
input=[
{"type": "text", "text": "What is happening in this video? Provide a timestamped summary."},
{"type": "video", "data": base64_video, "mime_type": "video/mp4" }
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const base64Video = fs.readFileSync('video.mp4', { encoding: 'base64' });
console.log('Analyzing video...');
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: [
{ type: 'text', text: 'What is happening in this video? Provide a timestamped summary.' },
{ type: 'video', data: base64Video, mime_type: 'video/mp4'}
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": [
{"type": "text", "text": "What is happening in this video?"},
{"type": "video", "mime_type": "video/mp4", "data": "'"$(base64 -w0 video.mp4)"'"}
]
}'
Tìm hiểu tài liệu (PDF)
Python
import base64
from google import genai
client = genai.Client()
with open("sample.pdf", "rb") as f:
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
interaction = client.interactions.create(
model="gemini-2.5-flash",
input=[
{"type": "text", "text": "What is this document about?"},
{"type": "document", "data": base64_pdf, "mime_type": "application/pdf"}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const base64Pdf = fs.readFileSync('sample.pdf', { encoding: 'base64' });
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: [
{ type: 'text', text: 'What is this document about?' },
{ type: 'document', data: base64Pdf, mime_type: 'application/pdf' }
],
});
console.log(interaction.outputs[0].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": [
{"type": "text", "text": "What is this document about?"},
{"type": "document", "data": "'"$(base64 -w0 sample.pdf)"'", "mime_type": "application/pdf"}
]
}'
Tạo nội dung đa phương thức
Bạn có thể sử dụng Interactions API để tạo đầu ra đa phương thức.
Tạo hình ảnh
Python
import base64
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-pro-image-preview",
input="Generate an image of a futuristic city.",
response_modalities=["IMAGE"]
)
for output in interaction.outputs:
if output.type == "image":
print(f"Generated image with mime_type: {output.mime_type}")
# Save the image
with open("generated_city.png", "wb") as f:
f.write(base64.b64decode(output.data))
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-pro-image-preview',
input: 'Generate an image of a futuristic city.',
response_modalities: ['IMAGE']
});
for (const output of interaction.outputs) {
if (output.type === 'image') {
console.log(`Generated image with mime_type: ${output.mime_type}`);
// Save the image
fs.writeFileSync('generated_city.png', Buffer.from(output.data, 'base64'));
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-pro-image-preview",
"input": "Generate an image of a futuristic city.",
"response_modalities": ["IMAGE"]
}'
Khả năng của trợ lý AI
Interactions API được thiết kế để xây dựng và tương tác với các tác nhân, đồng thời hỗ trợ tính năng gọi hàm, các công cụ tích hợp, đầu ra có cấu trúc và Giao thức ngữ cảnh mô hình (MCP).
Nhân viên hỗ trợ
Bạn có thể sử dụng các tác nhân chuyên biệt như deep-research-pro-preview-12-2025 cho các tác vụ phức tạp. Để tìm hiểu thêm về Gemini Deep Research Agent, hãy xem hướng dẫn về tính năng Nghiên cứu sâu.
Python
import time
from google import genai
client = genai.Client()
# 1. Start the Deep Research Agent
initial_interaction = client.interactions.create(
input="Research the history of the Google TPUs with a focus on 2025 and 2026.",
agent="deep-research-pro-preview-12-2025",
background=True
)
print(f"Research started. Interaction ID: {initial_interaction.id}")
# 2. Poll for results
while True:
interaction = client.interactions.get(initial_interaction.id)
print(f"Status: {interaction.status}")
if interaction.status == "completed":
print("\nFinal Report:\n", interaction.outputs[-1].text)
break
elif interaction.status in ["failed", "cancelled"]:
print(f"Failed with status: {interaction.status}")
break
time.sleep(10)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. Start the Deep Research Agent
const initialInteraction = await client.interactions.create({
input: 'Research the history of the Google TPUs with a focus on 2025 and 2026.',
agent: 'deep-research-pro-preview-12-2025',
background: true
});
console.log(`Research started. Interaction ID: ${initialInteraction.id}`);
// 2. Poll for results
while (true) {
const interaction = await client.interactions.get(initialInteraction.id);
console.log(`Status: ${interaction.status}`);
if (interaction.status === 'completed') {
console.log('\nFinal Report:\n', interaction.outputs[interaction.outputs.length - 1].text);
break;
} else if (['failed', 'cancelled'].includes(interaction.status)) {
console.log(`Failed with status: ${interaction.status}`);
break;
}
await new Promise(resolve => setTimeout(resolve, 10000));
}
REST
# 1. Start the Deep Research Agent
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"input": "Research the history of the Google TPUs with a focus on 2025 and 2026.",
"agent": "deep-research-pro-preview-12-2025",
"background": true
}'
# 2. Poll for results (Replace INTERACTION_ID with the ID from the previous interaction)
# curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID" \
# -H "x-goog-api-key: $GEMINI_API_KEY"
Công cụ và tính năng gọi hàm
Phần này giải thích cách sử dụng tính năng gọi hàm để xác định các công cụ tuỳ chỉnh và cách sử dụng các công cụ tích hợp của Google trong Interactions API.
Gọi hàm
Python
from google import genai
client = genai.Client()
# 1. Define the tool
def get_weather(location: str):
"""Gets the weather for a given location."""
return f"The weather in {location} is sunny."
weather_tool = {
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
},
"required": ["location"]
}
}
# 2. Send the request with tools
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="What is the weather in Paris?",
tools=[weather_tool]
)
# 3. Handle the tool call
for output in interaction.outputs:
if output.type == "function_call":
print(f"Tool Call: {output.name}({output.arguments})")
# Execute tool
result = get_weather(**output.arguments)
# Send result back
interaction = client.interactions.create(
model="gemini-2.5-flash",
previous_interaction_id=interaction.id,
input=[{
"type": "function_result",
"name": output.name,
"call_id": output.id,
"result": result
}]
)
print(f"Response: {interaction.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. Define the tool
const weatherTool = {
type: 'function',
name: 'get_weather',
description: 'Gets the weather for a given location.',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA' }
},
required: ['location']
}
};
// 2. Send the request with tools
let interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'What is the weather in Paris?',
tools: [weatherTool]
});
// 3. Handle the tool call
for (const output of interaction.outputs) {
if (output.type === 'function_call') {
console.log(`Tool Call: ${output.name}(${JSON.stringify(output.arguments)})`);
// Execute tool (Mocked)
const result = `The weather in ${output.arguments.location} is sunny.`;
// Send result back
interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
previous_interaction_id: interaction.id,
input: [{
type: 'function_result',
name: output.name,
call_id: output.id,
result: result
}]
});
console.log(`Response: ${interaction.outputs[interaction.outputs.length - 1].text}`);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "What is the weather in Paris?",
"tools": [{
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
},
"required": ["location"]
}
}]
}'
# Handle the tool call and send result back (Replace INTERACTION_ID and CALL_ID)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
# "model": "gemini-2.5-flash",
# "previous_interaction_id": "INTERACTION_ID",
# "input": [{
# "type": "function_result",
# "name": "get_weather",
# "call_id": "FUNCTION_CALL_ID",
# "result": "The weather in Paris is sunny."
# }]
# }'
Gọi hàm với trạng thái phía máy khách
Nếu không muốn sử dụng trạng thái phía máy chủ, bạn có thể quản lý tất cả trạng thái đó ở phía máy khách.
Python
from google import genai
client = genai.Client()
functions = [
{
"type": "function",
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {"type": "array", "items": {"type": "string"}},
"date": {"type": "string", "description": "Date of the meeting (e.g., 2024-07-29)"},
"time": {"type": "string", "description": "Time of the meeting (e.g., 15:00)"},
"topic": {"type": "string", "description": "The subject of the meeting."},
},
"required": ["attendees", "date", "time", "topic"],
},
}
]
history = [{"role": "user","content": [{"type": "text", "text": "Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen API."}]}]
# 1. Model decides to call the function
interaction = client.interactions.create(
model="gemini-2.5-flash",
input=history,
tools=functions
)
# add model interaction back to history
history.append({"role": "model", "content": interaction.outputs})
for output in interaction.outputs:
if output.type == "function_call":
print(f"Function call: {output.name} with arguments {output.arguments}")
# 2. Execute the function and get a result
# In a real app, you would call your function here.
# call_result = schedule_meeting(**json.loads(output.arguments))
call_result = "Meeting scheduled successfully."
# 3. Send the result back to the model
history.append({"role": "user", "content": [{"type": "function_result", "name": output.name, "call_id": output.id, "result": call_result}]})
interaction2 = client.interactions.create(
model="gemini-2.5-flash",
input=history,
)
print(f"Final response: {interaction2.outputs[-1].text}")
else:
print(f"Output: {output}")
JavaScript
// 1. Define the tool
const functions = [
{
type: 'function',
name: 'schedule_meeting',
description: 'Schedules a meeting with specified attendees at a given time and date.',
parameters: {
type: 'object',
properties: {
attendees: { type: 'array', items: { type: 'string' } },
date: { type: 'string', description: 'Date of the meeting (e.g., 2024-07-29)' },
time: { type: 'string', description: 'Time of the meeting (e.g., 15:00)' },
topic: { type: 'string', description: 'The subject of the meeting.' },
},
required: ['attendees', 'date', 'time', 'topic'],
},
},
];
const history = [
{ role: 'user', content: [{ type: 'text', text: 'Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen API.' }] }
];
// 2. Model decides to call the function
let interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: history,
tools: functions
});
// add model interaction back to history
history.push({ role: 'model', content: interaction.outputs });
for (const output of interaction.outputs) {
if (output.type === 'function_call') {
console.log(`Function call: ${output.name} with arguments ${JSON.stringify(output.arguments)}`);
// 3. Send the result back to the model
history.push({ role: 'user', content: [{ type: 'function_result', name: output.name, call_id: output.id, result: 'Meeting scheduled successfully.' }] });
const interaction2 = await client.interactions.create({
model: 'gemini-2.5-flash',
input: history,
});
console.log(`Final response: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
}
}
Công cụ tích hợp
Gemini được trang bị các công cụ tích hợp như Căn cứ vào thông tin trên Google Tìm kiếm, Thực thi mã và Ngữ cảnh URL.
Kết nối với Google Tìm kiếm
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="Who won the last Super Bowl?",
tools=[{"type": "google_search"}]
)
# Find the text output (not the GoogleSearchResultContent)
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
print(text_output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'Who won the last Super Bowl?',
tools: [{ type: 'google_search' }]
});
// Find the text output (not the GoogleSearchResultContent)
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "Who won the last Super Bowl?",
"tools": [{"type": "google_search"}]
}'
Thực thi mã
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="Calculate the 50th Fibonacci number.",
tools=[{"type": "code_execution"}]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'Calculate the 50th Fibonacci number.',
tools: [{ type: 'code_execution' }]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "Calculate the 50th Fibonacci number.",
"tools": [{"type": "code_execution"}]
}'
Bối cảnh URL
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="Summarize the content of https://www.wikipedia.org/",
tools=[{"type": "url_context"}]
)
# Find the text output (not the URLContextResultContent)
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
print(text_output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'Summarize the content of https://www.wikipedia.org/',
tools: [{ type: 'url_context' }]
});
// Find the text output (not the URLContextResultContent)
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "Summarize the content of https://www.wikipedia.org/",
"tools": [{"type": "url_context"}]
}'
Giao thức ngữ cảnh Mô hình từ xa (MCP)
Việc tích hợp MCP từ xa giúp đơn giản hoá quá trình phát triển tác nhân bằng cách cho phép Gemini API trực tiếp gọi các công cụ bên ngoài được lưu trữ trên máy chủ từ xa.
Python
from google import genai
client = genai.Client()
mcp_server = {
"type": "mcp_server",
"name": "weather_service",
"url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
}
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="What is the weather like in New York today?",
tools=[mcp_server]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const mcpServer = {
type: 'mcp_server',
name: 'weather_service',
url: 'https://gemini-api-demos.uc.r.appspot.com/mcp'
};
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'What is the weather like in New York today?',
tools: [mcpServer]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "What is the weather like in New York today?",
"tools": [{
"type": "mcp_server",
"name": "weather_service",
"url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
}]
}'
Đầu ra có cấu trúc (giản đồ JSON)
Thực thi một đầu ra JSON cụ thể bằng cách cung cấp một giản đồ JSON trong tham số response_format. Điều này hữu ích cho các tác vụ như kiểm duyệt, phân loại hoặc trích xuất dữ liệu.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import Literal, Union
client = genai.Client()
class SpamDetails(BaseModel):
reason: str = Field(description="The reason why the content is considered spam.")
spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"]
class NotSpamDetails(BaseModel):
summary: str = Field(description="A brief summary of the content.")
is_safe: bool = Field(description="Whether the content is safe for all audiences.")
class ModerationResult(BaseModel):
decision: Union[SpamDetails, NotSpamDetails]
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format=ModerationResult.model_json_schema(),
)
parsed_output = ModerationResult.model_validate_json(interaction.outputs[-1].text)
print(parsed_output)
JavaScript
import { GoogleGenAI } from '@google/genai';
import { z } from 'zod';
const client = new GoogleGenAI({});
const moderationSchema = z.object({
decision: z.union([
z.object({
reason: z.string().describe('The reason why the content is considered spam.'),
spam_type: z.enum(['phishing', 'scam', 'unsolicited promotion', 'other']).describe('The type of spam.'),
}).describe('Details for content classified as spam.'),
z.object({
summary: z.string().describe('A brief summary of the content.'),
is_safe: z.boolean().describe('Whether the content is safe for all audiences.'),
}).describe('Details for content classified as not spam.'),
]),
});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: "Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format: z.toJSONSchema(moderationSchema),
});
console.log(interaction.outputs[0].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
"response_format": {
"type": "object",
"properties": {
"decision": {
"type": "object",
"properties": {
"reason": {"type": "string", "description": "The reason why the content is considered spam."},
"spam_type": {"type": "string", "description": "The type of spam."}
},
"required": ["reason", "spam_type"]
}
},
"required": ["decision"]
}
}'
Kết hợp các công cụ và đầu ra có cấu trúc
Kết hợp các công cụ tích hợp với đầu ra có cấu trúc để nhận được một đối tượng JSON đáng tin cậy dựa trên thông tin do một công cụ truy xuất.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import Literal, Union
client = genai.Client()
class SpamDetails(BaseModel):
reason: str = Field(description="The reason why the content is considered spam.")
spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"]
class NotSpamDetails(BaseModel):
summary: str = Field(description="A brief summary of the content.")
is_safe: bool = Field(description="Whether the content is safe for all audiences.")
class ModerationResult(BaseModel):
decision: Union[SpamDetails, NotSpamDetails]
interaction = client.interactions.create(
model="gemini-3-pro-preview",
input="Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format=ModerationResult.model_json_schema(),
tools=[{"type": "url_context"}]
)
parsed_output = ModerationResult.model_validate_json(interaction.outputs[-1].text)
print(parsed_output)
JavaScript
import { GoogleGenAI } from '@google/genai';
import { z } from 'zod'; // Assuming zod is used for schema generation, or define manually
const client = new GoogleGenAI({});
const obj = z.object({
winning_team: z.string(),
score: z.string(),
});
const schema = z.toJSONSchema(obj);
const interaction = await client.interactions.create({
model: 'gemini-3-pro-preview',
input: 'Who won the last euro?',
tools: [{ type: 'google_search' }],
response_format: schema,
});
console.log(interaction.outputs[0].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-pro-preview",
"input": "Who won the last euro?",
"tools": [{"type": "google_search"}],
"response_format": {
"type": "object",
"properties": {
"winning_team": {"type": "string"},
"score": {"type": "string"}
}
}
}'
Các tính năng nâng cao
Ngoài ra, còn có các tính năng nâng cao khác giúp bạn linh hoạt hơn khi làm việc với Interactions API.
Phát trực tiếp
Nhận câu trả lời theo từng phần khi câu trả lời được tạo.
Python
from google import genai
client = genai.Client()
stream = client.interactions.create(
model="gemini-2.5-flash",
input="Explain quantum entanglement in simple terms.",
stream=True
)
for chunk in stream:
if chunk.event_type == "content.delta":
if chunk.delta.type == "text":
print(chunk.delta.text, end="", flush=True)
elif chunk.delta.type == "thought":
print(chunk.delta.thought, end="", flush=True)
elif chunk.event_type == "interaction.complete":
print(f"\n\n--- Stream Finished ---")
print(f"Total Tokens: {chunk.interaction.usage.total_tokens}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const stream = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'Explain quantum entanglement in simple terms.',
stream: true,
});
for await (const chunk of stream) {
if (chunk.event_type === 'content.delta') {
if (chunk.delta.type === 'text' && 'text' in chunk.delta) {
process.stdout.write(chunk.delta.text);
} else if (chunk.delta.type === 'thought' && 'thought' in chunk.delta) {
process.stdout.write(chunk.delta.thought);
}
} else if (chunk.event_type === 'interaction.complete') {
console.log('\n\n--- Stream Finished ---');
console.log(`Total Tokens: ${chunk.interaction.usage.total_tokens}`);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "Explain quantum entanglement in simple terms.",
"stream": true
}'
Cấu hình
Tuỳ chỉnh hành vi của mô hình bằng generation_config.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="Tell me a story about a brave knight.",
generation_config={
"temperature": 0.7,
"max_output_tokens": 500,
"thinking_level": "low",
}
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'Tell me a story about a brave knight.',
generation_config: {
temperature: 0.7,
max_output_tokens: 500,
thinking_level: 'low',
}
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "Tell me a story about a brave knight.",
"generation_config": {
"temperature": 0.7,
"max_output_tokens": 500,
"thinking_level": "low"
}
}'
Làm việc với tệp
Làm việc với các tệp từ xa
Truy cập trực tiếp vào các tệp bằng URL từ xa trong lệnh gọi API.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-flash",
input=[
{
"type": "image",
"uri": "https://github.com/<github-path>/cats-and-dogs.jpg",
},
{"type": "text", "text": "Describe what you see."}
],
)
for output in interaction.outputs:
if output.type == "text":
print(output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: [
{
type: 'image',
uri: 'https://github.com/<github-path>/cats-and-dogs.jpg',
},
{ type: 'text', text: 'Describe what you see.' }
],
});
for (const output of interaction.outputs) {
if (output.type === 'text') {
console.log(output.text);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": [
{
"type": "image",
"uri": "https://github.com/<github-path>/cats-and-dogs.jpg"
},
{"type": "text", "text": "Describe what you see."}
]
}'
Làm việc với Gemini Files API
Tải tệp lên Files API của Gemini trước khi sử dụng.
Python
from google import genai
import time
import requests
client = genai.Client()
# 1. Download the file
url = "https://github.com/philschmid/gemini-samples/raw/refs/heads/main/assets/cats-and-dogs.jpg"
response = requests.get(url)
with open("cats-and-dogs.jpg", "wb") as f:
f.write(response.content)
# 2. Upload to Gemini Files API
file = client.files.upload(file="cats-and-dogs.jpg")
# 3. Wait for processing
while client.files.get(name=file.name).state != "ACTIVE":
time.sleep(2)
# 4. Use in Interaction
interaction = client.interactions.create(
model="gemini-2.5-flash",
input=[
{
"type": "image",
"uri": file.uri,
},
{"type": "text", "text": "Describe what you see."}
],
)
for output in interaction.outputs:
if output.type == "text":
print(output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
import fetch from 'node-fetch';
const client = new GoogleGenAI({});
// 1. Download the file
const url = 'https://github.com/philschmid/gemini-samples/raw/refs/heads/main/assets/cats-and-dogs.jpg';
const filename = 'cats-and-dogs.jpg';
const response = await fetch(url);
const buffer = await response.buffer();
fs.writeFileSync(filename, buffer);
// 2. Upload to Gemini Files API
const myfile = await client.files.upload({ file: filename, config: { mimeType: 'image/jpeg' } });
// 3. Wait for processing
while ((await client.files.get({ name: myfile.name })).state !== 'ACTIVE') {
await new Promise(resolve => setTimeout(resolve, 2000));
}
// 4. Use in Interaction
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: [
{ type: 'image', uri: myfile.uri, },
{ type: 'text', text: 'Describe what you see.' }
],
});
for (const output of interaction.outputs) {
if (output.type === 'text') {
console.log(output.text);
}
}
REST
# 1. Upload the file (Requires File API setup)
# See https://ai.google.dev/gemini-api/docs/files for details.
# Assume FILE_URI is obtained from the upload step.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": [
{"type": "image", "uri": "FILE_URI"},
{"type": "text", "text": "Describe what you see."}
]
}'
Mô hình dữ liệu
Bạn có thể tìm hiểu thêm về mô hình dữ liệu trong Tài liệu tham khảo API. Sau đây là thông tin tổng quan cấp cao về các thành phần chính.
Tương tác
| Thuộc tính | Loại | Mô tả |
|---|---|---|
id |
string |
Giá trị nhận dạng riêng biệt của lượt tương tác. |
model/agent |
string |
Mô hình hoặc tác nhân được sử dụng. Bạn chỉ có thể cung cấp một giá trị. |
input |
Content[] |
Các dữ liệu đầu vào được cung cấp. |
outputs |
Content[] |
Câu trả lời của mô hình. |
tools |
Tool[] |
Các công cụ được sử dụng. |
previous_interaction_id |
string |
Mã nhận dạng của lượt tương tác trước đó để biết bối cảnh. |
stream |
boolean |
Liệu hoạt động tương tác có đang phát trực tuyến hay không. |
status |
string |
Trạng thái: completed, in_progress, requires_action,failed, v.v. |
background |
boolean |
Liệu hoạt động tương tác có ở chế độ nền hay không. |
store |
boolean |
Có lưu trữ hoạt động tương tác hay không. Mặc định: true. Đặt thành false để chọn không sử dụng. |
usage |
Tác dụng | Mức sử dụng mã thông báo của yêu cầu tương tác. |
Các mô hình và tác nhân được hỗ trợ
| Tên mô hình | Loại | Mã kiểu máy |
|---|---|---|
| Gemini 2.5 Pro | Mô hình | gemini-2.5-pro |
| Gemini 2.5 Flash | Mô hình | gemini-2.5-flash |
| Gemini 2.5 Flash-lite | Mô hình | gemini-2.5-flash-lite |
| Bản dùng thử Gemini 3 Pro | Mô hình | gemini-3-pro-preview |
| Bản dùng thử Deep Research | Nhân viên hỗ trợ | deep-research-pro-preview-12-2025 |
Cách hoạt động của Interactions API
Interactions API được thiết kế dựa trên một tài nguyên trung tâm: Interaction.
Interaction biểu thị một lượt hoàn thành trong cuộc trò chuyện hoặc nhiệm vụ. Nó hoạt động như một bản ghi phiên, chứa toàn bộ nhật ký của một hoạt động tương tác, bao gồm tất cả hoạt động đầu vào của người dùng, suy nghĩ của mô hình, lệnh gọi công cụ, kết quả công cụ và đầu ra cuối cùng của mô hình.
Khi thực hiện lệnh gọi đến interactions.create, bạn sẽ tạo một tài nguyên Interaction mới.
Bạn có thể sử dụng id của tài nguyên này trong một lệnh gọi tiếp theo bằng cách sử dụng tham số previous_interaction_id để tiếp tục cuộc trò chuyện. Máy chủ sử dụng mã nhận dạng này để truy xuất toàn bộ ngữ cảnh, giúp bạn không phải gửi lại toàn bộ nhật ký trò chuyện. Bạn không bắt buộc phải quản lý trạng thái phía máy chủ; bạn cũng có thể hoạt động ở chế độ không trạng thái bằng cách gửi toàn bộ nhật ký trò chuyện trong mỗi yêu cầu.
Lưu trữ và giữ lại dữ liệu
Theo mặc định, tất cả các đối tượng Tương tác đều được lưu trữ (store=true) để đơn giản hoá việc sử dụng các tính năng quản lý trạng thái phía máy chủ (với previous_interaction_id), thực thi trong nền (bằng background=true) và mục đích quan sát.
- Gói trả phí: Các lượt tương tác được giữ lại trong 55 ngày.
- Bậc miễn phí: Các lượt tương tác được giữ lại trong 1 ngày.
Nếu không muốn như vậy, bạn có thể đặt store=false trong yêu cầu của mình. Chế độ kiểm soát này tách biệt với hoạt động quản lý trạng thái; bạn có thể chọn không lưu trữ cho bất kỳ hoạt động tương tác nào. Tuy nhiên, xin lưu ý rằng store=false không tương thích với background=true và ngăn việc sử dụng previous_interaction_id cho các lượt tiếp theo.
Bạn có thể xoá các hoạt động tương tác đã lưu trữ bất cứ lúc nào bằng phương thức xoá trong Tài liệu tham khảo API. Bạn chỉ có thể xoá các hoạt động tương tác nếu biết mã nhận dạng của hoạt động tương tác đó.
Sau khi hết khoảng thời gian lưu giữ, dữ liệu của bạn sẽ tự động bị xoá.
Các đối tượng tương tác được xử lý theo điều khoản.
Các phương pháp hay nhất
- Tỷ lệ truy cập bộ nhớ đệm: Việc sử dụng
previous_interaction_idđể tiếp tục cuộc trò chuyện cho phép hệ thống dễ dàng sử dụng tính năng lưu vào bộ nhớ đệm ngầm cho nhật ký trò chuyện, giúp cải thiện hiệu suất và giảm chi phí. - Kết hợp các lượt tương tác: Bạn có thể linh hoạt kết hợp các lượt tương tác giữa Nhân viên hỗ trợ và Mô hình trong một cuộc trò chuyện. Ví dụ: bạn có thể sử dụng một tác nhân chuyên biệt (chẳng hạn như tác nhân Nghiên cứu chuyên sâu) để thu thập dữ liệu ban đầu, sau đó sử dụng một mô hình Gemini tiêu chuẩn cho các tác vụ tiếp theo như tóm tắt hoặc định dạng lại, liên kết các bước này với
previous_interaction_id.
SDK
Bạn có thể sử dụng phiên bản mới nhất của SDK Google GenAI để truy cập vào Interactions API.
- Trên Python, đây là gói
google-genaitừ phiên bản1.55.0trở đi. - Trên JavaScript, đây là gói
@google/genaitừ phiên bản1.33.0trở lên.
Bạn có thể tìm hiểu thêm về cách cài đặt SDK trên trang Thư viện.
Các điểm hạn chế
- Trạng thái thử nghiệm: Interactions API đang ở giai đoạn thử nghiệm/xem trước. Các tính năng và lược đồ có thể thay đổi.
Các tính năng không được hỗ trợ: Các tính năng sau chưa được hỗ trợ nhưng sẽ sớm ra mắt:
Sắp xếp đầu ra: Thứ tự nội dung cho các công cụ tích hợp (
google_searchvàurl_context) đôi khi có thể không chính xác, với văn bản xuất hiện trước khi thực thi công cụ và kết quả. Chúng tôi đã biết vấn đề này và đang tìm cách khắc phục.Kết hợp các công cụ: Hệ thống hiện chưa hỗ trợ việc kết hợp MCP, Lệnh gọi hàm và các công cụ tích hợp nhưng sẽ sớm ra mắt tính năng này.
MCP từ xa: Gemini 3 không hỗ trợ MCP từ xa, tính năng này sẽ sớm ra mắt.
Thay đổi có thể gây lỗi
Interactions API hiện đang ở giai đoạn thử nghiệm beta ban đầu. Chúng tôi đang tích cực phát triển và tinh chỉnh các chức năng API, lược đồ tài nguyên và giao diện SDK dựa trên mức sử dụng thực tế và ý kiến phản hồi của nhà phát triển.
Do đó, có thể xảy ra các thay đổi có thể gây lỗi. Nội dung cập nhật có thể bao gồm những thay đổi đối với:
- Lược đồ cho đầu vào và đầu ra.
- Chữ ký phương thức và cấu trúc đối tượng của SDK.
- Hành vi của một số tính năng cụ thể.
Đối với các khối lượng công việc sản xuất, bạn nên tiếp tục sử dụng API generateContent tiêu chuẩn. Đây vẫn là đường dẫn được đề xuất cho các hoạt động triển khai ổn định và sẽ tiếp tục được phát triển và duy trì một cách tích cực.
Phản hồi
Ý kiến phản hồi của bạn đóng vai trò quan trọng trong quá trình phát triển Interactions API. Vui lòng chia sẻ ý kiến, báo cáo lỗi hoặc yêu cầu tính năng trên Diễn đàn cộng đồng nhà phát triển AI của Google.
Bước tiếp theo
- Tìm hiểu thêm về Tác nhân Deep Research của Gemini.