A API Interactions (Beta) é uma interface unificada para interagir com modelos e agentes do Gemini. Como uma alternativa aprimorada à API generateContent, ela simplifica o gerenciamento de estado, a orquestração de ferramentas e as tarefas de longa duração. Para uma visão abrangente do esquema da API, consulte a
referência da API. Durante o período Beta, os recursos e esquemas estão sujeitos a mudanças incompatíveis.
Para começar rapidamente, teste o notebook de início rápido da API Interactions.
O exemplo a seguir mostra como chamar a API Interactions com um comando de texto.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me a short joke about programming."
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a short joke about programming.',
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Tell me a short joke about programming."
}'
Interações básicas
A API Interactions está disponível nos nossos
SDKs atuais. A maneira mais simples de interagir com o modelo é fornecendo um comando de texto. O input pode ser uma string, uma lista que contém objetos de conteúdo ou uma lista de turnos com funções e objetos de conteúdo.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me a short joke about programming."
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a short joke about programming.',
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Tell me a short joke about programming."
}'
Conversa
É possível criar conversas com vários turnos de duas maneiras:
- Com estado, referenciando uma interação anterior
- Sem estado, fornecendo todo o histórico de conversas
Conversa com estado
Para continuar uma conversa, transmita o id da interação anterior para o parâmetro previous_interaction_id. A API lembra o histórico da conversa,
então você só precisa enviar a nova entrada. Para detalhes sobre quais campos são
herdados e quais precisam ser especificados novamente, consulte
Gerenciamento de estado do lado do servidor.
Python
from google import genai
client = genai.Client()
# 1. First turn
interaction1 = client.interactions.create(
model="gemini-3-flash-preview",
input="Hi, my name is Phil."
)
print(f"Model: {interaction1.outputs[-1].text}")
# 2. Second turn (passing previous_interaction_id)
interaction2 = client.interactions.create(
model="gemini-3-flash-preview",
input="What is my name?",
previous_interaction_id=interaction1.id
)
print(f"Model: {interaction2.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. First turn
const interaction1 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Hi, my name is Phil.'
});
console.log(`Model: ${interaction1.outputs[interaction1.outputs.length - 1].text}`);
// 2. Second turn (passing previous_interaction_id)
const interaction2 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'What is my name?',
previous_interaction_id: interaction1.id
});
console.log(`Model: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
REST
# 1. First turn
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Hi, my name is Phil."
}'
# 2. Second turn (Replace INTERACTION_ID with the ID from the previous interaction)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
# "model": "gemini-3-flash-preview",
# "input": "What is my name?",
# "previous_interaction_id": "INTERACTION_ID"
# }'
Recuperar interações com estado anteriores
Usando a interação id para recuperar turnos anteriores da conversa.
Python
previous_interaction = client.interactions.get("<YOUR_INTERACTION_ID>")
print(previous_interaction)
JavaScript
const previous_interaction = await client.interactions.get("<YOUR_INTERACTION_ID>");
console.log(previous_interaction);
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/<YOUR_INTERACTION_ID>" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Incluir entrada original
Por padrão, interactions.get() retorna apenas as saídas do modelo. Para incluir a entrada normalizada original na resposta, defina include_input como true.
Python
interaction = client.interactions.get(
"<YOUR_INTERACTION_ID>",
include_input=True
)
print(f"Input: {interaction.input}")
print(f"Output: {interaction.outputs}")
JavaScript
const interaction = await client.interactions.get(
"<YOUR_INTERACTION_ID>",
{ include_input: true }
);
console.log(`Input: ${JSON.stringify(interaction.input)}`);
console.log(`Output: ${JSON.stringify(interaction.outputs)}`);
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/<YOUR_INTERACTION_ID>?include_input=true" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Conversa sem estado
Você pode gerenciar o histórico de conversas manualmente do lado do cliente.
Python
from google import genai
client = genai.Client()
conversation_history = [
{
"role": "user",
"content": "What are the three largest cities in Spain?"
}
]
interaction1 = client.interactions.create(
model="gemini-3-flash-preview",
input=conversation_history
)
print(f"Model: {interaction1.outputs[-1].text}")
conversation_history.append({"role": "model", "content": interaction1.outputs})
conversation_history.append({
"role": "user",
"content": "What is the most famous landmark in the second one?"
})
interaction2 = client.interactions.create(
model="gemini-3-flash-preview",
input=conversation_history
)
print(f"Model: {interaction2.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const conversationHistory = [
{
role: 'user',
content: "What are the three largest cities in Spain?"
}
];
const interaction1 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: conversationHistory
});
console.log(`Model: ${interaction1.outputs[interaction1.outputs.length - 1].text}`);
conversationHistory.push({ role: 'model', content: interaction1.outputs });
conversationHistory.push({
role: 'user',
content: "What is the most famous landmark in the second one?"
});
const interaction2 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: conversationHistory
});
console.log(`Model: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{
"role": "user",
"content": "What are the three largest cities in Spain?"
},
{
"role": "model",
"content": "The three largest cities in Spain are Madrid, Barcelona, and Valencia."
},
{
"role": "user",
"content": "What is the most famous landmark in the second one?"
}
]
}'
Recursos multimodais
Você pode usar a API Interactions para casos de uso multimodais, como compreensão de imagens ou geração de vídeos.
Compreensão multimodal
É possível fornecer entrada multimodal como dados codificados em base64 in-line, usando a API Files para arquivos maiores ou transmitindo um link acessível publicamente no campo uri. Os exemplos de código a seguir demonstram o método de URL público.
Compreensão de imagens
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "Describe the image."},
{
"type": "image",
"uri": "YOUR_URL",
"mime_type": "image/png"
}
]
)
print(interaction.outputs[-1].text)
JavaScript
import {GoogleGenAI} from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{type: 'text', text: 'Describe the image.'},
{
type: 'image',
uri: 'YOUR_URL',
mime_type: 'image/png'
}
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{
"type": "text",
"text": "Describe the image."
},
{
"type": "image",
"uri": "YOUR_URL",
"mime_type": "image/png"
}
]
}'
Compreensão de áudio
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "What does this audio say?"},
{
"type": "audio",
"uri": "YOUR_URL",
"mime_type": "audio/wav"
}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{ type: 'text', text: 'What does this audio say?' },
{
type: 'audio',
uri: 'YOUR_URL',
mime_type: 'audio/wav'
}
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "What does this audio say?"},
{
"type": "audio",
"uri": "YOUR_URL",
"mime_type": "audio/wav"
}
]
}'
Compreensão de vídeo
Python
from google import genai
client = genai.Client()
print("Analyzing video...")
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "What is happening in this video? Provide a timestamped summary."},
{
"type": "video",
"uri": "YOUR_URL",
"mime_type": "video/mp4"
}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
console.log('Analyzing video...');
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{ type: 'text', text: 'What is happening in this video? Provide a timestamped summary.' },
{
type: 'video',
uri: 'YOUR_URL',
mime_type: 'video/mp4'
}
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "What is happening in this video?"},
{
"type": "video",
"uri": "YOUR_URL",
"mime_type": "video/mp4"
}
]
}'
Entendimento de documentos (PDF)
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "What is this document about?"},
{
"type": "document",
"uri": "YOUR_URL",
"mime_type": "application/pdf"
}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{ type: 'text', text: 'What is this document about?' },
{
type: 'document',
uri: 'YOUR_URL',
mime_type: 'application/pdf'
}
],
});
console.log(interaction.outputs[0].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "What is this document about?"},
{
"type": "document",
"uri": "YOUR_URL",
"mime_type": "application/pdf"
}
]
}'
Geração multimodal
Você pode usar a API Interactions para gerar saídas multimodais.
Geração de imagens
Python
import base64
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-pro-image-preview",
input="Generate an image of a futuristic city.",
response_modalities=["IMAGE"]
)
for output in interaction.outputs:
if output.type == "image":
print(f"Generated image with mime_type: {output.mime_type}")
# Save the image
with open("generated_city.png", "wb") as f:
f.write(base64.b64decode(output.data))
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-pro-image-preview',
input: 'Generate an image of a futuristic city.',
response_modalities: ['IMAGE']
});
for (const output of interaction.outputs) {
if (output.type === 'image') {
console.log(`Generated image with mime_type: ${output.mime_type}`);
// Save the image
fs.writeFileSync('generated_city.png', Buffer.from(output.data, 'base64'));
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-pro-image-preview",
"input": "Generate an image of a futuristic city.",
"response_modalities": ["IMAGE"]
}'
Configurar a saída de imagem
É possível personalizar as imagens geradas usando image_config em generation_config para controlar a proporção e a resolução.
| Parâmetro | Opções | Descrição |
|---|---|---|
aspect_ratio |
1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 |
Controla a proporção entre largura e altura da imagem de saída. |
image_size |
1k, 2k, 4k |
Define a resolução da imagem de saída. |
Python
import base64
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-pro-image-preview",
input="Generate an image of a futuristic city.",
generation_config={
"image_config": {
"aspect_ratio": "9:16",
"image_size": "2k"
}
}
)
for output in interaction.outputs:
if output.type == "image":
print(f"Generated image with mime_type: {output.mime_type}")
# Save the image
with open("generated_city.png", "wb") as f:
f.write(base64.b64decode(output.data))
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-pro-image-preview',
input: 'Generate an image of a futuristic city.',
generation_config: {
image_config: {
aspect_ratio: '9:16',
image_size: '2k'
}
}
});
for (const output of interaction.outputs) {
if (output.type === 'image') {
console.log(`Generated image with mime_type: ${output.mime_type}`);
// Save the image
fs.writeFileSync('generated_city.png', Buffer.from(output.data, 'base64'));
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-pro-image-preview",
"input": "Generate an image of a futuristic city.",
"generation_config": {
"image_config": {
"aspect_ratio": "9:16",
"image_size": "2k"
}
}
}'
Geração de fala
Gerar fala com som natural a partir de texto usando o modelo de conversão de texto em voz (TTS).
Configure as configurações de voz, idioma e falante com o parâmetro speech_config.
Python
import base64
from google import genai
import wave
# Set up the wave file to save the output:
def wave_file(filename, pcm, channels=1, rate=24000, sample_width=2):
with wave.open(filename, "wb") as wf:
wf.setnchannels(channels)
wf.setsampwidth(sample_width)
wf.setframerate(rate)
wf.writeframes(pcm)
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-flash-preview-tts",
input="Say the following: WOOHOO This is so much fun!.",
response_modalities=["AUDIO"],
generation_config={
"speech_config": {
"language": "en-us",
"voice": "kore"
}
}
)
for output in interaction.outputs:
if output.type == "audio":
print(f"Generated audio with mime_type: {output.mime_type}")
# Save the audio as wave file to the current directory.
wave_file("generated_audio.wav", base64.b64decode(output.data))
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
import wav from 'wav';
async function saveWaveFile(
filename,
pcmData,
channels = 1,
rate = 24000,
sampleWidth = 2,
) {
return new Promise((resolve, reject) => {
const writer = new wav.FileWriter(filename, {
channels,
sampleRate: rate,
bitDepth: sampleWidth * 8,
});
writer.on('finish', resolve);
writer.on('error', reject);
writer.write(pcmData);
writer.end();
});
}
async function main() {
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const client = new GoogleGenAI({apiKey: GEMINI_API_KEY});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash-preview-tts',
input: 'Say the following: WOOHOO This is so much fun!.',
response_modalities: ['AUDIO'],
generation_config: {
speech_config: {
language: "en-us",
voice: "kore"
}
}
});
for (const output of interaction.outputs) {
if (output.type === 'audio') {
console.log(`Generated audio with mime_type: ${output.mime_type}`);
const audioBuffer = Buffer.from(output.data, 'base64');
// Save the audio as wave file to the current directory
await saveWaveFile("generated_audio.wav", audioBuffer);
}
}
}
await main();
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash-preview-tts",
"input": "Say the following: WOOHOO This is so much fun!.",
"response_modalities": ["AUDIO"],
"generation_config": {
"speech_config": {
"language": "en-us",
"voice": "kore"
}
}
}' | jq -r '.outputs[] | select(.type == "audio") | .data' | base64 -d > generated_audio.pcm
# You may need to install ffmpeg.
ffmpeg -f s16le -ar 24000 -ac 1 -i generated_audio.pcm generated_audio.wav
Geração de fala com vários locutores
Gere fala com vários falantes especificando os nomes deles no comando
e combinando-os no speech_config.
A solicitação precisa incluir os nomes dos participantes:
TTS the following conversation between Alice and Bob:
Alice: Hi Bob, how are you doing today?
Bob: I'm doing great, thanks for asking! How about you?
Alice: Fantastic! I just learned about the Gemini API.
Em seguida, configure o speech_config com alto-falantes correspondentes:
"generation_config": {
"speech_config": [
{"voice": "Zephyr", "speaker": "Alice", "language": "en-US"},
{"voice": "Puck", "speaker": "Bob", "language": "en-US"}
]
}
Recursos agênticos
A API Interactions foi projetada para criar e interagir com agentes e inclui suporte para chamada de função, ferramentas integradas, saídas estruturadas e o Protocolo de Contexto de Modelo (MCP).
Agentes
Você pode usar agentes especializados, como o deep-research-pro-preview-12-2025, para
tarefas complexas. Para saber mais sobre o agente Deep Research do Gemini, consulte o guia Deep Research.
Python
import time
from google import genai
client = genai.Client()
# 1. Start the Deep Research Agent
initial_interaction = client.interactions.create(
input="Research the history of the Google TPUs with a focus on 2025 and 2026.",
agent="deep-research-pro-preview-12-2025",
background=True
)
print(f"Research started. Interaction ID: {initial_interaction.id}")
# 2. Poll for results
while True:
interaction = client.interactions.get(initial_interaction.id)
print(f"Status: {interaction.status}")
if interaction.status == "completed":
print("\nFinal Report:\n", interaction.outputs[-1].text)
break
elif interaction.status in ["failed", "cancelled"]:
print(f"Failed with status: {interaction.status}")
break
time.sleep(10)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. Start the Deep Research Agent
const initialInteraction = await client.interactions.create({
input: 'Research the history of the Google TPUs with a focus on 2025 and 2026.',
agent: 'deep-research-pro-preview-12-2025',
background: true
});
console.log(`Research started. Interaction ID: ${initialInteraction.id}`);
// 2. Poll for results
while (true) {
const interaction = await client.interactions.get(initialInteraction.id);
console.log(`Status: ${interaction.status}`);
if (interaction.status === 'completed') {
console.log('\nFinal Report:\n', interaction.outputs[interaction.outputs.length - 1].text);
break;
} else if (['failed', 'cancelled'].includes(interaction.status)) {
console.log(`Failed with status: ${interaction.status}`);
break;
}
await new Promise(resolve => setTimeout(resolve, 10000));
}
REST
# 1. Start the Deep Research Agent
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"input": "Research the history of the Google TPUs with a focus on 2025 and 2026.",
"agent": "deep-research-pro-preview-12-2025",
"background": true
}'
# 2. Poll for results (Replace INTERACTION_ID with the ID from the previous interaction)
# curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID" \
# -H "x-goog-api-key: $GEMINI_API_KEY"
Ferramentas e chamada de função
Esta seção explica como usar a chamada de função para definir ferramentas personalizadas e como usar as ferramentas integradas do Google na API Interactions.
Chamadas de função
Python
from google import genai
client = genai.Client()
# 1. Define the tool
def get_weather(location: str):
"""Gets the weather for a given location."""
return f"The weather in {location} is sunny."
weather_tool = {
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
},
"required": ["location"]
}
}
# 2. Send the request with tools
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="What is the weather in Paris?",
tools=[weather_tool]
)
# 3. Handle the tool call
for output in interaction.outputs:
if output.type == "function_call":
print(f"Tool Call: {output.name}({output.arguments})")
# Execute tool
result = get_weather(**output.arguments)
# Send result back
interaction = client.interactions.create(
model="gemini-3-flash-preview",
previous_interaction_id=interaction.id,
input=[{
"type": "function_result",
"name": output.name,
"call_id": output.id,
"result": result
}]
)
print(f"Response: {interaction.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. Define the tool
const weatherTool = {
type: 'function',
name: 'get_weather',
description: 'Gets the weather for a given location.',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA' }
},
required: ['location']
}
};
// 2. Send the request with tools
let interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'What is the weather in Paris?',
tools: [weatherTool]
});
// 3. Handle the tool call
for (const output of interaction.outputs) {
if (output.type === 'function_call') {
console.log(`Tool Call: ${output.name}(${JSON.stringify(output.arguments)})`);
// Execute tool (Mocked)
const result = `The weather in ${output.arguments.location} is sunny.`;
// Send result back
interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
previous_interaction_id:interaction.id,
input: [{
type: 'function_result',
name: output.name,
call_id: output.id,
result: result
}]
});
console.log(`Response: ${interaction.outputs[interaction.outputs.length - 1].text}`);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "What is the weather in Paris?",
"tools": [{
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
},
"required": ["location"]
}
}]
}'
# Handle the tool call and send result back (Replace INTERACTION_ID and CALL_ID)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
# "model": "gemini-3-flash-preview",
# "previous_interaction_id": "INTERACTION_ID",
# "input": [{
# "type": "function_result",
# "name": "get_weather",
# "call_id": "FUNCTION_CALL_ID",
# "result": "The weather in Paris is sunny."
# }]
# }'
Chamada de função com estado do lado do cliente
Se você não quiser usar o estado do lado do servidor, poderá gerenciar tudo no lado do cliente.
Python
from google import genai
client = genai.Client()
functions = [
{
"type": "function",
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {"type": "array", "items": {"type": "string"}},
"date": {"type": "string", "description": "Date of the meeting (e.g., 2024-07-29)"},
"time": {"type": "string", "description": "Time of the meeting (e.g., 15:00)"},
"topic": {"type": "string", "description": "The subject of the meeting."},
},
"required": ["attendees", "date", "time", "topic"],
},
}
]
history = [{"role": "user","content": [{"type": "text", "text": "Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen API."}]}]
# 1. Model decides to call the function
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=history,
tools=functions
)
# add model interaction back to history
history.append({"role": "model", "content": interaction.outputs})
for output in interaction.outputs:
if output.type == "function_call":
print(f"Function call: {output.name} with arguments {output.arguments}")
# 2. Execute the function and get a result
# In a real app, you would call your function here.
# call_result = schedule_meeting(**json.loads(output.arguments))
call_result = "Meeting scheduled successfully."
# 3. Send the result back to the model
history.append({"role": "user", "content": [{"type": "function_result", "name": output.name, "call_id": output.id, "result": call_result}]})
interaction2 = client.interactions.create(
model="gemini-3-flash-preview",
input=history,
)
print(f"Final response: {interaction2.outputs[-1].text}")
else:
print(f"Output: {output}")
JavaScript
// 1. Define the tool
const functions = [
{
type: 'function',
name: 'schedule_meeting',
description: 'Schedules a meeting with specified attendees at a given time and date.',
parameters: {
type: 'object',
properties: {
attendees: { type: 'array', items: { type: 'string' } },
date: { type: 'string', description: 'Date of the meeting (e.g., 2024-07-29)' },
time: { type: 'string', description: 'Time of the meeting (e.g., 15:00)' },
topic: { type: 'string', description: 'The subject of the meeting.' },
},
required: ['attendees', 'date', 'time', 'topic'],
},
},
];
const history = [
{ role: 'user', content: [{ type: 'text', text: 'Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen API.' }] }
];
// 2. Model decides to call the function
let interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: history,
tools: functions
});
// add model interaction back to history
history.push({ role: 'model', content: interaction.outputs });
for (const output of interaction.outputs) {
if (output.type === 'function_call') {
console.log(`Function call: ${output.name} with arguments ${JSON.stringify(output.arguments)}`);
// 3. Send the result back to the model
history.push({ role: 'user', content: [{ type: 'function_result', name: output.name, call_id: output.id, result: 'Meeting scheduled successfully.' }] });
const interaction2 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: history,
});
console.log(`Final response: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
}
}
Resultados de função multimodal
O campo result em um function_result aceita uma string simples ou uma matriz de objetos TextContent e ImageContent. Isso permite retornar imagens, como capturas de tela ou gráficos, junto com o texto das chamadas de função, para que o modelo possa analisar a saída visual.
Python
import base64
from google import genai
client = genai.Client()
functions = [
{
"type": "function",
"name": "take_screenshot",
"description": "Takes a screenshot of a specified website.",
"parameters": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "The URL to take a screenshot of."},
},
"required": ["url"],
},
}
]
# 1. Model decides to call the function
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Can you take a screenshot of https://google.com and tell me what you see?",
tools=functions
)
for output in interaction.outputs:
if output.type == "function_call":
print(f"Function call: {output.name}({output.arguments})")
# 2. Execute the function and load the image
# Replace with actual function call, pseudo code for reading image from disk
with open("screenshot.png", "rb") as f:
base64_image = base64.b64encode(f.read()).decode("utf-8")
# 3. Return a multimodal result (text + image)
call_result = [
{"type": "text", "text": "Screenshot captured successfully."},
{"type": "image", "mime_type": "image/png", "data": base64_image}
]
response = client.interactions.create(
model="gemini-3-flash-preview",
tools=functions,
previous_interaction_id=interaction.id,
input=[{
"type": "function_result",
"name": output.name,
"call_id": output.id,
"result": call_result
}]
)
print(f"Response: {response.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const functions = [
{
type: 'function',
name: 'take_screenshot',
description: 'Takes a screenshot of a specified website.',
parameters: {
type: 'object',
properties: {
url: { type: 'string', description: 'The URL to take a screenshot of.' },
},
required: ['url'],
},
}
];
// 1. Model decides to call the function
let interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Can you take a screenshot of https://google.com and tell me what you see?',
tools: functions
});
for (const output of interaction.outputs) {
if (output.type === 'function_call') {
console.log(`Function call: ${output.name}(${JSON.stringify(output.arguments)})`);
// 2. Execute the function and load the image
// Replace with actual function call, pseudo code for reading image from disk
const base64Image = fs.readFileSync('screenshot.png').toString('base64');
// 3. Return a multimodal result (text + image)
const callResult = [
{ type: 'text', text: 'Screenshot captured successfully.' },
{ type: 'image', mime_type: 'image/png', data: base64Image }
];
const response = await client.interactions.create({
model: 'gemini-3-flash-preview',
tools: functions,
previous_interaction_id: interaction.id,
input: [{
type: 'function_result',
name: output.name,
call_id: output.id,
result: callResult
}]
});
console.log(`Response: ${response.outputs[response.outputs.length - 1].text}`);
}
}
REST
# 1. Send request with tools (will return a function_call)
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Can you take a screenshot of https://google.com and tell me what you see?",
"tools": [{
"type": "function",
"name": "take_screenshot",
"description": "Takes a screenshot of a specified website.",
"parameters": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "The URL to take a screenshot of."}
},
"required": ["url"]
}
}]
}'
# 2. Send multimodal result back (Replace INTERACTION_ID, CALL_ID, and BASE64_IMAGE)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
# "model": "gemini-3-flash-preview",
# "tools": [{"type": "function", "name": "take_screenshot", "description": "Takes a screenshot of a specified website.", "parameters": {"type": "object", "properties": {"url": {"type": "string"}}, "required": ["url"]}}],
# "previous_interaction_id": "INTERACTION_ID",
# "input": [{
# "type": "function_result",
# "name": "take_screenshot",
# "call_id": "CALL_ID",
# "result": [
# {"type": "text", "text": "Screenshot captured successfully."},
# {"type": "image", "mime_type": "image/png", "data": "BASE64_IMAGE"}
# ]
# }]
# }'
Ferramentas integradas
O Gemini vem com ferramentas integradas, como Embasamento com a Pesquisa Google, Embasamento com a Pesquisa de Imagens do Google, Embasamento com o Google Maps, Execução de código, Contexto de URL e Uso do computador
Embasamento com a Pesquisa Google
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Who won the last Super Bowl?",
tools=[{"type": "google_search"}]
)
# Find the text output (not the GoogleSearchResultContent)
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
print(text_output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Who won the last Super Bowl?',
tools: [{ type: 'google_search' }]
});
// Find the text output (not the GoogleSearchResultContent)
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Who won the last Super Bowl?",
"tools": [{"type": "google_search"}]
}'
Embasamento com a Pesquisa de imagens do Google (somente para imagens em Flash 3.1)
O embasamento com a Pesquisa de imagens do Google permite que os modelos usem imagens da Web recuperadas pela Pesquisa de imagens do Google como contexto visual para a geração de imagens. A Pesquisa de imagens é um novo tipo de pesquisa na ferramenta de embasamento com a Pesquisa Google, que funciona junto com a Pesquisa na Web padrão.
Como ativar a pesquisa por imagens
Solicite resultados de imagens adicionando "image_search" à matriz search_types da ferramenta google_search.
Python
interaction = client.interactions.create(
model="gemini-3.1-flash-image-preview",
input="Search for an image of a vintage gold bitcoin coin.",
tools=[{
"type": "google_search",
"search_types": ["web_search", "image_search"]
}]
)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3.1-flash-image-preview',
input: 'Search for an image of a vintage gold bitcoin coin.',
tools: [{
type: 'google_search',
search_types: ['web_search', 'image_search']
}]
});
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3.1-flash-image-preview",
"input": "Search for an image of a vintage gold bitcoin coin.",
"tools": [{
"type": "google_search",
"search_types": ["web_search", "image_search"]
}]
}'
Requisitos obrigatórios de exibição
Para obedecer aos Termos de pesquisa do Google Search, sua interface precisa implementar dois níveis distintos de atribuição:
Atribuição da Pesquisa Google
Você precisa mostrar as sugestões de pesquisa "Confira no Google" fornecidas no bloco
google_search_result.- Campo:
rendered_content(HTML/CSS) - Ação:renderize esse ícone como está perto da resposta do modelo.
- Campo:
Atribuição do publisher
Você precisa fornecer um link para a "página de contêiner" (a página de destino) de cada imagem exibida.
- Campo:
url(encontrado na matrizresult) - Requisito:você precisa fornecer um caminho direto de um único clique da imagem para a página da Web de origem que a contém. Não é permitido usar visualizadores de imagens intermediários ou caminhos de vários cliques.
- Campo:
Como processar respostas embasadas
O snippet a seguir demonstra como processar os blocos de resposta intercalados para dados de imagem bruta e atribuição obrigatória.
Python
for output in interaction.outputs:
# 1. Handle raw multimodal image data
if output.type == "image":
print(f"🖼️ Image received: {output.mime_type}")
# 'data' contains base64-encoded image content
display_image(output.data, output.mime_type)
# 2. Handle mandatory Search and Publisher attribution
elif output.type == "google_search_result":
# Display Google Search Attribution
if output.rendered_content:
render_html_chips(output.rendered_content)
# Provide Publisher Attribution
for source in output.result:
print(f"Source Page: {source['url']}")
JavaScript
for (const output of interaction.outputs) {
// 1. Handle raw multimodal image data
if (output.type === 'image') {
console.log(`🖼️ Image received: ${output.mimeType}`);
// 'data' contains base64-encoded image content
displayImage(output.data, output.mimeType);
}
// 2. Handle mandatory Search and Publisher attribution
else if (output.type === 'google_search_result') {
// Display Google Search Attribution
if (output.renderedContent) {
renderHtmlChips(output.renderedContent);
}
// Provide Publisher Attribution
for (const source of output.result) {
console.log(`Source Page: ${source.url}`);
}
}
}
Esquema de saída esperado
O bloco de imagem (tipo: "image") contém os dados visuais brutos gerados ou recuperados pelo modelo.
{
"type": "image",
"mime_type": "image/png",
"data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB..." // Base64 content
}
O bloco de resultados (tipo: "google_search_result") contém os metadados de atribuição obrigatórios vinculados à pesquisa.
{
"type": "google_search_result",
"call_id": "search_002",
"rendered_content": "<div class=\"search-suggestions\">...</div>", // Google Search Attribution
"result": [
{
"url": "https://example.com/source-page", // Publisher Attribution
"title": "Source Page Title"
}
]
}
Embasamento com o Google Maps
O embasamento com o Google Maps permite que os modelos usem dados do Google Maps para contexto visual, marcadores de mapa e descoberta baseada em localização.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="What's the best coffee shop near me?",
tools=[{"type": "google_maps"}]
)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'What\'s the best coffee shop near me?',
tools: [{ type: 'google_maps' }]
});
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "What is the best coffee shop near me?",
"tools": [{"type": "google_maps"}]
}'
Requisitos de uso do serviço
Ao apresentar resultados do embasamento com o Google Maps, siga os Termos de Serviço do Google Maps. Você precisa informar os usuários sobre o seguinte e atender a estes requisitos de exibição:
- Informe o usuário: logo após o conteúdo gerado, inclua as fontes associadas do Google Maps. As fontes precisam ser visíveis em uma interação do usuário.
- Links de exibição: gere uma prévia de link para cada fonte, incluindo snippets de avaliação, se houver.
- Atribuição ao "Google Maps": siga as diretrizes de atribuição de texto.
- Mostrar o título da fonte.
- Linke à fonte usando o URL fornecido.
- Diretrizes de atribuição: não modifique o texto "Google Maps" (uso de maiúsculas, quebra de linha). Impedir a tradução do navegador usando
translate="no".
Como processar a resposta
O snippet a seguir demonstra como processar a resposta extraindo o texto e as citações inline (incluindo snippets de avaliação) para atender aos requisitos de exibição.
Python
for output in interaction.outputs:
if output.type == "text":
print(output.text)
if output.annotations:
print("\nSources:")
for annotation in output.annotations:
if annotation.get("type") == "place_citation":
# Display place citation
print(f"- {annotation['name']} (Google Maps): {annotation['url']}")
# Display review snippets if available
if "review_snippets" in annotation:
for snippet in annotation["review_snippets"]:
print(f" - Review: {snippet['title']} ({snippet['url']})")
elif output.type == "google_maps_result":
# You can also access the raw place data here if needed for map pins
pass
JavaScript
for (const output of interaction.outputs) {
if (output.type === 'text') {
console.log(output.text);
if (output.annotations) {
console.log('\nSources:');
for (const annotation of output.annotations) {
if (annotation.type === 'place_citation') {
console.log(`- ${annotation.name} (Google Maps): ${annotation.url}`);
if (annotation.review_snippets) {
for (const snippet of annotation.review_snippets) {
console.log(` - Review: ${snippet.title} (${snippet.url})`);
}
}
}
}
}
}
}
Esquema de saída esperado
Confira o esquema de saída ao usar o Embasamento com o Google Maps.
O bloco de resultados (tipo: "google_maps_result") contém os dados estruturados do lugar.
{
"type": "google_maps_result",
"call_id": "maps_001",
"result": {
"places": [
{
"place_id": "ChIJ...",
"name": "Blue Bottle Coffee", // Google Maps Source
"url": "https://maps.google.com/?cid=...", // Google Maps Link
"review_snippets": [
{
"title": "Amazing single-origin selections",
"url": "https://maps.google.com/...",
"review_id": "def456"
}
]
}
],
"widget_context_token": "widgetcontent/..."
},
"signature": "..."
}
O bloco de texto (tipo: "text") contém o conteúdo gerado com anotações inline.
{
"type": "text",
"text": "Blue Bottle Coffee (4.5★) on Mint Plaza was rated highly online...",
"annotations": [
{
"type": "place_citation",
"place_id": "ChIJ...",
"name": "Blue Bottle Coffee", // Google Maps Source
"url": "https://maps.google.com/?cid=...", // Google Maps Link
"review_snippets": [
{
"title": "Amazing single-origin selections",
"url": "https://maps.google.com/...",
"review_id": "def456"
}
],
"start_index": 0,
"end_index": 42
}
]
}
Execução de código
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Calculate the 50th Fibonacci number.",
tools=[{"type": "code_execution"}]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Calculate the 50th Fibonacci number.',
tools: [{ type: 'code_execution' }]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Calculate the 50th Fibonacci number.",
"tools": [{"type": "code_execution"}]
}'
Contexto do URL
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Summarize the content of https://www.wikipedia.org/",
tools=[{"type": "url_context"}]
)
# Find the text output (not the URLContextResultContent)
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
print(text_output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Summarize the content of https://www.wikipedia.org/',
tools: [{ type: 'url_context' }]
});
// Find the text output (not the URLContextResultContent)
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Summarize the content of https://www.wikipedia.org/",
"tools": [{"type": "url_context"}]
}'
Uso do computador
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-computer-use-preview-10-2025",
input="Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.",
tools=[{
"type": "computer_use",
"environment": "browser",
"excludedPredefinedFunctions": ["drag_and_drop"]
}]
)
# The response will contain tool calls (actions) for the computer interface
# or text explaining the action
for output in interaction.outputs:
print(output)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-2.5-computer-use-preview-10-2025',
input: 'Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.',
tools: [{
type: 'computer_use',
environment: 'browser',
excludedPredefinedFunctions: ['drag_and_drop']
}]
});
// The response will contain tool calls (actions) for the computer interface
// or text explaining the action
interaction.outputs.forEach(output => console.log(output));
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-computer-use-preview-10-2025",
"input": "Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.",
"tools": [{
"type": "computer_use",
"environment": "browser",
"excludedPredefinedFunctions": ["drag_and_drop"]
}]
}'
Pesquisa de arquivos
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me about the book 'I, Claudius'",
tools=[{"type": "file_search", "file_search_store_names": ["fileSearchStores/my-store-name"]}]
)
# Find the text output
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
print(text_output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: "Tell me about the book 'I, Claudius'",
tools: [{ type: 'file_search', file_search_store_names: ['fileSearchStores/my-store-name'] }]
});
// Find the text output
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Tell me about the book I, Claudius",
"tools": [{"type": "file_search", "file_search_store_names": ["fileSearchStores/my-store-name"]}]
}'
Como combinar ferramentas integradas e chamadas de função
Você pode usar ferramentas integradas e chamadas de função juntas na mesma solicitação.
Python
from google import genai
import json
client = genai.Client()
get_weather = {
"type": "function",
"name": "getWeather",
"description": "Gets the weather for a requested city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city and state, e.g. Utqiaġvik, Alaska",
},
},
"required": ["city"],
},
}
tools = [
{"type": "google_search"}, # Built-in tool
get_weather # Custom tool (callable)
]
# Turn 1: Initial request with both tools enabled
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="What is the northernmost city in the United States? What's the weather like there today?",
tools=tools
)
for output in interaction.outputs:
if output.type == "function_call":
print(f"Function call: {output.name} (ID: {output.id})")
# Execute your custom function locally
result = {"response": "Very cold. 22 degrees Fahrenheit."}
# Turn 2: Provide the function result back to the model.
# Passing `previous_interaction_id` automatically circulates the
# built-in Google Search context (and thought signatures) from Turn 1
interaction_2 = client.interactions.create(
model="gemini-3-flash-preview",
previous_interaction_id=interaction.id,
tools=tools,
input=[{
"type": "function_result",
"name": output.name,
"call_id": output.id,
"result": json.dumps(result)
}]
)
for output in interaction_2.outputs:
if output.type == "text":
print(output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const weatherTool = {
type: 'function',
name: 'get_weather',
description: 'Gets the weather for a given location.',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA' }
},
required: ['location']
}
};
const tools = [
{type: 'google_search'}, // Built-in tool
weatherTool // Custom tool
];
// Turn 1: Initial request with both tools enabled
let interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: "What is the northernmost city in the United States? What's the weather like there today?",
tools: tools
});
for (const output of interaction.outputs) {
if (output.type == "function_call") {
console.log(`Function call: ${output.name} (ID: ${output.id})`);
// Execute your custom function locally
const result = {response: "Very cold. 22 degrees Fahrenheit."};
// Turn 2: Provide the function result back to the model.
// Passing `previous_interaction_id` automatically circulates the
// built-in Google Search context (and thought signatures) from Turn 1
const interaction_2 = await client.interactions.create({
model: "gemini-3-flash-preview",
previous_interaction_id: interaction.id,
tools: tools,
input: [{
type: "function_result",
name: output.name,
call_id: output.id,
result: JSON.stringify(result)
}]
});
for (const output_2 of interaction_2.outputs) {
if (output_2.type == "text") {
console.log(output_2.text);
}
}
}
}
REST
# Turn 1: Initial request with both tools enabled
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "What is the northernmost city in the United States? What is the weather like there today?",
"tools": [
{"type": "google_search"},
{
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
},
"required": ["location"]
}
}
]
}'
# Assuming Turn 1 returns a function_call for get_weather,
# replace INTERACTION_ID and CALL_ID with values from Turn 1 response.
# Turn 2: Provide the function result back to the model.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"previous_interaction_id": "INTERACTION_ID",
"tools": [
{"type": "google_search"},
{
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
},
"required": ["location"]
}
}
],
"input": [{
"type": "function_result",
"name": "get_weather",
"call_id": "CALL_ID",
"result": "{\"response\": \"Very cold. 22 degrees Fahrenheit.\"}"
}]
}'
Como entender a circulação do contexto da ferramenta
O Gemini 3 e modelos mais recentes oferecem suporte à circulação de contexto de ferramentas para manter uma "memória" confiável das ações do lado do servidor. Quando uma ferramenta integrada (como a Pesquisa Google) é acionada, a API gera partes específicas de toolCall e toolResponse. Essas partes contêm o contexto preciso de que o modelo precisa para argumentar sobre esses resultados na próxima vez.
- Com estado (recomendado): se você usar
previous_interaction_id, a API vai gerenciar essa circulação automaticamente. - Sem estado: se você gerenciar o histórico manualmente, inclua esses blocos exatamente como foram retornados pela API na sua matriz de entrada.
Protocolo de contexto de modelo (MCP) remoto
A integração remota do MCP simplifica o desenvolvimento de agentes, permitindo que a API Gemini chame diretamente ferramentas externas hospedadas em servidores remotos.
Python
import datetime
from google import genai
client = genai.Client()
mcp_server = {
"type": "mcp_server",
"name": "weather_service",
"url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
}
today = datetime.date.today().strftime("%d %B %Y")
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="What is the weather like in New York today?",
tools=[mcp_server],
system_instruction=f"Today is {today}."
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const mcpServer = {
type: 'mcp_server',
name: 'weather_service',
url: 'https://gemini-api-demos.uc.r.appspot.com/mcp'
};
const today = new Date().toDateString();
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'What is the weather like in New York today?',
tools: [mcpServer],
system_instruction: `Today is ${today}.`
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "What is the weather like in New York today?",
"tools": [{
"type": "mcp_server",
"name": "weather_service",
"url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
}],
"system_instruction": "Today is '"$(date +"%du%Bt%Y")"' YYYY-MM-DD>."
}'
Observações importantes:
- O MCP remoto só funciona com servidores HTTP de streaming (servidores SSE não são compatíveis).
- O MCP remoto não funciona com os modelos do Gemini 3 (isso será lançado em breve)
- Os nomes de servidores MCP não podem incluir o caractere "-". Use nomes de servidores snake_case.
Saída estruturada (esquema JSON)
Forçar uma saída JSON específica fornecendo um esquema JSON no parâmetro response_format. Isso é útil para tarefas como moderação,
classificação ou extração de dados.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import Literal, Union
client = genai.Client()
class SpamDetails(BaseModel):
reason: str = Field(description="The reason why the content is considered spam.")
spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"]
class NotSpamDetails(BaseModel):
summary: str = Field(description="A brief summary of the content.")
is_safe: bool = Field(description="Whether the content is safe for all audiences.")
class ModerationResult(BaseModel):
decision: Union[SpamDetails, NotSpamDetails]
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format=ModerationResult.model_json_schema(),
)
parsed_output = ModerationResult.model_validate_json(interaction.outputs[-1].text)
print(parsed_output)
JavaScript
import { GoogleGenAI } from '@google/genai';
import { z } from 'zod';
const client = new GoogleGenAI({});
const moderationSchema = z.object({
decision: z.union([
z.object({
reason: z.string().describe('The reason why the content is considered spam.'),
spam_type: z.enum(['phishing', 'scam', 'unsolicited promotion', 'other']).describe('The type of spam.'),
}).describe('Details for content classified as spam.'),
z.object({
summary: z.string().describe('A brief summary of the content.'),
is_safe: z.boolean().describe('Whether the content is safe for all audiences.'),
}).describe('Details for content classified as not spam.'),
]),
});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: "Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format: z.toJSONSchema(moderationSchema),
});
console.log(interaction.outputs[0].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
"response_format": {
"type": "object",
"properties": {
"decision": {
"type": "object",
"properties": {
"reason": {"type": "string", "description": "The reason why the content is considered spam."},
"spam_type": {"type": "string", "description": "The type of spam."}
},
"required": ["reason", "spam_type"]
}
},
"required": ["decision"]
}
}'
Combinar ferramentas e saída estruturada
Combine ferramentas integradas com saída estruturada para receber um objeto JSON confiável com base nas informações recuperadas por uma ferramenta.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import Literal, Union
client = genai.Client()
class SpamDetails(BaseModel):
reason: str = Field(description="The reason why the content is considered spam.")
spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"]
class NotSpamDetails(BaseModel):
summary: str = Field(description="A brief summary of the content.")
is_safe: bool = Field(description="Whether the content is safe for all audiences.")
class ModerationResult(BaseModel):
decision: Union[SpamDetails, NotSpamDetails]
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format=ModerationResult.model_json_schema(),
tools=[{"type": "url_context"}]
)
parsed_output = ModerationResult.model_validate_json(interaction.outputs[-1].text)
print(parsed_output)
JavaScript
import { GoogleGenAI } from '@google/genai';
import { z } from 'zod'; // Assuming zod is used for schema generation, or define manually
const client = new GoogleGenAI({});
const obj = z.object({
winning_team: z.string(),
score: z.string(),
});
const schema = z.toJSONSchema(obj);
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Who won the last euro?',
tools: [{ type: 'google_search' }],
response_format: schema,
});
console.log(interaction.outputs[0].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Who won the last euro?",
"tools": [{"type": "google_search"}],
"response_format": {
"type": "object",
"properties": {
"winning_team": {"type": "string"},
"score": {"type": "string"}
}
}
}'
Recursos avançados
Há também outros recursos avançados que oferecem mais flexibilidade ao trabalhar com a API Interactions.
Streaming
Receber respostas de forma incremental à medida que são geradas.
Quando stream=true, o evento interaction.complete final não contém o conteúdo gerado no campo outputs. Ele contém apenas metadados de uso e o status final. É necessário agregar eventos content.delta do lado do cliente para
reconstruir a resposta completa ou os argumentos de chamada de função.
Python
from google import genai
client = genai.Client()
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)
elif chunk.delta.type == "thought":
print(chunk.delta.thought, end="", flush=True)
elif chunk.event_type == "interaction.complete":
print(f"\n\n--- Stream Finished ---")
print(f"Total Tokens: {chunk.interaction.usage.total_tokens}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
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' && 'text' in chunk.delta) {
process.stdout.write(chunk.delta.text);
} else if (chunk.delta.type === 'thought' && 'thought' in chunk.delta) {
process.stdout.write(chunk.delta.thought);
}
} else if (chunk.event_type === 'interaction.complete') {
console.log('\n\n--- Stream Finished ---');
console.log(`Total Tokens: ${chunk.interaction.usage.total_tokens}`);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Explain quantum entanglement in simple terms.",
"stream": true
}'
Tipos de eventos de transmissão
Quando o streaming está ativado, a API retorna eventos enviados pelo servidor (SSE). Cada evento tem um campo event_type que indica a finalidade dele. A lista completa de tipos de eventos está disponível na referência da API.
| Tipo de evento | Descrição |
|---|---|
interaction.start |
Primeiro evento. Contém a interação id e o status inicial (in_progress). |
interaction.status_update |
Indica mudanças de status (por exemplo, in_progress). |
content.start |
Marca o início de um novo bloco de saída. Contém index e conteúdo type (por exemplo, text, thought). |
content.delta |
Atualizações incrementais de conteúdo. Contém os dados parciais com chave delta.type. |
content.stop |
Marca o fim de um bloco de saída em index. |
interaction.complete |
Evento final. Contém id, status, usage e metadados. Observação:outputs é None. É necessário reconstruir as saídas dos eventos content.*. |
error |
Indica que ocorreu um erro. Contém error.code e error.message. |
Reconstruir o objeto de interação com base em eventos de streaming
Ao contrário das respostas sem streaming, as respostas com streaming não contêm uma matriz
outputs. É necessário reconstruir as saídas acumulando conteúdo dos eventos
content.delta.
Python
from google import genai
client = genai.Client()
stream = client.interactions.create(
model="gemini-3-flash-preview",
input="Write a haiku about Python programming.",
stream=True
)
# Accumulate outputs by index
outputs = {}
usage = None
for chunk in stream:
if chunk.event_type == "content.start":
outputs[chunk.index] = {"type": chunk.content.type}
elif chunk.event_type == "content.delta":
output = outputs[chunk.index]
if chunk.delta.type == "text":
output["text"] = output.get("text", "") + chunk.delta.text
elif chunk.delta.type == "thought_signature":
output["signature"] = chunk.delta.signature
elif chunk.delta.type == "thought_summary":
output["summary"] = output.get("summary", "") + getattr(chunk.delta.content, "text", "")
elif chunk.event_type == "interaction.complete":
usage = chunk.interaction.usage
# Final outputs list (sorted by index)
final_outputs = [outputs[i] for i in sorted(outputs.keys())]
print(f"\n\nOutputs: {final_outputs}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const stream = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Write a haiku about Python programming.',
stream: true,
});
// Accumulate outputs by index
const outputs = new Map();
let usage = null;
for await (const chunk of stream) {
if (chunk.event_type === 'content.start') {
outputs.set(chunk.index, { type: chunk.content.type });
} else if (chunk.event_type === 'content.delta') {
const output = outputs.get(chunk.index);
if (chunk.delta.type === 'text') {
output.text = (output.text || '') + chunk.delta.text;
process.stdout.write(chunk.delta.text);
} else if (chunk.delta.type === 'thought_signature') {
output.signature = chunk.delta.signature;
} else if (chunk.delta.type === 'thought_summary') {
output.summary = (output.summary || '') + (chunk.delta.content?.text || '');
}
} else if (chunk.event_type === 'interaction.complete') {
usage = chunk.interaction.usage;
}
}
// Final outputs list (sorted by index)
const finalOutputs = [...outputs.entries()]
.sort((a, b) => a[0] - b[0])
.map(([_, output]) => output);
console.log(`\n\nOutputs:`, finalOutputs);
Chamadas de ferramentas de streaming
Ao usar ferramentas com streaming, o modelo gera chamadas de função como uma sequência de
eventos content.delta no stream. Ao contrário do texto, os argumentos da ferramenta são entregues como
objetos JSON completos em um único evento content.delta. A matriz outputs está vazia no evento interaction.complete durante o streaming. Você precisa capturar as chamadas de função dos deltas, conforme mostrado abaixo.
Python
from google import genai
import json
client = genai.Client()
weather_tool = {
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state"}
},
"required": ["location"]
}
}
stream = client.interactions.create(
model="gemini-3-flash-preview",
input="What is the weather in Paris?",
tools=[weather_tool],
stream=True
)
# A map to capture tool calls by their ID as they arrive
function_calls = {}
for chunk in stream:
if chunk.event_type == "content.delta":
if chunk.delta.type == "text" and chunk.delta.text:
print(chunk.delta.text, end="", flush=True)
elif chunk.delta.type == "function_call":
print(f"\nExecuting {chunk.delta.name} immediately...")
# result = my_tools[chunk.delta.name](**chunk.delta.arguments)
function_calls[chunk.delta.id] = chunk.delta
elif chunk.event_type == "interaction.complete":
print("\n\nAll tools executed. Stream finished.")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const weatherTool = {
type: 'function',
name: 'get_weather',
description: 'Gets the weather for a given location.',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'The city and state' }
},
required: ['location']
}
};
const stream = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'What is the weather in Paris?',
tools: [weatherTool],
stream: true,
});
const toolCalls = new Map();
for await (const chunk of stream) {
if (chunk.event_type === 'content.delta') {
if (chunk.delta.type === 'text' && chunk.delta.text) {
process.stdout.write(chunk.delta.text);
} else if (chunk.delta.type === 'function_call') {
console.log(`\nExecuting ${chunk.delta.name} immediately...`);
// const result = myTools[chunk.delta.name](chunk.delta.arguments);
toolCalls.set(chunk.delta.id, chunk.delta);
}
} else if (chunk.event_type === 'interaction.complete') {
console.log('\n\nAll tools executed. Stream finished.');
}
}
REST
# When streaming via SSE, capture function_call data from content.delta events.
# The 'arguments' field arrives as a complete JSON object once generated.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "What is the weather in Paris?",
"tools": [{
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state"}
},
"required": ["location"]
}
}],
"stream": true
}'
Configuração
Personalize o comportamento do modelo com generation_config.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me a story about a brave knight.",
generation_config={
"temperature": 0.7,
"max_output_tokens": 500,
"thinking_level": "low",
}
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a story about a brave knight.',
generation_config: {
temperature: 0.7,
max_output_tokens: 500,
thinking_level: 'low',
}
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Tell me a story about a brave knight.",
"generation_config": {
"temperature": 0.7,
"max_output_tokens": 500,
"thinking_level": "low"
}
}'
Pensando
Os modelos Gemini 2.5 e mais recentes usam um processo interno de raciocínio chamado "pensamento" antes de gerar uma resposta. Isso ajuda o modelo a produzir respostas melhores para tarefas complexas, como matemática, programação e raciocínio em várias etapas.
Nível de pensamento
O parâmetro thinking_level permite controlar a profundidade do raciocínio do modelo:
| Nível | Descrição | Modelos compatíveis |
|---|---|---|
minimal |
Corresponde à configuração "sem pensar" para a maioria das consultas. Em alguns casos, os modelos podem pensar de forma muito limitada. Minimiza a latência e o custo. | Somente modelos Flash (por exemplo, Gemini 3 Flash) |
low |
Raciocínio leve que prioriza a latência e a economia de custos para seguir instruções simples e conversar. | Todos os modelos de pensamento |
medium |
Pensamento equilibrado para a maioria das tarefas. | Somente modelos Flash (por exemplo, Gemini 3 Flash) |
high |
(Padrão): maximiza a profundidade do raciocínio. O modelo pode levar muito mais tempo para alcançar um primeiro token, mas a saída será mais bem fundamentada. | Todos os modelos de pensamento |
Resumos de pensamentos
O raciocínio do modelo é representado como blocos de pensamento (type: "thought") nas saídas de resposta. É possível controlar se você quer receber resumos legíveis
do processo de pensamento usando o parâmetro thinking_summaries:
| Valor | Descrição |
|---|---|
auto |
(Padrão): retorna resumos de ideias quando disponíveis. |
none |
Desativa os resumos de ideias. |
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Solve this step by step: What is 15% of 240?",
generation_config={
"thinking_level": "high",
"thinking_summaries": "auto"
}
)
for output in interaction.outputs:
if output.type == "thought":
print(f"Thinking: {output.summary}")
elif output.type == "text":
print(f"Answer: {output.text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Solve this step by step: What is 15% of 240?',
generation_config: {
thinking_level: 'high',
thinking_summaries: 'auto'
}
});
for (const output of interaction.outputs) {
if (output.type === 'thought') {
console.log(`Thinking: ${output.summary}`);
} else if (output.type === 'text') {
console.log(`Answer: ${output.text}`);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Solve this step by step: What is 15% of 240?",
"generation_config": {
"thinking_level": "high",
"thinking_summaries": "auto"
}
}'
Cada bloco de pensamento contém um campo signature (um hash criptográfico do estado de raciocínio interno) e um campo summary opcional (um resumo legível por humanos do raciocínio do modelo). O signature está sempre presente, mas um bloco de pensamento pode conter apenas uma assinatura sem resumo nestes casos:
- Solicitações simples: o modelo não raciocinou o suficiente para gerar um resumo.
thinking_summaries: "none": os resumos estão explicitamente desativados
Seu código precisa sempre processar blocos de pensamento em que o summary está vazio ou ausente. Ao gerenciar o histórico de conversas manualmente (modo sem estado), inclua blocos de pensamento com as assinaturas deles em solicitações subsequentes para validar a autenticidade.
Como trabalhar com arquivos
Como trabalhar com arquivos remotos
Acesse arquivos usando URLs remotos diretamente na chamada de API.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{
"type": "image",
"uri": "https://github.com/<github-path>/cats-and-dogs.jpg",
},
{"type": "text", "text": "Describe what you see."}
],
)
for output in interaction.outputs:
if output.type == "text":
print(output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{
type: 'image',
uri: 'https://github.com/<github-path>/cats-and-dogs.jpg',
},
{ type: 'text', text: 'Describe what you see.' }
],
});
for (const output of interaction.outputs) {
if (output.type === 'text') {
console.log(output.text);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{
"type": "image",
"uri": "https://github.com/<github-path>/cats-and-dogs.jpg"
},
{"type": "text", "text": "Describe what you see."}
]
}'
Como trabalhar com a API Gemini Files
Faça upload dos arquivos para a API Files do Gemini antes de usá-los.
Python
from google import genai
import time
import requests
client = genai.Client()
# 1. Download the file
url = "https://github.com/philschmid/gemini-samples/raw/refs/heads/main/assets/cats-and-dogs.jpg"
response = requests.get(url)
with open("cats-and-dogs.jpg", "wb") as f:
f.write(response.content)
# 2. Upload to Gemini Files API
file = client.files.upload(file="cats-and-dogs.jpg")
# 3. Wait for processing
while client.files.get(name=file.name).state != "ACTIVE":
time.sleep(2)
# 4. Use in Interaction
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{
"type": "image",
"uri": file.uri,
},
{"type": "text", "text": "Describe what you see."}
],
)
for output in interaction.outputs:
if output.type == "text":
print(output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
import fetch from 'node-fetch';
const client = new GoogleGenAI({});
// 1. Download the file
const url = 'https://github.com/philschmid/gemini-samples/raw/refs/heads/main/assets/cats-and-dogs.jpg';
const filename = 'cats-and-dogs.jpg';
const response = await fetch(url);
const buffer = await response.buffer();
fs.writeFileSync(filename, buffer);
// 2. Upload to Gemini Files API
const myfile = await client.files.upload({ file: filename, config: { mimeType: 'image/jpeg' } });
// 3. Wait for processing
while ((await client.files.get({ name: myfile.name })).state !== 'ACTIVE') {
await new Promise(resolve => setTimeout(resolve, 2000));
}
// 4. Use in Interaction
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{ type: 'image', uri: myfile.uri, },
{ type: 'text', text: 'Describe what you see.' }
],
});
for (const output of interaction.outputs) {
if (output.type === 'text') {
console.log(output.text);
}
}
REST
# 1. Upload the file (Requires File API setup)
# See https://ai.google.dev/gemini-api/docs/files for details.
# Assume FILE_URI is obtained from the upload step.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "image", "uri": "FILE_URI"},
{"type": "text", "text": "Describe what you see."}
]
}'
Modelo de dados
Saiba mais sobre o modelo de dados na Referência da API. A seguir, apresentamos uma visão geral de alto nível dos principais componentes.
Interação
| Propriedade | Tipo | Descrição |
|---|---|---|
id |
string |
Identificador exclusivo da interação. |
model / agent |
string |
O modelo ou agente usado. Só é possível fornecer um. |
input |
Content[] |
As entradas fornecidas. |
outputs |
Content[] |
As respostas do modelo. |
tools |
Tool[] |
As ferramentas usadas. |
previous_interaction_id |
string |
ID da interação anterior para contexto. |
stream |
boolean |
Se a interação está sendo transmitida por streaming. |
status |
string |
Status: completed, in_progress, requires_action, failed etc. |
background |
boolean |
Se a interação está no modo em segundo plano. |
store |
boolean |
Indica se a interação deve ser armazenada. Padrão: true. Defina como false para recusar. |
usage |
Uso | Uso de token da solicitação de interação. |
Modelos e agentes compatíveis
| Nome do modelo | Tipo | ID do modelo |
|---|---|---|
| Pré-lançamento do Gemini 3.1 Flash-Lite | Modelo | gemini-3.1-flash-lite-preview |
| Pré-lançamento do Gemini 3.1 Pro | Modelo | gemini-3.1-pro-preview |
| Pré-lançamento do Gemini 3 Flash | Modelo | gemini-3-flash-preview |
| Gemini 2.5 Pro | Modelo | gemini-2.5-pro |
| Gemini 2.5 Flash | Modelo | gemini-2.5-flash |
| Gemini 2.5 Flash-lite | Modelo | gemini-2.5-flash-lite |
| Prévia do Deep Research | Agente | deep-research-pro-preview-12-2025 |
Como a API Interactions funciona
A API Interactions foi projetada em torno de um recurso central: o
Interaction.
Um Interaction representa uma rodada completa em uma conversa ou tarefa. Ele funciona como um registro de sessão, contendo todo o histórico de uma interação, incluindo todas as entradas do usuário, reflexões do modelo, chamadas de ferramentas, resultados de ferramentas e saídas finais do modelo.
Ao fazer uma chamada para
interactions.create, você está
criando um novo recurso Interaction.
Gerenciamento de estado do lado do servidor
Você pode usar o id de uma interação concluída em uma chamada subsequente usando o parâmetro previous_interaction_id para continuar a conversa. O servidor usa esse ID para recuperar o histórico da conversa, evitando que você precise reenviar todo o histórico de chat.
Apenas o histórico de conversas (entradas e saídas) é preservado usando previous_interaction_id. Os outros parâmetros são no escopo da interação e se aplicam apenas à interação específica que você está gerando:
toolssystem_instructiongeneration_config(incluindothinking_level,temperatureetc.)
Isso significa que você precisa especificar esses parâmetros novamente em cada nova interação se quiser que eles sejam aplicados. O gerenciamento de estado do lado do servidor é opcional. Você também pode operar no modo sem estado enviando o histórico completo da conversa em cada solicitação.
Armazenamento e retenção de dados
Por padrão, todos os objetos de interação são armazenados (store=true) para simplificar o uso de recursos de gerenciamento de estado do lado do servidor (com previous_interaction_id), execução em segundo plano (usando background=true) e fins de observabilidade.
- Nível pago: as interações são retidas por 55 dias.
- Nível sem custo financeiro: as interações são retidas por 1 dia.
Se não quiser isso, defina store=false na sua solicitação. Esse controle é separado do gerenciamento de estado. Você pode desativar o armazenamento para qualquer interação. No entanto, store=false é incompatível com background=true e impede o uso de previous_interaction_id em turnos subsequentes.
É possível excluir as interações armazenadas a qualquer momento usando o método de exclusão encontrado na Referência da API. Só é possível excluir interações se você souber o ID delas.
Após o período de armazenamento expirar, seus dados serão excluídos automaticamente.
Os objetos de interações são processados de acordo com os termos.
Práticas recomendadas
- Taxa de ocorrência em cache: usar
previous_interaction_idpara continuar conversas permite que o sistema utilize mais facilmente o armazenamento em cache implícito para o histórico de conversas, o que melhora o desempenho e reduz os custos. - Interações combinadas: você tem a flexibilidade de combinar interações do agente e do modelo em uma conversa. Por exemplo, você pode usar um agente especializado, como o Deep Research, para a coleta inicial de dados e, em seguida, usar um modelo padrão do Gemini para tarefas de acompanhamento, como resumir ou reformatar, vinculando essas etapas ao
previous_interaction_id.
SDKs
Use a versão mais recente dos SDKs da IA generativa do Google para acessar a API Interactions.
- Em Python, esse é o pacote
google-genaida versão1.55.0em diante. - Em JavaScript, esse é o pacote
@google/genaida versão1.33.0em diante.
Saiba mais sobre como instalar os SDKs na página Bibliotecas.
Limitações
- Status Beta: a API Interactions está na versão Beta/prévia. Os recursos e esquemas podem mudar.
- MCP remoto: o Gemini 3 não é compatível com o MCP remoto, mas isso vai estar disponível em breve.
Alterações importantes
No momento, a API Interactions está na versão Beta inicial. Estamos desenvolvendo e refinando ativamente os recursos da API, os esquemas de recursos e as interfaces do SDK com base no uso no mundo real e no feedback dos desenvolvedores.
Como resultado, mudanças interruptivas podem ocorrer. As atualizações podem incluir mudanças em:
- Esquemas de entrada e saída.
- Assinaturas de métodos do SDK e estruturas de objetos.
- Comportamentos específicos de recursos.
Para cargas de trabalho de produção, continue usando a API padrão
generateContent. Ele continua sendo o caminho recomendado para implantações estáveis e vai continuar sendo desenvolvido e mantido ativamente.
Feedback
Seu feedback é fundamental para o desenvolvimento da API Interactions. Compartilhe suas ideias, informe bugs ou solicite recursos no fórum da comunidade de desenvolvedores de IA do Google.
A seguir
- Teste o notebook de início rápido da API Interactions.
- Saiba mais sobre o agente do Deep Research do Gemini.