El agente de Deep Research de Gemini planifica, ejecuta y sintetiza de forma autónoma tareas de investigación de varios pasos. Con la tecnología de Gemini 3 Pro, navega por entornos de información complejos con la Búsqueda web y tus propios datos para generar informes detallados con citas.
Las tareas de investigación implican búsquedas y lecturas iterativas, y pueden tardar varios minutos en completarse. Debes usar la ejecución en segundo plano (establece background=true) para ejecutar el agente de forma asíncrona y sondear los resultados. Consulta Cómo controlar tareas de larga duración para obtener más detalles.
En el siguiente ejemplo, se muestra cómo iniciar una tarea de investigación en segundo plano y sondear los resultados.
Python
import time
from google import genai
client = genai.Client()
interaction = client.interactions.create(
input="Research the history of Google TPUs.",
agent='deep-research-pro-preview-12-2025',
background=True
)
print(f"Research started: {interaction.id}")
while True:
interaction = client.interactions.get(interaction.id)
if interaction.status == "completed":
print(interaction.outputs[-1].text)
break
elif interaction.status == "failed":
print(f"Research failed: {interaction.error}")
break
time.sleep(10)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
input: 'Research the history of Google TPUs.',
agent: 'deep-research-pro-preview-12-2025',
background: true
});
console.log(`Research started: ${interaction.id}`);
while (true) {
const result = await client.interactions.get(interaction.id);
if (result.status === 'completed') {
console.log(result.outputs[result.outputs.length - 1].text);
break;
} else if (result.status === 'failed') {
console.log(`Research failed: ${result.error}`);
break;
}
await new Promise(resolve => setTimeout(resolve, 10000));
}
REST
# 1. Start the research task
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 Google TPUs.",
"agent": "deep-research-pro-preview-12-2025",
"background": true
}'
# 2. Poll for results (Replace INTERACTION_ID)
# curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID" \
# -H "x-goog-api-key: $GEMINI_API_KEY"
Investiga con tus propios datos
Deep Research tiene acceso a una variedad de herramientas. De forma predeterminada, el agente tiene acceso a la información de Internet pública a través de las herramientas google_search y url_context. No es necesario que especifiques estas herramientas de forma predeterminada. Sin embargo, si también quieres darle acceso a tus propios datos usando la herramienta Búsqueda de archivos, deberás agregarla como se muestra en el siguiente ejemplo.
Python
import time
from google import genai
client = genai.Client()
interaction = client.interactions.create(
input="Compare our 2025 fiscal year report against current public web news.",
agent="deep-research-pro-preview-12-2025",
background=True,
tools=[
{
"type": "file_search",
"file_search_store_names": ['fileSearchStores/my-store-name']
}
]
)
JavaScript
const interaction = await client.interactions.create({
input: 'Compare our 2025 fiscal year report against current public web news.',
agent: 'deep-research-pro-preview-12-2025',
background: true,
tools: [
{ type: 'file_search', file_search_store_names: ['fileSearchStores/my-store-name'] },
]
});
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"input": "Compare our 2025 fiscal year report against current public web news.",
"agent": "deep-research-pro-preview-12-2025",
"background": true,
"tools": [
{"type": "file_search", "file_search_store_names": ["fileSearchStores/my-store-name"]},
]
}'
Capacidad de dirección y formato
Puedes guiar la respuesta del agente proporcionando instrucciones de formato específicas en tu instrucción. Esto te permite estructurar los informes en secciones y subsecciones específicas, incluir tablas de datos o ajustar el tono para diferentes públicos (p.ej., "técnico", "ejecutivo", "informal").
Define el formato de salida deseado de forma explícita en el texto de entrada.
Python
prompt = """
Research the competitive landscape of EV batteries.
Format the output as a technical report with the following structure:
1. Executive Summary
2. Key Players (Must include a data table comparing capacity and chemistry)
3. Supply Chain Risks
"""
interaction = client.interactions.create(
input=prompt,
agent="deep-research-pro-preview-12-2025",
background=True
)
JavaScript
const prompt = `
Research the competitive landscape of EV batteries.
Format the output as a technical report with the following structure:
1. Executive Summary
2. Key Players (Must include a data table comparing capacity and chemistry)
3. Supply Chain Risks
`;
const interaction = await client.interactions.create({
input: prompt,
agent: 'deep-research-pro-preview-12-2025',
background: true,
});
REST
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 competitive landscape of EV batteries.\n\nFormat the output as a technical report with the following structure: \n1. Executive Summary\n2. Key Players (Must include a data table comparing capacity and chemistry)\n3. Supply Chain Risks",
"agent": "deep-research-pro-preview-12-2025",
"background": true
}'
Cómo controlar tareas de larga duración
Deep Research es un proceso de varios pasos que incluye planificación, búsqueda, lectura y escritura. Por lo general, este ciclo supera los límites de tiempo de espera estándar de las llamadas a la API síncronas.
Se requieren agentes para usar background=True. La API devuelve un objeto Interaction parcial de inmediato. Puedes usar la propiedad id para recuperar una interacción para la votación. El estado de interacción pasará de in_progress a completed o failed.
Transmisión
Deep Research admite la transmisión para recibir actualizaciones en tiempo real sobre el progreso de la investigación. Debes configurar stream=True y background=True.
En el siguiente ejemplo, se muestra cómo iniciar una tarea de investigación y procesar la transmisión.
Fundamentalmente, muestra cómo hacer un seguimiento del interaction_id a partir del evento interaction.start. Necesitarás este ID para reanudar la transmisión si se produce una interrupción de la red. Este código también introduce una variable event_id que te permite reanudar la sesión desde el punto específico en el que te desconectaste.
Python
stream = client.interactions.create(
input="Research the history of Google TPUs.",
agent="deep-research-pro-preview-12-2025",
background=True,
stream=True,
agent_config={
"type": "deep-research",
"thinking_summaries": "auto"
}
)
interaction_id = None
last_event_id = None
for chunk in stream:
if chunk.event_type == "interaction.start":
interaction_id = chunk.interaction.id
print(f"Interaction started: {interaction_id}")
if chunk.event_id:
last_event_id = chunk.event_id
if chunk.event_type == "content.delta":
if chunk.delta.type == "text":
print(chunk.delta.text, end="", flush=True)
elif chunk.delta.type == "thought_summary":
print(f"Thought: {chunk.delta.content.text}", flush=True)
elif chunk.event_type == "interaction.complete":
print("\nResearch Complete")
JavaScript
const stream = await client.interactions.create({
input: 'Research the history of Google TPUs.',
agent: 'deep-research-pro-preview-12-2025',
background: true,
stream: true,
agent_config: {
type: 'deep-research',
thinking_summaries: 'auto'
}
});
let interactionId;
let lastEventId;
for await (const chunk of stream) {
// 1. Capture Interaction ID
if (chunk.event_type === 'interaction.start') {
interactionId = chunk.interaction.id;
console.log(`Interaction started: ${interactionId}`);
}
// 2. Track IDs for potential reconnection
if (chunk.event_id) lastEventId = chunk.event_id;
// 3. Handle Content
if (chunk.event_type === 'content.delta') {
if (chunk.delta.type === 'text') {
process.stdout.write(chunk.delta.text);
} else if (chunk.delta.type === 'thought_summary') {
console.log(`Thought: ${chunk.delta.content.text}`);
}
} else if (chunk.event_type === 'interaction.complete') {
console.log('\nResearch Complete');
}
}
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 '{
"input": "Research the history of Google TPUs.",
"agent": "deep-research-pro-preview-12-2025",
"background": true,
"stream": true,
"agent_config": {
"type": "deep-research",
"thinking_summaries": "auto"
}
}'
# Note: Look for the 'interaction.start' event to get the interaction ID.
Restableciendo la conexión con la transmisión
Las interrupciones de red pueden ocurrir durante las tareas de investigación de larga duración. Para controlar esto con facilidad, tu aplicación debe detectar los errores de conexión y reanudar la transmisión con client.interactions.get().
Debes proporcionar dos valores para reanudar la operación:
- ID de interacción: Se adquiere del evento
interaction.starten el flujo inicial. - ID del último evento: Es el ID del último evento procesado correctamente. Esto le indica al servidor que reanude el envío de eventos después de ese punto específico. Si no se proporciona, obtendrás el inicio de la transmisión.
En los siguientes ejemplos, se muestra un patrón resiliente: se intenta transmitir la solicitud inicial de create y se recurre a un bucle de get si se interrumpe la conexión.
Python
import time
from google import genai
client = genai.Client()
# Configuration
agent_name = 'deep-research-pro-preview-12-2025'
prompt = 'Compare golang SDK test frameworks'
# State tracking
last_event_id = None
interaction_id = None
is_complete = False
def process_stream(event_stream):
"""Helper to process events from any stream source."""
global last_event_id, interaction_id, is_complete
for event in event_stream:
# Capture Interaction ID
if event.event_type == "interaction.start":
interaction_id = event.interaction.id
print(f"Interaction started: {interaction_id}")
# Capture Event ID
if event.event_id:
last_event_id = event.event_id
# Print content
if event.event_type == "content.delta":
if event.delta.type == "text":
print(event.delta.text, end="", flush=True)
elif event.delta.type == "thought_summary":
print(f"Thought: {event.delta.content.text}", flush=True)
# Check completion
if event.event_type in ['interaction.complete', 'error']:
is_complete = True
# 1. Attempt initial streaming request
try:
print("Starting Research...")
initial_stream = client.interactions.create(
input=prompt,
agent=agent_name,
background=True,
stream=True,
agent_config={
"type": "deep-research",
"thinking_summaries": "auto"
}
)
process_stream(initial_stream)
except Exception as e:
print(f"\nInitial connection dropped: {e}")
# 2. Reconnection Loop
# If the code reaches here and is_complete is False, we resume using .get()
while not is_complete and interaction_id:
print(f"\nConnection lost. Resuming from event {last_event_id}...")
time.sleep(2)
try:
resume_stream = client.interactions.get(
id=interaction_id,
stream=True,
last_event_id=last_event_id
)
process_stream(resume_stream)
except Exception as e:
print(f"Reconnection failed, retrying... ({e})")
JavaScript
let lastEventId;
let interactionId;
let isComplete = false;
// Helper to handle the event logic
const handleStream = async (stream) => {
for await (const chunk of stream) {
if (chunk.event_type === 'interaction.start') {
interactionId = chunk.interaction.id;
}
if (chunk.event_id) lastEventId = chunk.event_id;
if (chunk.event_type === 'content.delta') {
if (chunk.delta.type === 'text') {
process.stdout.write(chunk.delta.text);
} else if (chunk.delta.type === 'thought_summary') {
console.log(`Thought: ${chunk.delta.content.text}`);
}
} else if (chunk.event_type === 'interaction.complete') {
isComplete = true;
}
}
};
// 1. Start the task with streaming
try {
const stream = await client.interactions.create({
input: 'Compare golang SDK test frameworks',
agent: 'deep-research-pro-preview-12-2025',
background: true,
stream: true,
agent_config: {
type: 'deep-research',
thinking_summaries: 'auto'
}
});
await handleStream(stream);
} catch (e) {
console.log('\nInitial stream interrupted.');
}
// 2. Reconnect Loop
while (!isComplete && interactionId) {
console.log(`\nReconnecting to interaction ${interactionId} from event ${lastEventId}...`);
try {
const stream = await client.interactions.get(interactionId, {
stream: true,
last_event_id: lastEventId
});
await handleStream(stream);
} catch (e) {
console.log('Reconnection failed, retrying in 2s...');
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
REST
# 1. Start the research task (Initial Stream)
# Watch for event: interaction.start to get the INTERACTION_ID
# Watch for "event_id" fields to get the LAST_EVENT_ID
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 '{
"input": "Compare golang SDK test frameworks",
"agent": "deep-research-pro-preview-12-2025",
"background": true,
"stream": true,
"agent_config": {
"type": "deep-research",
"thinking_summaries": "auto"
}
}'
# ... Connection interrupted ...
# 2. Reconnect (Resume Stream)
# Pass the INTERACTION_ID and the LAST_EVENT_ID you saved.
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID?stream=true&last_event_id=LAST_EVENT_ID&alt=sse" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Preguntas y conversaciones de seguimiento
Puedes continuar la conversación después de que el agente devuelva el informe final con previous_interaction_id. Esto te permite pedir aclaraciones, resúmenes o explicaciones sobre secciones específicas de la investigación sin tener que reiniciar toda la tarea.
Python
import time
from google import genai
client = genai.Client()
interaction = client.interactions.create(
input="Can you elaborate on the second point in the report?",
model="gemini-3-pro-preview",
previous_interaction_id="COMPLETED_INTERACTION_ID"
)
print(interaction.outputs[-1].text)
JavaScript
const interaction = await client.interactions.create({
input: 'Can you elaborate on the second point in the report?',
agent: 'deep-research-pro-preview-12-2025',
previous_interaction_id: 'COMPLETED_INTERACTION_ID'
});
console.log(interaction.outputs[-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 '{
"input": "Can you elaborate on the second point in the report?",
"agent": "deep-research-pro-preview-12-2025",
"previous_interaction_id": "COMPLETED_INTERACTION_ID"
}'
Cuándo usar el agente de Deep Research de Gemini
Deep Research es un agente, no solo un modelo. Es más adecuado para cargas de trabajo que requieren un enfoque de "analista en una caja" en lugar de un chat de latencia baja.
| Función | Modelos de Gemini estándar | Agente de Deep Research de Gemini |
|---|---|---|
| Latencia | Segundos | Minutos (en segundo plano o asíncrono) |
| Proceso | Generar -> Resultado | Planificar -> Buscar -> Leer -> Iterar -> Generar |
| Resultado | Texto conversacional, código y resúmenes breves | Informes detallados, análisis de formato largo y tablas comparativas |
| Ideal para | Chatbots, extracción y escritura creativa | Análisis de mercado, diligencia debida, revisiones bibliográficas y análisis de la competencia |
Disponibilidad y precios
- Disponibilidad: Se puede acceder a través de la API de Interactions en Google AI Studio y la API de Gemini.
- Precios: Consulta la página de precios para conocer las tarifas y los detalles específicos.
Consideraciones de seguridad
Darle acceso a un agente a la Web y a tus archivos privados requiere una consideración cuidadosa de los riesgos de seguridad.
- Inyección de instrucciones con archivos: El agente lee el contenido de los archivos que proporcionas. Asegúrate de que los documentos subidos (PDFs, archivos de texto) provengan de fuentes confiables. Un archivo malicioso podría contener texto oculto diseñado para manipular la respuesta del agente.
- Riesgos del contenido web: El agente busca en la Web pública. Si bien implementamos filtros de seguridad sólidos, existe el riesgo de que el agente encuentre y procese páginas web maliciosas. Te recomendamos que revises el
citationsque se proporciona en la respuesta para verificar las fuentes. - Exfiltración: Ten cuidado cuando le pidas al agente que resuma datos internos sensibles si también le permites navegar por la Web.
Prácticas recomendadas
- Pregunta sobre lo desconocido: Indica al agente cómo controlar los datos faltantes. Por ejemplo, agrega "Si no hay cifras específicas disponibles para el 2025, indica explícitamente que son proyecciones o que no están disponibles en lugar de hacer una estimación" a tu instrucción.
- Proporciona contexto: Fundamenta la investigación del agente proporcionando información de antecedentes o restricciones directamente en la instrucción de entrada.
- Entradas multimodales: El agente de Deep Research admite entradas multimodales. Úsala con precaución, ya que aumenta los costos y el riesgo de desbordamiento de la ventana de contexto.
Limitaciones
- Estado beta: La API de Interactions está en versión beta pública. Las funciones y los esquemas pueden cambiar.
- Herramientas personalizadas: Actualmente, no puedes proporcionar herramientas personalizadas de Llamadas a funciones ni servidores remotos de MCP (Protocolo de contexto del modelo) al agente de Investigación profunda.
- Aprobación de planes y resultados estructurados: Actualmente, el agente de investigación profunda no admite la planificación aprobada por humanos ni los resultados estructurados.
- Tiempo máximo de investigación: El agente de Deep Research tiene un tiempo máximo de investigación de 60 minutos. La mayoría de las tareas deberían completarse en un plazo de 20 minutos.
- Requisito de la tienda: La ejecución del agente con
background=Truerequierestore=True. - Búsqueda de Google: La Búsqueda de Google está habilitada de forma predeterminada y se aplican restricciones específicas a los resultados fundamentados.
- Entradas de audio: No se admiten entradas de audio.
¿Qué sigue?
- Obtén más información sobre la API de Interactions.
- Lee sobre el modelo Gemini 3 Pro que potencia este agente.
- Obtén información para usar tus propios datos con la herramienta Búsqueda de archivos.