Loading...
Loading...
Compare original and translation side by side
[!IMPORTANT] CRITICAL: Unified SDK & Latest Models
- Unified SDK: Use the Google Gen AI SDK (
for Python,google-genai >= 2.0.0for JS/TS). Legacy SDKs like@google/genai >= 2.0.0,google-cloud-aiplatform, and@google-cloud/vertexaiare strictly unsupported for Interactions.google-generativeai- Latest Models Only: Use
,gemini-3.1-pro-preview,gemini-3.1-flash-lite,gemini-3-flash-preview, orgemini-2.5-pro. Refer to the latest model versions to check for new updates. Legacy models (gemini-2.5-flash,gemini-2.0-*) are deprecated and do not support interactions.gemini-1.5-*- Turn-Scoped Parameters: Parameters like
,tools, andsystem_instructionare turn-scoped. They MUST be passed with each interaction request.generation_config
[!IMPORTANT] 重要提示:统一SDK与最新模型
- 统一SDK:请使用Google Gen AI SDK(Python版本需**
,JS/TS版本需google-genai >= 2.0.0**)。旧版SDK如@google/genai >= 2.0.0、google-cloud-aiplatform和@google-cloud/vertexai完全不支持Interactions功能。google-generativeai- 仅使用最新模型:请使用
、gemini-3.1-pro-preview、gemini-3.1-flash-lite、gemini-3-flash-preview或gemini-2.5-pro。可参考最新模型版本查看更新信息。旧版模型(gemini-2.5-flash、gemini-2.0-*)已被弃用,不支持Interactions功能。gemini-1.5-*- 轮次作用域参数:
、tools和system_instruction等参数属于轮次作用域,必须随每次交互请求一并传递。generation_config
gcloud auth application-default logingcloud services enable aiplatform.googleapis.comgcloud auth application-default logingcloud services enable aiplatform.googleapis.comexport GOOGLE_GENAI_USE_ENTERPRISE=true
export GOOGLE_CLOUD_PROJECT="your-project-id"
export GOOGLE_CLOUD_LOCATION="global"export GOOGLE_GENAI_USE_ENTERPRISE=true
export GOOGLE_CLOUD_PROJECT="your-project-id"
export GOOGLE_CLOUD_LOCATION="global"from google import genaifrom google import genaiundefinedundefinedimport { GoogleGenAI } from "@google/genai";
// The SDK automatically picks up the environment variables
const ai = new GoogleGenAI();import { GoogleGenAI } from "@google/genai";
// SDK会自动读取环境变量
const ai = new GoogleGenAI();from google import genai
import google.auth
_, project_id = google.auth.default()
client = genai.Client(enterprise=True, project=project_id, location="global")from google import genai
import google.auth
_, project_id = google.auth.default()
client = genai.Client(enterprise=True, project=project_id, location="global")import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: {
project: "your-project-id",
location: "global"
}
});import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: {
project: "your-project-id",
location: "global"
}
});stepsstepsinteraction = client.interactions.create(
model="gemini-3-flash-preview",
input="Explain serverless computing in one sentence."
)interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Explain serverless computing in one sentence."
)undefinedundefinedconst interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Explain serverless computing in one sentence."
});
console.log(interaction.steps[interaction.steps.length - 1].content[0].text);const interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Explain serverless computing in one sentence."
});
console.log(interaction.steps[interaction.steps.length - 1].content[0].text);previous_interaction_idprevious_interaction_idundefinedundefinedundefinedundefined// Turn 1
const turn1 = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Hi! My name is John. I am working on AI agents.",
store: true
});
// Turn 2
const turn2 = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "What is my name?",
previousInteractionId: turn1.id
});
console.log(turn2.steps[turn2.steps.length - 1].content[0].text);// 第一轮
const turn1 = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Hi! My name is John. I am working on AI agents.",
store: true
});
// 第二轮
const turn2 = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "What is my name?",
previousInteractionId: turn1.id
});
console.log(turn2.steps[turn2.steps.length - 1].content[0].text);stream=Truestream=Trueresponse = client.interactions.create(
model="gemini-3-flash-preview",
input="Write a short poem about debugging.",
stream=True
)
for chunk in response:
if chunk.steps:
step = chunk.steps[-1]
if step.content and step.content[0].text:
print(step.content[0].text, end="", flush=True)
print()response = client.interactions.create(
model="gemini-3-flash-preview",
input="Write a short poem about debugging.",
stream=True
)
for chunk in response:
if chunk.steps:
step = chunk.steps[-1]
if step.content and step.content[0].text:
print(step.content[0].text, end="", flush=True)
print()const responseStream = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Write a short poem about debugging.",
stream: true
});
for await (const chunk of responseStream) {
if (chunk.steps) {
const step = chunk.steps[chunk.steps.length - 1];
if (step.content && step.content[0].text) {
process.stdout.write(step.content[0].text);
}
}
}
console.log();const responseStream = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Write a short poem about debugging.",
stream: true
});
for await (const chunk of responseStream) {
if (chunk.steps) {
const step = chunk.steps[chunk.steps.length - 1];
if (step.content && step.content[0].text) {
process.stdout.write(step.content[0].text);
}
}
}
console.log();response_formatresponse_formatresponse_formatresponse_formatfrom pydantic import BaseModel, Field
class Book(BaseModel):
title: str = Field(description="The title of the book")
author: str = Field(description="The book's author")
year_published: int
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Recommend one famous sci-fi book.",
response_format=Book
)from pydantic import BaseModel, Field
class Book(BaseModel):
title: str = Field(description="The title of the book")
author: str = Field(description="The book's author")
year_published: int
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Recommend one famous sci-fi book.",
response_format=Book
)undefinedundefinedimport { Type } from "@google/genai";
const BookSchema = {
type: Type.OBJECT,
properties: {
title: { type: Type.STRING, description: "The title of the book" },
author: { type: Type.STRING, description: "The book's author" },
yearPublished: { type: Type.INTEGER }
},
required: ["title", "author", "yearPublished"]
};
const interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Recommend one famous sci-fi book.",
responseFormat: BookSchema
});
console.log(interaction.steps[interaction.steps.length - 1].content[0].text);import { Type } from "@google/genai";
const BookSchema = {
type: Type.OBJECT,
properties: {
title: { type: Type.STRING, description: "The title of the book" },
author: { type: Type.STRING, description: "The book's author" },
yearPublished: { type: Type.INTEGER }
},
required: ["title", "author", "yearPublished"]
};
const interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Recommend one famous sci-fi book.",
responseFormat: BookSchema
});
console.log(interaction.steps[interaction.steps.length - 1].content[0].text);def get_stock_price(ticker: str) -> float:
"""Gets the stock price for a given ticker symbol."""
if ticker.upper() == "GOOG":
return 175.50
return 100.0def get_stock_price(ticker: str) -> float:
"""Gets the stock price for a given ticker symbol."""
if ticker.upper() == "GOOG":
return 175.50
return 100.0 # Turn 2: Submit function execution result statefully
final_turn = client.interactions.create(
model="gemini-3-flash-preview",
input=f"The stock price for {ticker_arg} is ${price}.",
previous_interaction_id=interaction.id
)
print(final_turn.steps[-1].content[0].text)undefined # 第二轮:有状态地提交函数执行结果
final_turn = client.interactions.create(
model="gemini-3-flash-preview",
input=f"The stock price for {ticker_arg} is ${price}.",
previous_interaction_id=interaction.id
)
print(final_turn.steps[-1].content[0].text)undefinedimport { Type } from "@google/genai";
// Define local tool
function getStockPrice({ ticker }: { ticker: string }): number {
if (ticker.toUpperCase() === "GOOG") {
return 175.50;
}
return 100.00;
}
// Turn 1: Pass tools to the model
const interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "What is the stock price of GOOG?",
tools: [{
functionDeclarations: [{
name: "getStockPrice",
description: "Gets the stock price for a given ticker symbol.",
parameters: {
type: Type.OBJECT,
properties: {
ticker: { type: Type.STRING, description: "The stock ticker symbol" }
},
required: ["ticker"]
}
}]
}]
});
const lastStep = interaction.steps[interaction.steps.length - 1];
// Check if the model requested a function call
if (lastStep.toolCalls) {
for (const call of lastStep.toolCalls) {
if (call.name === "getStockPrice") {
const tickerArg = call.args.ticker as string;
const price = getStockPrice({ ticker: tickerArg });
// Turn 2: Submit function execution result statefully
const finalTurn = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: `The stock price for ${tickerArg} is $${price}.`,
previousInteractionId: interaction.id
});
console.log(finalTurn.steps[finalTurn.steps.length - 1].content[0].text);
}
}
}import { Type } from "@google/genai";
// 定义本地工具
function getStockPrice({ ticker }: { ticker: string }): number {
if (ticker.toUpperCase() === "GOOG") {
return 175.50;
}
return 100.00;
}
// 第一轮:向模型传递工具
const interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "What is the stock price of GOOG?",
tools: [{
functionDeclarations: [{
name: "getStockPrice",
description: "Gets the stock price for a given ticker symbol.",
parameters: {
type: Type.OBJECT,
properties: {
ticker: { type: Type.STRING, description: "The stock ticker symbol" }
},
required: ["ticker"]
}
}]
}]
});
const lastStep = interaction.steps[interaction.steps.length - 1];
// 检查模型是否请求了函数调用
if (lastStep.toolCalls) {
for (const call of lastStep.toolCalls) {
if (call.name === "getStockPrice") {
const tickerArg = call.args.ticker as string;
const price = getStockPrice({ ticker: tickerArg });
// 第二轮:有状态地提交函数执行结果
const finalTurn = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: `The stock price for ${tickerArg} is $${price}.`,
previousInteractionId: interaction.id
});
console.log(finalTurn.steps[finalTurn.steps.length - 1].content[0].text);
}
}
}curlcurlPOST https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/interactionsglobalPOST https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/interactionsglobalAGENT_ID="your-agent-id"
ACCESS_TOKEN=$(gcloud auth print-access-token)AGENT_ID="your-agent-id"
ACCESS_TOKEN=$(gcloud auth print-access-token)curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"agent": "'"${AGENT_ID}"'",
"input": [{
"role": "user",
"content": [{
"type": "text",
"text": "Explain serverless computing in one sentence."
}]
}]
}'curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"agent": "'"${AGENT_ID}"'",
"input": [{
"role": "user",
"content": [{
"type": "text",
"text": "Explain serverless computing in one sentence."
}]
}]
}'{
"id": "your-interaction-id",
"status": "completed",
"steps": [
{
"role": "model",
"content": [
{
"type": "text",
"text": "Serverless computing is a cloud execution model where the cloud provider dynamically manages the allocation and provisioning of servers, charging customers based on actual usage rather than pre-purchased capacity."
}
]
}
],
"usage": {
"total_tokens": 24751,
"total_input_tokens": 23894,
"total_output_tokens": 857
},
"created": "2026-05-08T10:44:43Z",
"updated": "2026-05-08T10:44:43Z",
"environment_id": "your-environment-id",
"object": "interaction"
}{
"id": "your-interaction-id",
"status": "completed",
"steps": [
{
"role": "model",
"content": [
{
"type": "text",
"text": "Serverless computing is a cloud execution model where the cloud provider dynamically manages the allocation and provisioning of servers, charging customers based on actual usage rather than pre-purchased capacity."
}
]
}
],
"usage": {
"total_tokens": 24751,
"total_input_tokens": 23894,
"total_output_tokens": 857
},
"created": "2026-05-08T10:44:43Z",
"updated": "2026-05-08T10:44:43Z",
"environment_id": "your-environment-id",
"object": "interaction"
}previous_interaction_idcurl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"agent": "'"${AGENT_ID}"'",
"store": true,
"previous_interaction_id": "YOUR_PREVIOUS_INTERACTION_ID",
"input": [{
"role": "user",
"content": [{
"type": "text",
"text": "Can you elaborate on that?"
}]
}]
}'previous_interaction_idcurl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"agent": "'"${AGENT_ID}"'",
"store": true,
"previous_interaction_id": "YOUR_PREVIOUS_INTERACTION_ID",
"input": [{
"role": "user",
"content": [{
"type": "text",
"text": "Can you elaborate on that?"
}]
}]
}'"stream": truecurl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"agent": "'"${AGENT_ID}"'",
"stream": true,
"input": [{
"role": "user",
"content": [{
"type": "text",
"text": "Write a long story about space travel."
}]
}]
}'data: event_typeHowhandles streaming: By default, whencurlis passed, the server responds with"stream": trueandTransfer-Encoding: chunked(Server-Sent Events).Content-Type: text/event-streamwill automatically keep the connection open and print the incoming data chunks tocurlin real time as they are pushed by the server. The user does not need to poll or pull further; the complete sequence of events streams continuously until completion.stdout
"stream": truecurl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"agent": "'"${AGENT_ID}"'",
"stream": true,
"input": [{
"role": "user",
"content": [{
"type": "text",
"text": "Write a long story about space travel."
}]
}]
}'data: event_typecurl处理流式传输的方式: 默认情况下,当传入时,服务器会返回"stream": true和Transfer-Encoding: chunked(Server-Sent Events)。curl会自动保持连接打开,并在服务器推送数据时实时将传入的数据分片打印到Content-Type: text/event-stream。用户无需轮询或进一步拉取,完整的事件序列会持续流式传输直至完成。stdout