Agente de Deep Research de Gemini

El agente 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.1 Pro, navega por entornos de información complejos con la Búsqueda web y tus propios datos para producir informes detallados, y 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 (establecer 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 con 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 al agente a tus propios datos con la herramienta File Search, deberás agregarlo 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 dirigir el resultado del agente proporcionando instrucciones de formato específicas en tu instrucción. Esto te permite estructurar informes en secciones y subsecciones, incluir tablas de datos o ajustar el tono para diferentes públicos (p.ej., "técnico", "ejecutivo" o "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

Entradas multimodales

Deep Research admite entradas multimodales, incluidas imágenes, archivos PDF, audio y video, lo que permite que el agente analice contenido enriquecido y, luego, realice investigaciones basadas en la Web contextualizadas por las entradas proporcionadas. Por ejemplo, puedes proporcionar una fotografía y pedirle al agente que identifique temas, investigue su comportamiento o encuentre información relacionada.

En el siguiente ejemplo, se muestra una solicitud de análisis de imágenes con una URL de imagen.

Python

import time
from google import genai

client = genai.Client()

prompt = '''Analyze the interspecies dynamics and behavioral risks present
in the provided image of the African watering hole. Specifically, investigate
the symbiotic relationship between the avian species and the pachyderms
shown, and conduct a risk assessment for the reticulated giraffes based on
their drinking posture relative to the specific predator visible in the
foreground.'''

interaction = client.interactions.create(
    input=[
        {"type": "text", "text": prompt},
        {
            "type": "image",
            "uri": "https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg"
        }
    ],
    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 prompt = `Analyze the interspecies dynamics and behavioral risks present
in the provided image of the African watering hole. Specifically, investigate
the symbiotic relationship between the avian species and the pachyderms
shown, and conduct a risk assessment for the reticulated giraffes based on
their drinking posture relative to the specific predator visible in the
foreground.`;

const interaction = await client.interactions.create({
    input: [
        { type: 'text', text: prompt },
        {
            type: 'image',
            uri: 'https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg'
        }
    ],
    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 with image input
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "input": [
        {"type": "text", "text": "Analyze the interspecies dynamics and behavioral risks present in the provided image of the African watering hole. Specifically, investigate the symbiotic relationship between the avian species and the pachyderms shown, and conduct a risk assessment for the reticulated giraffes based on their drinking posture relative to the specific predator visible in the foreground."},
        {"type": "image", "uri": "https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg"}
    ],
    "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"

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.

Los agentes deben usar background=True. La API devuelve un objeto parcial Interaction de inmediato. Puedes usar la propiedad id para recuperar una interacción para el sondeo. El estado de la 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 establecer stream=True y background=True.

En el siguiente ejemplo, se muestra cómo iniciar una tarea de investigación y procesar la transmisión. Es fundamental que se muestre cómo hacer un seguimiento del interaction_id del interaction.start evento. Necesitarás este ID para reanudar la transmisión si se produce una interrupción de la red. Este código también presenta una variable event_id que te permite reanudar 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.

Cómo volver a conectarse para transmitir

Las interrupciones de la red pueden ocurrir durante las tareas de investigación de larga duración. Para controlarlo correctamente, tu aplicación debe detectar errores de conexión y reanudar la transmisión con client.interactions.get().

Debes proporcionar dos valores para reanudar:

  1. ID de interacción: Se adquiere del evento interaction.start en la transmisión inicial.
  2. 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 comienzo de la transmisión.

En los siguientes ejemplos, se muestra un patrón resistente: se intenta transmitir la solicitud create inicial y se vuelve a un bucle 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 respuestas adicionales

Puedes continuar la conversación después de que el agente devuelva el informe final con el previous_interaction_id. Esto te permite solicitar aclaraciones, resúmenes o explicaciones sobre secciones específicas de la investigación sin 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.1-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?',
    model: 'gemini-3.1-pro-preview',
    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?",
    "model": "gemini-3.1-pro-preview",
    "previous_interaction_id": "COMPLETED_INTERACTION_ID"
}'

Cuándo usar el agente 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 baja latencia.

Función Modelos estándar de Gemini Agente Deep Research de Gemini
Latencia Segundos Minutos (asíncrono/en segundo plano)
Proceso Generar -> Resultado Planificar -> Buscar -> Leer -> Iterar -> Resultado
Resultado Texto conversacional, código, resúmenes breves Informes detallados, análisis de formato largo, tablas comparativas
Ideal para Chatbots, extracción, escritura creativa Análisis de mercado, diligencia debida, revisiones de literatura, panorama competitivo

Disponibilidad y precios

Puedes acceder al agente Deep Research de Gemini con la API de Interactions en Google AI Studio y la API de Gemini.

Los precios siguen un modelo de pago por uso basado en el modelo subyacente de Gemini 3.1 Pro y las herramientas específicas que utiliza el agente. A diferencia de las solicitudes de chat estándar, en las que una solicitud genera un resultado, una tarea de Deep Research es un flujo de trabajo de agentes. Una sola solicitud activa un bucle autónomo de planificación, búsqueda, lectura y razonamiento.

Costos estimados

Los costos varían según la profundidad de la investigación requerida. El agente determina de forma autónoma cuánta lectura y búsqueda es necesaria para responder tu instrucción.

  • Tarea de investigación estándar: Para una consulta típica que requiere un análisis moderado, el agente podría usar ~80 consultas de búsqueda, ~250,000 tokens de entrada (~50-70% almacenados en caché) y ~60,000 tokens de salida.
    • Total estimado: ~$2.00 a $3.00 por tarea
  • Tarea de investigación compleja: Para un análisis profundo del panorama competitivo o una diligencia debida exhaustiva, el agente podría usar hasta ~160 consultas de búsqueda, ~900,000 tokens de entrada (~50-70% almacenados en caché) y ~80,000 tokens de salida.
    • Total estimado: ~$3.00 a $5.00 por tarea

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 (archivos PDF y de texto) provengan de fuentes confiables. Un archivo malicioso podría contener texto oculto diseñado para manipular el resultado del agente.
  • Riesgos de 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 pueda encontrar y procesar páginas web maliciosas. Te recomendamos que revises los citations proporcionados 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

  • Instrucciones para datos desconocidos: Indica al agente cómo controlar los datos faltantes. Por ejemplo, agrega "Si no hay cifras específicas para 2025, indica explícitamente que son proyecciones o que no están disponibles en lugar de estimarlas" a tu instrucción.
  • Proporciona contexto: Fundamenta la investigación del agente proporcionando información de contexto o restricciones directamente en la instrucción de entrada.
  • Entradas multimodales El agente Deep Research admite entradas multimodales. Úsalo con precaución, ya que aumenta los costos y los riesgos 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 Function Calling ni servidores MCP (Protocolo de contexto del modelo) remotos al agente Deep Research.
  • Aprobación de planes y resultados estructurados: Actualmente, el agente Deep Research no admite la planificación aprobada por humanos ni los resultados estructurados.
  • Tiempo máximo de investigación: El agente 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 almacenamiento: La ejecución del agente con background=True requiere store=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?