對於長時間執行的工作 (例如深度研究、複雜推論或多步驟代理執行作業),連線逾時可能會中斷標準 HTTP 要求 (通常會在 60 秒後關閉)。Interactions API 提供背景執行功能,可非同步執行這些工作。
如要讓互動持續執行,直到伺服器完成工作為止,請在建立互動時設定 "background": true。API 會立即傳回互動 ID,用戶端應用程式可使用此 ID 輪詢狀態、串流進度,或重新連線至已中斷的串流。
標準 Gemini 模型 (例如 gemini-3.5-flash 和 gemini-3.1-pro-preview) 和代管代理程式 (例如 antigravity-preview-05-2026) 支援背景執行。
建立背景互動
如要啟動背景互動,請在建立資源時將 background 參數設為 true。
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.5-flash",
input="Write a guide on space exploration.",
background=True,
)
print(f"Created background interaction ID: {interaction.id}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3.5-flash",
input: "Write a guide on space exploration.",
background: true,
});
console.log(`Created background interaction ID: ${interaction.id}`);
REST
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.5-flash",
"input": "Write a guide on space exploration.",
"background": true
}'
背景執行的運作方式
建立背景互動時,工作會在伺服器上非同步執行。互動會經歷各種執行狀態:
in_progress:伺服器正在執行互動 (例如執行程式碼或研究)。requires_action:互動已暫停,等待用戶端輸入內容 (例如確認工具執行或回答問題)。completed:互動已順利完成,且輸出內容可用。failed:執行期間發生錯誤 (例如工具故障或超出速率限制)。cancelled:用戶端要求停止執行。
用途
背景執行功能適用於:
代理執行:需要執行程式碼、瀏覽網頁或協調子代理 (例如
antigravity-preview-05-2026) 的工作。Deep Research:使用
deep-research-preview-04-2026或deep-research-max-preview-04-2026執行,需要幾分鐘。長推論:模型思考步驟超出標準 HTTP 連線限制的工作。
擷取結果
使用輪詢或串流,取得背景互動結果。
輪詢模式 (非阻斷)
輪詢會使用非封鎖 GET 要求定期檢查互動狀態,直到達到終端狀態為止。
Python
import time
from google import genai
client = genai.Client()
interaction = client.interactions.get(id="YOUR_INTERACTION_ID")
while interaction.status == "in_progress":
time.sleep(5)
interaction = client.interactions.get(id=interaction.id)
if interaction.status == "completed":
print(interaction.output_text)
else:
print(f"Finished with status: {interaction.status}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
let interaction = await client.interactions.get("YOUR_INTERACTION_ID");
while (interaction.status === "in_progress") {
await new Promise(resolve => setTimeout(resolve, 5000));
interaction = await client.interactions.get(interaction.id);
}
if (interaction.status === "completed") {
console.log(interaction.output_text);
} else {
console.log(`Finished with status: ${interaction.status}`);
}
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20"
串流模式
如果網路中斷導致串流中斷,串流可以從上次收到的事件繼續。每個 delta 的酬載中都包含專屬的 event_id。將這個 ID 做為 last_event_id 傳遞,即可從該事件繼續串流。
Python
import time
from google import genai
client = genai.Client()
interaction_id = "YOUR_INTERACTION_ID"
def stream_with_reconnect(interaction_id: str):
last_event_id = None
while True:
try:
# Retrieve the stream. If resuming, pass last_event_id
stream = client.interactions.get(
id=interaction_id,
stream=True,
last_event_id=last_event_id
)
for event in stream:
# Log event updates and capture event_id if present
if event.event_id:
last_event_id = event.event_id
if event.event_type == "step.delta" and event.delta.type == "text":
print(event.delta.text, end="", flush=True)
if event.event_type == "interaction.completed":
return
except Exception as e:
print(f"\n[Connection lost: {e}. Reconnecting in 3s...]")
time.sleep(3)
stream_with_reconnect(interaction_id)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interactionId = "YOUR_INTERACTION_ID";
async function streamWithReconnect(id) {
let lastEventId = undefined;
while (true) {
try {
// Retrieve the stream. If resuming, pass last_event_id in options
const stream = await client.interactions.get(id, {
stream: true,
last_event_id: lastEventId
});
for await (const event of stream) {
// Capture event_id if present
const idVal = event.event_id || event.id;
if (idVal) {
lastEventId = idVal;
}
if (event.event_type === "step.delta" && event.delta?.type === "text") {
process.stdout.write(event.delta.text);
}
if (event.event_type === "interaction.completed") {
return;
}
}
} catch (error) {
console.log(`\n[Connection lost: ${error.message}. Reconnecting in 3s...]`);
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
}
await streamWithReconnect(interactionId);
REST
curl -N -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID?stream=true&last_event_id=YOUR_LAST_EVENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20"
多轉折對話
後續互動可使用 previous_interaction_id 鏈結至背景對話,但須遵守下列限制:
- 封鎖有效執行作業:將後續互動鏈結至狀態為
in_progress的互動,會傳回400 Bad Request錯誤。請等待互動達到completed狀態,再開始下一個互動。 - 受管理代理程式的環境參數:為受管理代理程式串連互動 (例如
antigravity-preview-05-2026) 時,要求必須同時包含previous_interaction_id和environment。
以下範例說明如何串連互動:
Python
import time
from google import genai
client = genai.Client()
agent_model = "antigravity-preview-05-2026"
# First interaction: Provision sandbox environment and execute first instruction
interaction1 = client.interactions.create(
model=agent_model,
input="Create a folder named project/ and write hello.py inside.",
environment="remote",
background=True
)
# Wait for completion
while True:
check = client.interactions.get(id=interaction1.id)
if check.status != "in_progress":
break
time.sleep(2)
# Second interaction: Chain using previous_interaction_id and environment
interaction2 = client.interactions.create(
model=agent_model,
input="List all files in the project/ directory.",
previous_interaction_id=interaction1.id,
environment="remote",
background=True
)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const agentModel = "antigravity-preview-05-2026";
// First interaction: Provision sandbox environment and execute first instruction
const interaction1 = await client.interactions.create({
model: agentModel,
input: "Create a folder named project/ and write hello.py inside.",
environment: "remote",
background: true
});
// Wait for completion
while (true) {
const check = await client.interactions.get(interaction1.id);
if (check.status !== "in_progress") {
break;
}
await new Promise(resolve => setTimeout(resolve, 2000));
}
// Second interaction: Chain using previous_interaction_id and environment
const interaction2 = await client.interactions.create({
model: agentModel,
input: "List all files in the project/ directory.",
previous_interaction_id: interaction1.id,
environment: "remote",
background: true
});
REST
# Chain second interaction (Make sure FIRST_INTERACTION_ID has status 'completed')
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": "antigravity-preview-05-2026",
"input": "List all files in the project/ directory.",
"previous_interaction_id": "FIRST_INTERACTION_ID",
"environment": "remote",
"background": true
}'
取消和刪除
使用取消和刪除要求控制執行作業並管理儲存空間:
- 取消 (
POST /interactions/{id}/cancel):停止執行中的工作。狀態會轉換為cancelled。伺服器上的清除動作可能會導致 GET 要求中的狀態更新稍微延遲。 刪除 (
DELETE /interactions/{id}):從伺服器移除互動記錄。後續的 GET 要求會傳回404 Not Found錯誤。
Python
from google import genai
client = genai.Client()
# Cancel a running interaction
client.interactions.cancel(id="YOUR_INTERACTION_ID")
# Delete the interaction record entirely
client.interactions.delete(id="YOUR_INTERACTION_ID")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
// Cancel a running interaction
await client.interactions.cancel("YOUR_INTERACTION_ID");
// Delete the interaction record entirely
await client.interactions.delete("YOUR_INTERACTION_ID");
REST
# Cancel the interaction
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID/cancel" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20"
# Delete the interaction
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20"
後續步驟
- 請參閱「Interactions API 總覽」,瞭解工作階段和狀態管理。
- 如要進一步瞭解即時事件更新,請參閱「串流互動」指南。
- 請參閱代管型代理程式快速入門指南,建構有狀態的多輪對話代理程式。