Quando crei un'interazione, puoi impostare stream: true per trasmettere in streaming la risposta in modo incrementale utilizzando gli eventi inviati dal server (SSE).
Python
from google import genai
client = genai.Client()
stream = client.interactions.create(
model="gemini-3.6-flash",
input="Count from 1 to 25.",
stream=True,
)
for event in stream:
if event.event_type == "step.delta":
if event.delta.type == "text":
print(event.delta.text, end="", flush=True)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const stream = await client.interactions.create({
model: "gemini-3.6-flash",
input: "Count from 1 to 25.",
stream: true,
});
for await (const event of stream) {
if (event.event_type === "step.delta") {
if (event.delta.type === "text") {
process.stdout.write(event.delta.text);
}
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
--no-buffer \
-d '{
"model": "gemini-3.6-flash",
"input": "Count from 1 to 25.",
"stream": true
}'
event: interaction.created
data: {"interaction":{"id":"v1_...","status":"in_progress","object":"interaction","model":"gemini-3.6-flash"},"event_type":"interaction.created"}
event: interaction.status_update
data: {"interaction_id":"v1_...","status":"in_progress","event_type":"interaction.status_update"}
event: step.start
data: {"index":0,"step":{"type":"thought"},"event_type":"step.start"}
event: step.delta
data: {"index":0,"delta":{"signature":"...","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":"1, 2, 3, 4, 5, 6, ","type":"text"},"event_type":"step.delta"}
event: step.delta
data: {"index":1,"delta":{"text":"7, 8, 9, 10, 11, 12, 13,","type":"text"},"event_type":"step.delta"}
...
event: step.stop
data: {"index":1,"event_type":"step.stop"}
event: interaction.completed
data: {"interaction":{"id":"v1_...","status":"completed","usage":{"total_tokens":346,"total_input_tokens":11,"input_tokens_by_modality":[{"modality":"text","tokens":11}],"total_cached_tokens":0,"total_output_tokens":90,"total_tool_use_tokens":0,"total_thought_tokens":245},"created":"2026-05-12T18:44:51Z","updated":"2026-05-12T18:44:51Z","service_tier":"standard","object":"interaction","model":"gemini-3.6-flash"},"event_type":"interaction.completed"}
event: done
data: [DONE]
Tipi di evento
Ogni evento inviato dal server include un event_type denominato e dati JSON associati. L'API Interactions utilizza un modello di streaming simmetrico in cui tutti i contenuti (testo, chiamate di strumenti, pensiero) scorrono attraverso un evento basato sui passaggi coerente.
Ogni stream segue questo flusso di eventi:
interaction.created: l'interazione viene creata e include i metadati (ID, modello, stato).- Una serie di passaggi, ognuno dei quali consiste in:
- Un evento
step.start, che indica il tipo di passaggio (ad es.model_output,thought,function_call). - Uno o più eventi
step.deltacon dati incrementali per questo passaggio. - Un evento
step.stopche contrassegna il passaggio come completato.
- Un evento
- Un evento
interaction.completedcon statisticheusagefinali.
Quando imposti stream: false, l'API restituisce un singolo oggetto interaction con un array steps. Ogni elemento di steps è la versione completamente assemblata di un ciclo step.start → step.delta → step.stop.
interaction.created
Inviato al momento della creazione dell'interazione. Contiene l'ID interazione, il modello e lo stato iniziale.
event: interaction.created
data: {"interaction": {"id": "...", "model": "gemini-3.6-flash", "status": "in_progress", "object": "interaction"}, "event_type": "interaction.created"}
interaction.status_update
Indica una transizione di stato a livello di interazione. Potrebbe essere visualizzato tra i passaggi.
event: interaction.status_update
data: {"interaction_id": "...", "status": "in_progress", "event_type": "interaction.status_update"}
step.start
Indica l'inizio di un nuovo passaggio. Contiene i passaggi type e index. Il tipo di passaggio determina quali tipi di delta prevedere e come viene visualizzato il passaggio in una risposta non in streaming:
| Tipo di passaggio | Tipi di delta previsti | Descrizione |
|---|---|---|
model_output |
text, image, audio |
Il contenuto della risposta finale del modello. |
thought |
thought_signature, thought_summary |
Ragionamento chain-of-thought. summary è presente solo quando thinking_summaries è abilitato. |
function_call |
arguments_delta |
Una richiesta al client di eseguire una funzione. Imposta lo stato dell'interazione su requires_action. |
| Strumenti lato server | Varia in base allo strumento | Strumenti eseguiti dall'API (ad es. google_search_call, google_search_result, code_execution_call, code_execution_result). |
Per l'elenco completo, consulta il riferimento all'API Interactions.
event: step.start
data: {"index": 0, "step": {"type": "model_output"}, "event_type": "step.start"}
Per le chiamate di funzioni, il passaggio include il nome della funzione, l'ID e gli argomenti vuoti {}.
event: step.start
data: {"index": 0, "step": {"type": "function_call", "id":"un6k8t18", "name": "get_weather", "arguments":{}}, "event_type": "step.start"}
step.delta
Dati incrementali per il passaggio corrente. L'oggetto delta contiene un campo type che ne determina la forma.
Esempi:
text: token di testo incrementale di un passaggio model_output:
event: step.delta
data: {"index": 0, "delta": {"type": "text", "text": "Hello, my name is Phil"}, "event_type": "step.delta"}
event: step.delta
data: {"index": 0, "delta": {"type": "text", "text": ", and I live in Germany." }, "event_type": "step.delta"}
image: dati immagine con codifica Base64 da un passaggio model_output:
event: step.delta
data: {"index": 0, "delta": {"type": "image", "mime_type": "image/jpeg", "data": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCg..."}, "event_type": "step.delta"}
thought_summary: riepilogo dei contenuti di un passaggio thought:
event: step.delta
data: {"index": 0, "delta": {"type": "thought_summary", "content": {"type": "text", "text": "I need to find the GCD..."}}, "event_type": "step.delta"}
arguments_delta: stringa JSON (parziale) per gli argomenti della chiamata di funzione. Deve essere accumulato nei delta:
event: step.delta
data: {"index": 0, "delta": {"type": "arguments_delta", "arguments": "{\"location\": \"San Francisco, CA\"}"}, "event_type": "step.delta"}
Questi sono alcuni dei tipi di delta più comuni. Per l'elenco completo di tutti i tipi di delta, consulta il riferimento API Interactions.
step.stop
Indica la fine di un passaggio. Contiene il passaggio index.
event: step.stop
data: {"index": 0, "event_type": "step.stop"}
interaction.completed
Inviato al termine dell'interazione. Contiene l'oggetto interazione finale con le statistiche usage. In modalità non streaming, questo è l'oggetto di risposta di primo livello. Non include steps nella risposta.
event: interaction.completed
data: {"interaction": {"id": "v1_abc123", "status": "completed", "usage": {"total_input_tokens": 7, "total_output_tokens": 12, "total_tokens": 19}}, "event_type": "interaction.completed"}
error
Inviato quando si verifica un errore durante l'interazione. Contiene un oggetto di errore con un messaggio e un codice.
event: error
data: {"error":{"message":"Deadline expired before operation could complete.","code":"gateway_timeout"},"event_type":"error"}
Streaming con gli strumenti
L'API Interactions supporta lo streaming con strumenti lato client (chiamata di funzione) e lato server (Ricerca Google, esecuzione di codice e così via) in un'unica richiesta. Durante lo streaming, le chiamate agli strumenti vengono visualizzate come passaggi digitati nel flusso di eventi. Per le chiamate di funzione, l'evento step.start fornisce il nome della funzione,
mentre gli eventi step.delta trasmettono gli argomenti come stringhe JSON
(arguments_delta). Devi accumulare questi delta per ottenere gli argomenti completi.
Gli strumenti lato server come la Ricerca Google vengono eseguiti automaticamente dall'API, producendo i passaggi google_search_call e google_search_result.
Streaming con la chiamata di funzione
Per eseguire la chiamata di funzioni con lo streaming, il client deve gestire una conversazione multi-turn:
- Turno 1 (richiesta di funzione): chiama
interactions.createconstream: trueetoolsche hai definito. L'API trasmetterà in streaming un passaggiofunction_call. Devi accumulare le stringhe JSON degli argomenti incrementali (arguments_delta) dagli eventistep.deltafino al completamento dell'interazione con lo statorequires_action. - Turno 2 (invio del risultato): chiama di nuovo
interactions.create, passandoprevious_interaction_id(corrispondente all'ID della prima interazione) e inviando un bloccofunction_resultall'interno dell'arrayinput. In questo modo, il flusso viene ripreso e il modello può generare la risposta finale.
Python
from google import genai
client = genai.Client()
weather_tool = {
"type": "function",
"name": "get_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
}
},
"required": ["location"]
}
}
# Turn 1: Request function call
stream = client.interactions.create(
model="gemini-3.6-flash",
tools=[weather_tool],
input="What is the weather in Paris right now?",
stream=True,
)
first_interaction_id = None
func_call_id = None
func_call_name = None
func_args_accumulated = ""
for event in stream:
if event.event_type == "interaction.created":
first_interaction_id = event.interaction.id
elif event.event_type == "step.start":
step = event.step
if step.type == "function_call":
func_call_id = step.id
func_call_name = step.name
elif event.event_type == "step.delta":
if event.delta.type == "arguments_delta":
func_args_accumulated += event.delta.arguments
# Turn 2: Execute tool and send the result back to resume stream
if func_call_id:
# Execute weather_tool using accumulated arguments
dummy_result = {
"content": [{"type": "text", "text": '{"weather": "Sunny and 22°C"}'}]
}
stream2 = client.interactions.create(
model="gemini-3.6-flash",
previous_interaction_id=first_interaction_id,
input=[{
"type": "function_result",
"name": func_call_name,
"call_id": func_call_id,
"result": dummy_result
}],
stream=True,
)
for event in stream2:
if event.event_type == "step.delta":
if event.delta.type == "text":
print(event.delta.text, end="", flush=True)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const weatherTool = {
type: "function",
name: "get_weather",
description: "Get the current weather in a given location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city and state, e.g. San Francisco, CA"
}
},
required: ["location"]
}
};
// Turn 1: Request function call
const stream = await client.interactions.create({
model: "gemini-3.6-flash",
tools: [weatherTool],
input: "What is the weather in Paris right now?",
stream: true,
});
let firstInteractionId = null;
let funcCallId = null;
let funcCallName = null;
let funcArgsAccumulated = "";
for await (const event of stream) {
if (event.event_type === "interaction.created") {
firstInteractionId = event.interaction.id;
} else if (event.event_type === "step.start") {
const step = event.step;
if (step.type === "function_call") {
funcCallId = step.id;
funcCallName = step.name;
}
} else if (event.event_type === "step.delta") {
if (event.delta.type === "arguments_delta") {
funcArgsAccumulated += event.delta.arguments;
}
}
}
// Turn 2: Execute tool and send the result back to resume stream
if (funcCallId && firstInteractionId && funcCallName) {
const dummyResult = {
content: [{ type: "text", text: '{"weather": "Sunny and 22°C"}' }]
};
const stream2 = await client.interactions.create({
model: "gemini-3.6-flash",
previous_interaction_id: firstInteractionId,
input: [{
type: "function_result",
name: funcCallName,
call_id: funcCallId,
result: dummyResult
}],
stream: true,
});
for await (const event of stream2) {
if (event.event_type === "step.delta") {
if (event.delta.type === "text") {
process.stdout.write(event.delta.text);
}
}
}
}
REST
Turno 1: richiedi la chiamata di funzione
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
--no-buffer \
-d '{
"model": "gemini-3.6-flash",