A API Interactions do v1beta está introduzindo mudanças interruptivas que reestruturam o
formato da API para oferecer suporte a recursos futuros, como direcionamento em voo e
chamadas de ferramentas assíncronas. Esta página explica o que está mudando e fornece exemplos de código de antes e depois para ajudar na migração. Há duas categorias de mudanças:
- Esquema de etapas: uma nova matriz
stepssubstitui a matrizoutputs, fornecendo uma linha do tempo estruturada de cada interação. - Configuração do formato de saída: um novo
response_formatpolimórfico consolida todos os controles de formato de saída e removeresponse_mime_type.
Siga as etapas em Como migrar para o novo esquema para atualizar sua integração.
Mudança principal: outputs para steps
O novo esquema substitui a matriz outputs por uma matriz steps.
- Legado: as respostas retornavam uma matriz
outputssimples que continha apenas o conteúdo gerado pelo modelo. - Novo esquema: as respostas retornam uma matriz
stepsque contém etapas estruturadas com discriminadores de tipo.
POST /interactions retorna apenas etapas de saída. GET /interactions/{id}
retorna a linha do tempo completa da etapa, incluindo a etapa inicial user_input.
Entrada/saída básica (unária)
Antes (legado)
Python
# Request
interaction = client.interactions.create(
model="gemini-3-flash-preview", input="Tell me a joke."
)
# Response access
print(interaction.outputs[-1].text)
JavaScript
// Request
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a joke.'
});
// Response access
console.log(interaction.outputs[-1].text);
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Tell me a joke."
}
// Response
{
"id": "int_123",
"role": "model",
"outputs": [
{
"type": "text",
"text": "Why did the chicken cross the road?"
}
]
}
Depois (novo esquema)
Python
# Request
interaction = client.interactions.create(
model="gemini-3-flash-preview", input="Tell me a joke."
)
# Response access
print(interaction.steps[-1].content[0].text) # CHANGED: steps instead of outputs
JavaScript
// Request
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a joke.'
});
// Response access
console.log(interaction.steps.at(-1).content[0].text);
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Tell me a joke."
}
// POST Response
{
"id": "int_123",
"steps": [
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "Why did the chicken cross the road?"
}
]
}
]
}
// GET /v1beta/interactions/int_123 (returns full timeline including input)
{
"id": "int_123",
"steps": [
{
"type": "user_input",
"content": [
{ "type": "text", "text": "Tell me a joke." }
]
},
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "Why did the chicken cross the road?"
}
]
}
]
}
Chamadas de função
A estrutura da solicitação permanece inalterada, mas a resposta substitui o conteúdo
outputs simples por etapas estruturadas.
Antes (legado)
Python
# Accessing function call in legacy schema
for output in interaction.outputs:
if output.type == "function_call":
print(f"Calling {output.name} with {output.arguments}")
JavaScript
// Accessing function call in legacy schema
for (const output of interaction.outputs) {
if (output.type === 'function_call') {
console.log(`Calling {output.name} with {JSON.stringify(output.arguments)}`);
}
}
REST
// Response
{
"id": "int_001",
"role": "model",
"status": "requires_action",
"outputs": [
{
"type": "thought",
"signature": "abc123..."
},
{
"type": "function_call",
"id": "fc_1",
"name": "get_weather",
"arguments": { "location": "Boston, MA" }
}
]
}
Depois (novo esquema)
Python
# Accessing function call in new steps schema
for step in interaction.steps:
if step.type == "function_call":
print(f"Calling {step.name} with {step.arguments}")
JavaScript
// Accessing function call in new steps schema
for (const step of interaction.steps) {
if (step.type === 'function_call') {
console.log(`Calling {step.name} with {JSON.stringify(step.arguments)}`);
}
}
REST
// POST Response
{
"id": "int_001",
"status": "requires_action",
"steps": [
{
"type": "thought",
"summary": [{
"type": "text",
"text": "I need to check the weather in Boston..."
}],
"signature": "abc123..."
},
{
"type": "function_call",
"id": "fc_1",
"name": "get_weather",
"arguments": { "location": "Boston, MA" }
}
]
}
Ferramentas do lado do servidor
As ferramentas do lado do servidor (como a Pesquisa Google ou a execução de código) agora geram tipos de etapas específicos na matriz steps. Enquanto o esquema legado retornava essas operações como tipos de conteúdo específicos na matriz outputs, o novo esquema as move para a matriz steps. Os exemplos a seguir usam a Pesquisa Google.
Antes (legado)
Python
# Accessing search results in legacy schema
for output in interaction.outputs:
if output.type == "google_search_call":
print(f"Searched for: {output.arguments.queries}")
elif output.type == "google_search_result":
print(f"Found results: {output.result.rendered_content}")
JavaScript
// Accessing search results in legacy schema
for (const output of interaction.outputs) {
if (output.type === 'google_search_call') {
console.log(`Searched for: {output.arguments.queries}`);
} else if (output.type === 'google_search_result') {
console.log(`Found results: {output.result.renderedContent}`);
}
}
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Who won the last Super Bowl?",
"tools": [
{ "type": "google_search" }
]
}
// Response
{
"id": "int_456",
"outputs": [
{
"type": "google_search_call",
"id": "gs_1",
"arguments": { "queries": ["last Super Bowl winner"] }
},
{
"type": "google_search_result",
"call_id": "gs_1",
"result": {
"rendered_content": "<div>...</div>",
"url": "https://www.nfl.com/super-bowl"
}
},
{
"type": "text",
"text": "The Kansas City Chiefs won the last Super Bowl.",
"annotations": [
{
"start_index": 4,
"end_index": 22,
"source": "https://www.nfl.com/super-bowl"
}
]
}
],
"status": "completed"
}
Depois (novo esquema)
Python
# Accessing search results in new steps schema
for step in interaction.steps:
if step.type == "google_search_call":
print(f"Searched for: {step.arguments.queries}")
elif step.type == "google_search_result":
print(f"Found results: {step.result.search_suggestions}")
JavaScript
// Accessing search results in new steps schema
for (const step of interaction.steps) {
if (step.type === 'google_search_call') {
console.log(`Searched for: {step.arguments.queries}`);
} else if (step.type === 'google_search_result') {
console.log(`Found results: {step.result.searchSuggestions}`);
}
}
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Who won the last Super Bowl?",
"tools": [
{ "type": "google_search" }
]
}
// POST Response
{
"id": "int_456",
"steps": [
{
"type": "google_search_call",
"id": "gs_1",
"arguments": { "queries": ["last Super Bowl winner"] },
"signature": "abc123..."
},
{
"type": "google_search_result",
"call_id": "gs_1",
"result": {
"search_suggestions": "<div>...</div>"
},
"signature": "abc123..."
},
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "The Kansas City Chiefs won the last Super Bowl.",
"annotations": [
{
"type": "url_citation",
"url": "https://www.nfl.com/super-bowl",
"title": "NFL.com",
"start_index": 4,
"end_index": 22
}
]
}
]
}
],
"status": "completed"
}
Streaming
O streaming expõe novos tipos de eventos:
Novos tipos de evento
interaction.createdinteraction.completedinteraction.status_update: abrange estados e erros do ciclo de vida. Consulte os status abaixo.step.startstep.deltastep.stop
interaction.status_update status
in_progressactiveinterruptedrequires_actionerror
Tipos de evento descontinuados
Os seguintes tipos de eventos legados foram substituídos pelos novos eventos listados acima:
interaction.start→interaction.createdcontent.start→step.startcontent.delta→step.deltacontent.stop→step.stopinteraction.complete→interaction.completederror→interaction.status_updatecomstatus: "error"interaction.status_update→interaction.status_update(sem mudanças, mas agora abrange outros estados)
Chamadas de função de streaming: quando você usa o streaming com a chamada de função, o evento step.start entrega o nome da função, e os eventos step.delta transmitem os argumentos como strings JSON parciais (usando arguments_delta). É necessário acumular esses deltas para receber os argumentos completos. Isso difere das chamadas
unárias, em que você recebe o objeto de chamada de função completo de uma só vez.
Exemplos
Antes (legado)
Python
# Legacy streaming used content.delta
stream = client.interactions.create(
model="gemini-3-flash-preview",
input="Explain quantum entanglement in simple terms.",
stream=True,
)
for chunk in stream:
if chunk.event_type == "content.delta":
if chunk.delta.type == "text":
print(chunk.delta.text, end="", flush=True)
JavaScript
// Legacy streaming used content.delta
const stream = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Explain quantum entanglement in simple terms.',
stream: true,
});
for await (const chunk of stream) {
if (chunk.event_type === 'content.delta') {
if (chunk.delta.type === 'text') {
process.stdout.write(chunk.delta.text);
}
}
}
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Explain quantum entanglement in simple terms.",
"stream": true
}
// Response (SSE Lines)
// event: interaction.start
// data: {"id": "int_123", "status": "in_progress"}
//
// event: content.start
// data: {"index": 0, "type": "text"}
//
// event: content.delta
// data: {"delta": {"type": "text", "text": "Quantum entanglement is..."}}
//
// event: content.stop
// data: {"index": 0}
//
// event: interaction.complete
// data: {"id": "int_123", "status": "done", "usage": {"total_tokens": 42}}
Depois (novo esquema)
Python
# Consuming stream and handling new event types
for event in client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me a story.",
stream=True,
):
if event.type == "step.delta": # CHANGED: step.delta instead of content.delta
if event.delta.type == "text":
print(event.delta.text, end="")
JavaScript
// Consuming stream and handling new event types
const stream = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a story.',
stream: true,
});
for await (const event of stream) {
if (event.type === 'step.delta') { // CHANGED: step.delta instead of content.delta
if (event.delta.type === 'text') {
process.stdout.write(event.delta.text);
}
}
}
REST
// Request: POST /v1beta/interactions
// Accept: text/event-stream
{
"model": "gemini-3-flash-preview",
"input": "Tell me a story.",
"stream": true
}
// Response (SSE Lines)
// event: interaction.created
// data: {"interaction": {"id": "int_xyz", "status": "in_progress", "object": "interaction", "model": "gemini-3-flash-preview"}, "event_type": "interaction.created"}
//
// event: interaction.status_update
// data: {"interaction_id": "int_xyz", "status": "active", "event_type": "interaction.status_update"}
//
// event: step.start
// data: {"index": 0, "step": {"type": "thought", "signature": "abc123..."}, "event_type": "step.start"}
//
// event: step.stop
// data: {"index": 0, "event_type": "step.stop"}
//
// event: step.start
// data: {"index": 1, "step": {"content": [{"text": "Once upon", "type": "text"}], "type": "model_output"}, "event_type": "step.start"}
//
// event: step.delta
// data: {"index": 1, "delta": {"text": " a time...", "type": "text"}, "event_type": "step.delta"}
//
// event: step.stop
// data: {"type": "step.stop", "index": 1, "status": "done"}
//
// event: interaction.completed
// data: {"type": "interaction.completed", "interaction": {"id": "int_xyz", "status": "completed", "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}} // NEW: Dedicated completion event
Histórico de conversas sem estado
Se você gerenciar o histórico de conversas manualmente no lado do cliente (caso de uso sem estado), atualize a forma como você encadeia as conversas anteriores.
- Legado: os desenvolvedores geralmente coletavam a matriz
outputsdas respostas e as enviavam de volta no campoinputna próxima vez. - Novo esquema: agora, colete a matriz
stepsda resposta e transmita-a no campoinputda próxima solicitação, anexando a nova vez do usuário como uma etapauser_input.
Configuração do formato de saída: mudanças em response_format
A API atualizada consolida todos os controles de formato de saída em um campo response_format unificado e polimórfico. Isso centraliza a configuração de saída no nível superior e mantém generation_config focado no comportamento do modelo (como temperatura, top_p e raciocínio).
Mudanças importantes
- A API remove
response_mime_type. Agora você especifica o tipo MIME por entrada de formato emresponse_format. response_formatagora é um objeto (ou matriz) polimórfico. Cada entrada tem um discriminadortype(text,audio,image) e campos específicos do tipo. Para solicitar várias modalidades de saída, transmita uma matriz de entradas de formato.image_configserá movido degeneration_configpararesponse_format. Agora você especifica configurações de saída de imagem, comoaspect_ratioeimage_sizeem uma entradaresponse_formatcom"type": "image".
Saída estruturada (JSON)
O novo esquema remove o campo response_mime_type. Em vez disso, especifique o tipo MIME e o esquema JSON em um objeto response_format com "type": "text".
Antes (legado)
Python
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Summarize this article.",
response_mime_type="application/json",
response_format={
"type": "object",
"properties": {
"summary": {"type": "string"}
}
},
)
print(interaction.outputs[-1].text)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Summarize this article.',
responseMimeType: 'application/json',
responseFormat: {
type: 'object',
properties: {
summary: { type: 'string' }
}
},
});
console.log(interaction.outputs[-1].text);
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Summarize this article.",
"response_mime_type": "application/json",
"response_format": {
"type": "object",
"properties": {
"summary": { "type": "string" }
}
}
}
Depois (novo esquema)
Python
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Summarize this article.",
# response_mime_type is removed — specify mime_type inside response_format
response_format={
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "object",
"properties": {
"summary": {"type": "string"}
}
}
},
)
print(interaction.steps[-1].content[0].text)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Summarize this article.',
// responseMimeType is removed — specify mimeType inside responseFormat
responseFormat: {
type: 'text',
mimeType: 'application/json',
schema: {
type: 'object',
properties: {
summary: { type: 'string' }
}
}
},
});
console.log(interaction.steps.at(-1).content[0].text);
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Summarize this article.",
// response_mime_type is removed
"response_format": {
"type": "text", // NEW: type discriminator
"mime_type": "application/json", // MOVED: from response_mime_type
"schema": { // RENAMED: was response_format directly
"type": "object",
"properties": {
"summary": { "type": "string" }
}
}
}
}
Configuração de imagem
O novo esquema remove image_config de generation_config. Agora você especifica as configurações de saída de imagem em uma entrada response_format com "type": "image".
Antes (legado)
Python
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Generate an image of a sunset over the ocean.",
generation_config={
"image_config": {
"aspect_ratio": "1:1",
"image_size": "1K"
}
},
)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Generate an image of a sunset over the ocean.',
generationConfig: {
imageConfig: {
aspectRatio: '1:1',
imageSize: '1K'
}
},
});
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Generate an image of a sunset over the ocean.",
"generation_config": {
"image_config": {
"aspect_ratio": "1:1",
"image_size": "1K"
}
}
}
Depois (novo esquema)
Python
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Generate an image of a sunset over the ocean.",
# image_config is removed from generation_config — use response_format
response_format={
"type": "image",
"mime_type": "image/jpeg",
"delivery": "inline",
"aspect_ratio": "1:1",
"image_size": "1K"
},
)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Generate an image of a sunset over the ocean.',
// imageConfig is removed from generationConfig — use responseFormat
responseFormat: {
type: 'image',
mimeType: 'image/jpeg',
delivery: 'inline',
aspectRatio: '1:1',
imageSize: '1K'
},
});
REST
// Request: POST /v1beta/interactions
{
"model": "gemini-3-flash-preview",
"input": "Generate an image of a sunset over the ocean.",
// image_config removed from generation_config
"response_format": {
"type": "image", // NEW: type discriminator
"mime_type": "image/jpeg",
"delivery": "inline",
"aspect_ratio": "1:1", // MOVED: from generation_config.image_config
"image_size": "1K" // MOVED: from generation_config.image_config
}
}
Para solicitar várias modalidades de saída (por exemplo, texto e áudio juntos),
transmita uma matriz de entradas de formato para response_format em vez de um único
objeto.
Como migrar para o novo esquema
Usuários do SDK
Faça upgrade para a versão mais recente do SDK (Python ≥2.0.0, JavaScript ≥2.0.0). O SDK ativa automaticamente o novo esquema. Não é necessário mudar o código, apenas atualizar a forma como você lê as respostas (confira os exemplos acima). Somente o novo esquema é compatível com essas versões do SDK. As versões mais antigas do SDK (Python 1.x.x, JavaScript 1.x.x) vão continuar funcionando até que o esquema legado seja removido em 8 de junho de 2026.
Usuários da API REST
Adicione o cabeçalho Api-Revision: 2026-05-20 às suas solicitações para ativar o novo esquema agora. Depois de 26 de maio, o novo esquema se torna o padrão para todas as solicitações. É possível desativar temporariamente com Api-Revision: 2026-05-07
até 8 de junho, quando a API vai remover permanentemente o esquema legado.
Cronograma
| Data | Fase | Usuários do SDK | Usuários da API REST |
|---|---|---|---|
| 7 de maio | Ativar | Nova versão do SDK disponível (Python ≥2.0.0, JS ≥2.0.0). Faça upgrade para receber o novo esquema automaticamente. | Adicione o cabeçalho Api-Revision: 2026-05-20 para ativar. O padrão continua sendo o legado. |
| 26 de maio | Inversão padrão | Nenhuma ação é necessária se você já fez o upgrade. SDKs mais antigos (Python 1.x.x, JS 1.x.x) ainda funcionam, mas retornam respostas legadas. | O novo esquema agora é o padrão. Envie o cabeçalho Api-Revision: 2026-05-07 para desativar. |
| 8 de junho | Pôr do sol | As versões 1.x.x do SDK Python e JS vão falhar nas chamadas da API Interactions. | O esquema legado foi removido da API Interactions. Cabeçalho Api-Revision ignorado. |
Lista de verificação de migração
Esquema de etapas (steps)
- Atualize o código para ler o conteúdo da resposta da matriz
stepsem vez deoutputs. Confira exemplos. - Verifique se o código processa os tipos de etapa
user_inputemodel_output. Confira exemplos. - (Chamada de função) Atualize o código para encontrar
function_calletapas na matrizsteps. Confira exemplos. - (Ferramentas do lado do servidor) Atualize o código para processar etapas específicas da ferramenta (por exemplo,
google_search_call,google_search_result). Confira exemplos. - (Histórico sem estado) Atualize o gerenciamento do histórico para transmitir a matriz
stepsno campoinputda próxima solicitação. Confira os detalhes. - (Somente streaming) Atualize o cliente para detectar novos tipos de eventos SSE (
interaction.created,step.deltaetc.). Confira exemplos.
Configuração do formato de saída (response_format)
- Substitua
response_mime_typepor um campomime_typedentro deresponse_format. Confira exemplos. - Encapsule o esquema JSON
response_formatem um objeto{"type": "text", "schema": ...}. Confira exemplos. - (Geração de imagens) Mova
image_configdegeneration_configpara uma entrada{"type": "image", ...}emresponse_format. Confira exemplos. - (Multimodal) Converta
response_formatde um único objeto para uma matriz ao solicitar várias modalidades de saída.