このガイドでは、Interactions API を使用して Gemini API を使い始める方法について説明します。1 分以内に最初の API 呼び出しを行い、テキスト生成、マルチモーダルな理解、画像生成、構造化出力、ツール、関数呼び出し、エージェント、バックグラウンド実行について説明します。
Interactions API は、Python SDK、JavaScript SDK、REST を介して利用できます。
1. API キーを取得する
Gemini API を使用するには、API キーが必要です。無料で作成して開始しましょう。
次に、それを環境変数として設定します。
export GEMINI_API_KEY="YOUR_API_KEY"
2. SDK をインストールして最初の呼び出しを行う
SDK をインストールし、1 回の API 呼び出しでテキストを生成します。
Python
SDK をインストールします。
pip install -U google-genai
クライアントを初期化してリクエストを行います。
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.5-flash",
input="Explain how AI works in a few words"
)
print(interaction.output_text)
JavaScript
SDK をインストールします。
npm install @google/genai
クライアントを初期化してリクエストを行います。
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Explain how AI works in a few words",
});
console.log(interaction.output_text);
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": "Explain how AI works in a few words"
}'
回答:
{
"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.5-flash",
}
REST を使用すると、API はメタデータ、使用状況の統計情報、ターンのステップごとの履歴を含む完全な Interaction リソースを返します。
SDK は完全なレスポンスを公開しますが、interaction.output_text や interaction.output_image などの便利なプロパティを使用して、最終的な出力に直接アクセスすることもできます。レスポンス構造の詳細については、Interactions の概要をご覧ください。システム命令と生成構成の詳細については、テキスト生成ガイドをご覧ください。
3. レスポンスをストリーミングする
よりスムーズなインタラクションを実現するには、レスポンスが生成されたときにストリーミングします。各 step.delta イベントは、すぐに表示できるテキストのチャンクを配信します。
Python
from google import genai
client = genai.Client()
stream = client.interactions.create(
model="gemini-3.5-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.5-flash",
input: "Explain how AI works",
stream: true,
});
for await (const event of stream) {
console.log(event);
}
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' \
-H "Api-Revision: 2026-05-20" \
--no-buffer \
-d '{
"model": "gemini-3.5-flash",
"input": "Explain how AI works",
"stream": true
}'
ストリーミングを行うと、サーバーはサーバー送信イベント(SSE)のストリームで応答します。各イベントには、タイプと JSON データが含まれます。
回答:
event: interaction.created
data: {"interaction":{"id":"v1_Chd...","status":"in_progress","model":"gemini-3.5-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"}
ストリーミング イベントとデルタタイプの処理の詳細については、ストリーミング インタラクション ガイドをご覧ください。
4. マルチターンの会話
Interactions API は、次の 2 つの方法でマルチターンの会話をサポートしています。
- ステートフル(推奨):
previous_interaction_idを使用して、サーバーで会話を続けます。サーバーで履歴を管理し、キャッシュを最適化する場合に最適な、ほとんどのチャットとエージェントのワークフローに適しています。 ステートレス: 各リクエストで以前のすべてのターン(中間モデルの思考とツールのステップを含む)を渡すことで、クライアントで会話履歴を管理します。
ステートフル(推奨)
previous_interaction_id を渡してインタラクションをチェーンします。サーバーが会話履歴全体を管理します。
Python
from google import genai
client = genai.Client()
# Server-side state (recommended)
interaction1 = client.interactions.create(
model="gemini-3.5-flash",
input="I have 2 dogs in my house.",
)
print("Response 1:", interaction1.output_text)
interaction2 = client.interactions.create(
model="gemini-3.5-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({});
// Server-side state (recommended)
const interaction1 = await ai.interactions.create({
model: "gemini-3.5-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.5-flash",
input: "How many paws are in my house?",
previous_interaction_id: interaction1.id,
});
console.log("Response 2:", interaction2.output_text);
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' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.5-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' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.5-flash",
"input": "How many paws are in my house?",
"previous_interaction_id": "'$INTERACTION_ID'"
}'
ステートレス
store=false を設定し、クライアント側で会話履歴を管理します。モデルによって生成されたすべてのステップ(thought ステップと 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.5-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.5-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.5-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.5-flash",
store: false,
input: history
});
console.log("Response 2:", interaction2.steps.at(-1).content[0].text);
REST
# Turn 1: Send with 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' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.5-flash",
"store": false,
"input": [
{
"type": "user_input",
"content": "I have 2 dogs in my house."
}
]
}')
MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')
# Turn 2: Build full history
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' \
-H "Api-Revision: 2026-05-20" \
-d "{
\"model\": \"gemini-3.5-flash\",
\"store\": false,
\"input\": $HISTORY
}"
回答:
{
"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.5-flash"
}
2 回目のインタラクションでは、新しいステップのみを含む完全なレスポンス オブジェクトが返されますが、前のターンのコンテキストに基づいています。マルチターンの会話ガイドで状態を維持する方法について学習するか、クライアントサイドの履歴管理にステートレス モードを使用してください。
5. マルチモーダルな理解
Gemini モデルは、画像、音声、動画、ドキュメントをネイティブに理解します。1 つのリクエストでテキストとともにメディアを渡します。
Python
import base64
from google import genai
client = genai.Client()
# Load a local image
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.5-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({});
// Load a local image
const imageBytes = fs.readFileSync("sample.jpg");
const imageB64 = imageBytes.toString("base64");
const interaction = await ai.interactions.create({
model: "gemini-3.5-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);
REST
# Base64-encode local image
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.5-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"
}
]
}'
回答:
{
"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.5-flash",
}
画像理解ガイドで、画像、動画、音声ファイルを渡す方法を確認してください。
音声の理解
音声ファイルの文字起こし、要約、質問への回答を行います。
動画理解
動画コンテンツの分析、イベントの特定、アクションの説明を行います。
ドキュメント処理
PDF やその他のドキュメント形式から情報を抽出します。
6. マルチモーダル生成
Gemini は、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);
}
REST
curl -s -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.1-flash-image",
"input": [
{"type": "text", "text": "Generate an image of a futuristic city skyline at sunset"}
]
}'
回答:
{
"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",
}
モデルが画像を生成すると、steps 配列内のステップと output_image 便利なプロパティを介して、base64 エンコードされた画像データが返されます。アスペクト比、画像編集、参照については、画像生成ガイドをご覧ください。
7. 構造化出力を使用する
定義したスキーマに一致する JSON を返すようにモデルを構成します。構造化出力は、Pydantic(Python)と 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.5-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.5-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);
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": "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"]
}
}
}'
回答:
{
"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.5-flash",
}
出力テキスト ブロックには、リクエストされたスキーマに正確に準拠した有効な JSON 文字列が含まれています。より複雑な構造と再帰スキーマを定義する方法については、構造化出力ガイドをご覧ください。
8. ツールを使用する
Google 検索を使用して、モデルのレスポンスをリアルタイムの情報にグラウンディングします。API は自動的に検索し、結果を処理して引用を返します。
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.5-flash",
input="Who won the euro 2024?",
tools=[{"type": "google_search"}]
)
print(interaction.output_text)
# Print citations
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.5-flash",
input: "Who won the euro 2024?",
tools: [{ type: "google_search" }]
});
console.log(interaction.output_text);
// Print citations
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})`);
}
}
}
}
}
}
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": "Who won the euro 2024?",
"tools": [{"type": "google_search"}]
}'
回答:
{
"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.5-flash",
}
検索ステップはインタラクション履歴に詳しく記載されており、最終的な出力にはウェブソースを指すインライン引用が含まれています。
検索引用を抽出する方法については、Google 検索のグラウンディング ガイドをご覧ください。複数のツールを組み合わせる方法については、ツールの組み合わせガイドをご覧ください。
コード実行
安全なサンドボックス化された Borg 環境で Python コードを実行します。
URL コンテキスト
公開ウェブ URL を直接渡して、ウェブページ コンテンツのレスポンスをグラウンディングします。
ファイル検索
アップロードされたドキュメントとメディア ファイルをインデックスに登録して検索します。
Google マップ
実際の地理空間データと位置情報データでレスポンスをグラウンディングします。
パソコンの使用
ブラウザの自動化と画面操作。
9. 独自の関数を呼び出す
関数呼び出しを使用すると、モデルをコードに接続できます。関数の名前とパラメータを宣言すると、モデルは呼び出すタイミングを決定して構造化された引数を返し、ローカルで実行して結果を返します。
ステートフル(推奨)
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.5-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.5-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);
REST
# Turn 1: Send prompt with function declaration
RESPONSE1=$(curl -s -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": "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"
# Turn 2: Send function result back
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",
"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"]
}
}]
}'
ステートレス
クライアント側で会話履歴を管理し、store=false を設定することで、ステートレス モードで関数呼び出しを使用することもできます。ステートレス モードでは、後続のリクエストの input フィールドに会話の完全な履歴を渡す必要があります。この履歴には次のものが含まれている必要があります。
- 最初の
user_inputステップ。 - ターン 1 で返されたモデル生成のすべてのステップ(
thoughtステップとfunction_callステップを含む)。受信したとおりに返されます。 - 実行された関数の出力を含む
function_resultステップ。
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.5-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.5-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);
REST
# Turn 1: Send request with tools and 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' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.5-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"]
}
}]
}')
# Extract model steps (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"
# Assume local execution returns:
RESULT="{\"location\": \"London\", \"temperature\": \"22\", \"unit\": \"celsius\"}"
# Reconstruct history for Turn 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}]}]')
# Turn 2: Send the full history
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\",
\"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\"]
}
}]
}"
回答:
ターン 1 で、モデルはステータス requires_action と 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.5-flash"
}
関数をローカルで実行して結果を送信すると(ターン 2)、最終的な完了したインタラクションが返されます。
{
"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.5-flash",
}
並列関数呼び出しや関数選択モードなどの上級者向け機能については、関数呼び出しガイドをご覧ください。
10. マネージド エージェントを実行する
マネージド エージェントは、コード実行やファイル管理などのツールにアクセスできるリモート サンドボックスで実行されます。model の代わりに agent を渡し、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);
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 '{
"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"
}'
独自の指示、スキル、データソースを使用して、カスタム エージェントを定義して保存することもできます。
クイックスタート
最初のエージェント呼び出しを行い、レスポンスをストリーミングして、カスタム エージェントを構築します。
Antigravity エージェント
デフォルト エージェントの機能、ツール、マルチモーダル入力、料金。
AI Studio のエージェント
コードを記述せずにエージェントをプロトタイピングするためのビジュアル プレイグラウンド。
11. バックグラウンドでタスクを実行する
background=True を設定して、長時間実行されるタスクを非同期で実行します。interactions.get() で結果をポーリングします。
Python
import time
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.5-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}")
# Poll for completion
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.5-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}`);
// Poll for completion
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));
}
REST
# Start a background task
RESPONSE=$(curl -s -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 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"
# Poll for completion
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
done
回答:
最初のレスポンスはすぐに返され、ステータスは in_progress になります。
{
"id": "v1_abc123",
"status": "in_progress",
"object": "interaction",
"model": "gemini-3.5-flash"
}
バックグラウンド タスクが完全に実行されると、インタラクションの状態を確認すると次のようになります。
{
"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.5-flash",
}
バックグラウンドでのモデルとエージェントの非同期実行については、バックグラウンド実行ガイドをご覧ください。
次のステップ
- テキスト生成: システム命令、生成構成、高度なテキスト パターン。
- 画像生成: アスペクト比、画像編集、スタイル参照。
- 画像理解: 分類、オブジェクト検出、ビジュアル Q&A。
- Thinking: The user wants to translate the source text while preserving the placeholder and . The source text is "Thinking: Use chain-of-thought reasoning for complex tasks." The example translation for "Thinking: Use chain-of-thought reasoning for complex tasks." is "思考: 複雑なタスクに思考連鎖推論を使用します。" I need to insert the placeholders and into the translated text at the corresponding positions. The word "Thinking" corresponds to "思考". So the translation should be "思考: 複雑なタスクに思考連鎖推論を使用します。" 思考: 複雑なタスクに思考連鎖推論を使用します。
- 関数呼び出し: 並列関数モード、コンポジション関数モード、制約付き関数モード。
- Google 検索: グラウンディング、引用、検索候補。
- マネージド エージェント: コード実行とファイル管理を備えた事前構築済みのエージェント。
- Deep Research: プランニングと統合による自律的な複数ステップのリサーチ。
- 構造化出力: JSON スキーマ、列挙型、再帰型定義。