In diesem Leitfaden erfahren Sie, wie Sie von der generateContent API zur Interactions API migrieren.
Die Interactions API ist die einfachste und beste Möglichkeit, Anwendungen mit Gemini-Modellen und ‑Agents zu entwickeln. generateContent wird weiterhin vollständig unterstützt, wir empfehlen jedoch, für alle neuen Entwicklungen die Interactions API zu verwenden.
Warum migrieren?
Die Interactions API ist die einfachste und beste Möglichkeit, mit Gemini-Modellen und ‑Agents zu arbeiten:
- Serverseitige Verlaufsverwaltung: Vereinfachte Abläufe mit mehreren Durchgängen über
previous_interaction_id. Der Server aktiviert den Status standardmäßig (store=true). Sie können jedoch das statuslose Verhalten aktivieren, indem Siestore=falsefestlegen. - Beobachtbare Ausführungsschritte: Durch die typisierten Schritte lassen sich komplexe Abläufe einfach debuggen und die Benutzeroberfläche für Zwischenereignisse (z. B. Gedanken oder Such-Widgets) rendern.
- Tool-Nutzung und Agenten-Workflows: Native Unterstützung für die mehrstufige Tool-Nutzung, Orchestrierung und komplexe Schlussfolgerungsabläufe durch typisierte Ausführungsschritte.
- Lang andauernde Aufgaben und Hintergrundaufgaben: Unterstützt das Auslagern zeitaufwendiger Vorgänge wie Deep Think und Deep Research in Hintergrundprozesse mithilfe von
background=true.
Einfache Eingabe/Ausgabe
In diesem Abschnitt wird gezeigt, wie Sie eine einfache Anfrage zur Textgenerierung migrieren.
Vor (generateContent)
Die generateContent API ist zustandslos und gibt die Antwort direkt zurück. Die Antwortstruktur umschließt die Ausgabe in einer Liste von candidates, die jeweils content mit einer Liste von zu parsenden parts enthalten.
Python
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash-lite", contents="Tell me a joke."
)
print(response.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-lite",
contents: "Tell me a joke.",
});
console.log(response.text);
REST
# Request
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"contents": [{
"parts": [{
"text": "Tell me a joke."
}]
}]
}'
# Response
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Why did the chicken cross the road? To get to the other side!"
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 0
}
],
"usageMetadata": {
"promptTokenCount": 4,
"candidatesTokenCount": 12,
"totalTokenCount": 16
}
}
Die Interactions API gibt eine gespeicherte Interaktionsressource mit einer steps-Zeitachse zurück. Sie können das steps-Array zwar manuell prüfen, um Zwischenereignisse zu finden, die Google GenAI SDKs bieten jedoch praktische Eigenschaften direkt im zurückgegebenen Interaction-Objekt, um auf die endgültige Ausgabe zuzugreifen.
Die gängigste Convenience-Eigenschaft ist .output_text (String), mit der aufeinanderfolgende TextContent-Blöcke am Ende der Antwort des Modells automatisch extrahiert und zusammengeführt werden. Das funktioniert zwar perfekt für einfache Antworten, aber frühere Textblöcke, die durch nicht textbezogene Inhalte (z. B. Gedanken, Bilder, Audio oder Tool-Aufrufe) getrennt sind, werden nicht berücksichtigt. Bei komplexen oder verschachtelten multimodalen Antworten müssen Sie stattdessen manuell über steps iterieren.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.6-flash", input="Tell me a joke."
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
let interaction = await client.interactions.create({
model: 'gemini-3.6-flash',
input: 'Tell me a joke.'
});
console.log(interaction.output_text);
REST
# Request
curl -X POST "https://generativelanguage.googleapis.com/v1beta2/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3.6-flash",
"input": "Tell me a joke."
}'
# Response
{
"id": "int_123",
"status": "completed",
"steps": [
{
"type": "user_input",
"status": "done",
"content": [
{
"type": "text",
"text": "Tell me a joke."
}
]
},
{
"type": "model_output",
"status": "done",
"content": [
{
"type": "text",
"text": "Why did the chicken cross the road?"
}
]
}
]
}
Unterhaltungen über mehrere Themen
In der Interactions API werden Interaktionen standardmäßig gespeichert, sodass die serverseitige Statusverwaltung für Multi-Turn-Unterhaltungen möglich ist.
Vor (generateContent)
In generateContent müssen Sie den Unterhaltungsverlauf manuell mit dem contents-Array oder einem clientseitigen Chat-Helfer verwalten.
Python
Chat-Assistenten verwenden (empfohlen)
from google import genai
client = genai.Client()
chat = client.chats.create(model="gemini-2.5-flash-lite")
response1 = chat.send_message("Hi, my name is Phil.")
print(response1.text)
response2 = chat.send_message("What is my name?")
print(response2.text)
Verlauf manuell verwalten
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=[
types.Content(
role="user", parts=[types.Part.from_text(text="Hi, my name is Phil.")]
),
types.Content(
role="model",
parts=[types.Part.from_text(text="Hi Phil, how can I help you?")],
),
types.Content(
role="user", parts=[types.Part.from_text(text="What is my name?")]
),
],
)
print(response.text)
JavaScript
Chat-Assistenten verwenden (empfohlen)
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const chat = client.chats.create({ model: 'gemini-2.5-flash-lite' });
let response = await chat.sendMessage({ message: 'Hi, my name is Phil.' });
console.log(response.text);
response = await chat.sendMessage({ message: 'What is my name?' });
console.log(response.text);
Verlauf manuell verwalten
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const response = await client.models.generateContent({
model: 'gemini-2.5-flash-lite',
contents: [
{ role: 'user', parts: [{ text: 'Hi, my name is Phil.' }] },
{ role: 'model', parts: [{ text: 'Hi Phil, how can I help you?' }] },
{ role: 'user', parts: [{ text: 'What is my name?' }] }
]
});
console.log(response.text);
REST
# Request (the second turn requires sending the entire history)
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"contents": [
{"role": "user", "parts": [{"text": "Hi, my name is Phil."}]},
{"role": "model", "parts": [{"text": "Hi Phil, how can I help you?"}]},
{"role": "user", "parts": [{"text": "What is my name?"}]}
]
}'
# Response
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Your name is Phil."
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 0
}
]
}
After (Interactions API)
Die Interactions API verwaltet den Status auf dem Server. Sie setzen eine Unterhaltung fort, indem Sie auf die previous_interaction_id verweisen.
Python
from google import genai
client = genai.Client()
interaction1 = client.interactions.create(
model="gemini-3.6-flash", input="Hi, my name is Phil."
)
print("Response 1:", interaction1.output_text)
interaction2 = client.interactions.create(
model="gemini-3.6-flash",
previous_interaction_id=interaction1.id,
input="What is my name?",
)
print("Response 2:", interaction2.output_text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
let interaction = await client.interactions.create({
model: 'gemini-3.6-flash',
input: 'Hi, my name is Phil.'
});
console.log("Response 1:", interaction.output_text);
interaction = await client.interactions.create({
model: 'gemini-3.6-flash',
previous_interaction_id: interaction.id,
input: 'What is my name?'
});
console.log("Response 2:", interaction.output_text);
REST
# First Request
curl -X POST "https://generativelanguage.googleapis.com/v1beta2/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3.6-flash",
"input": "Hi, my name is Phil."
}'
# Second Request (using ID from first response)
curl -X POST "https://generativelanguage.googleapis.com/v1beta2/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3.6-flash",
"previous_interaction_id": "int_123",
"input": "What is my name?"
}'
# Response to Second Request
{
"id": "int_123",
"steps": [
{
"type": "user_input",
"status": "done",
"content": [{ "type": "text", "text": "Hi, my name is Phil." }]
},
{
"type": "model_output",
"status": "done",
"content": [{ "type": "text", "text": "Hello Phil! How can I help you today?" }]
},
{
"type": "user_input",
"status": "done",
"content": [{ "type": "text", "text": "What is my name?" }]
},
{
"type": "model_output",
"status": "done",
"content": [{ "type": "text", "text": "Your name is Phil." }]
}
]
}
Multimodale Eingaben
Beide APIs unterstützen multimodale Eingaben (Text, Bilder, Videos usw.).
Vor (generateContent)
In generateContent übergeben Sie eine Liste von parts im Array contents. Die Antwort gibt die Ausgabe im parts des ersten Kandidaten zurück.
Python
from google import genai
from google.genai import types
client = genai.Client()
with open("sample.jpg", "rb") as f:
image_bytes = f.read()
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=[
types.Part.from_bytes(data=image_bytes, mime_type="image/jpeg"),
"Describe this image.",
],
)
print(response.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const imageBytes = fs.readFileSync('sample.jpg').toString('base64');
const response = await client.models.generateContent({
model: 'gemini-2.5-flash-lite',
contents: [
{
inlineData: {
data: imageBytes,
mimeType: 'image/jpeg',
},
},
'Describe this image.',
],
});
console.log(response.text);
REST
# Request
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"contents": [{
"parts": [
{
"inlineData": {
"mimeType": "image/jpeg",
"data": "..."
}
},
{
"text": "Describe this image."
}
]
}]
}'
# Response
{
"candidates": [
{
"content": {
"parts": [
{
"text": "This is a picture of a beautiful sunset."
}
],
"role": "model"
}
}
]
}
After (Interactions API)
In der Interactions API übergeben Sie ein Array an das Feld input. Sie rufen Ausgabedaten ab, indem Sie in der Zeitachse den Schritt model_output suchen.
Python
import base64
from google import genai
client = genai.Client()
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.6-flash",
input=[
{
"type": "image",
"mime_type": "image/jpeg",
"data": image_b64,
},
{"type": "text", "text": "Describe this image."},
],
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const imageBytes = fs.readFileSync('sample.jpg').toString('base64');
const interaction = await client.interactions.create({
model: 'gemini-3.6-flash',
input: [
{
type: 'image',
mime_type: 'image/jpeg',
data: imageBytes
},
{
type: 'text',
text: 'Describe this image.'
}
]
});
console.log(interaction.output_text);
REST
# Request
curl -X POST "https://generativelanguage.googleapis.com/v1beta2/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3.6-flash",
"input": [
{
"type": "image",
"mime_type": "image/jpeg",
"data": "..."
},
{
"type": "text",
"text": "Describe this image."
}
]
}'
# Response
{
"id": "int_multimodal",
"steps": [
{
"type": "user_input",
"status": "done",
"content": [
{
"type": "image",
"mime_type": "image/jpeg",
"data": "..."
},
{
"type": "text",
"text": "Describe this image."
}
]
},
{
"type": "model_output",
"status": "done",
"content": [
{
"type": "text",
"text": "This is a picture of a beautiful sunset over the mountains."
}
]
}
]
}
Strukturierte Ausgabe
Wenn das Modell JSON zurückgeben soll, das einem bestimmten Schema entspricht, konfigurieren Sie das Antwortformat.
Vor (generateContent)
In generateContent konfigurieren Sie das Ausgabeformat mit den Feldern response_mime_type und response_schema, die im Objekt config (oder generationConfig) verschachtelt sind.
Python
from google import genai
from google.genai import types
from pydantic import BaseModel
client = genai.Client()
class Recipe(BaseModel):
recipe_name: str
ingredients: list[str]
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents="Give me a recipe for chocolate chip cookies.",
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=Recipe,
),
)
print(response.text)
JavaScript
import { GoogleGenAI, Type } from '@google/genai';
const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash-lite',
contents: 'Give me a recipe for chocolate chip cookies.',
config: {
responseMimeType: 'application/json',
responseSchema: {
type: Type.OBJECT,
properties: {
recipe_name: { type: Type.STRING },
ingredients: {
type: Type.ARRAY,
items: { type: Type.STRING },
},
},
required: ['recipe_name', 'ingredients'],
},
},
});
console.log(response.text);
REST
# Request
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"contents": [{
"parts": [{
"text": "Give me a recipe for chocolate chip cookies."
}]
}],
"generationConfig": {
"responseMimeType": "application/json",
"responseSchema": {
"type": "OBJECT",
"properties": {
"recipe_name": { "type": "STRING" },
"ingredients": {
"type": "ARRAY",
"items": { "type": "STRING" }
}
},
"required": ["recipe_name", "ingredients"]
}
}
}'
# Response
{
"candidates": [
{
"content": {
"parts": [
{
"text": "{\n \"recipe_name\": \"Chocolate Chip Cookies\",\n \"ingredients\": [\n \"1 cup butter\",\n \"1 cup sugar\",\n \"2 cups flour\",\n \"1 cup chocolate chips\"\n ]\n}"
}
],
"role": "model"
}
}
]
}
After (Interactions API)
In der Interactions API werden Steuerelemente für das Ausgabeformat in ein response_format-Array auf oberster Ebene verschoben.
Python
from google import genai
from pydantic import BaseModel
client = genai.Client()
class Recipe(BaseModel):
recipe_name: str
ingredients: list[str]
interaction = client.interactions.create(
model="gemini-3.6-flash",
input="Give me a recipe for chocolate chip cookies.",
response_format=[
{
"type": "text",
"mime_type": "application/json",
"schema": Recipe.model_json_schema(),
}
],
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI }