Agente Deep Research di Gemini

L'agente Gemini Deep Research pianifica, esegue e sintetizza in modo autonomo attività di ricerca in più fasi. Basato su Gemini 3 Pro, esplora paesaggi informativi complessi utilizzando la ricerca web e i tuoi dati per produrre report dettagliati e citati.

Le attività di ricerca comportano la ricerca e la lettura iterative e possono richiedere diversi minuti per essere completate. Devi utilizzare l'esecuzione in background (imposta background=true) per eseguire l'agente in modo asincrono e cercare i risultati. Per maggiori dettagli, consulta Gestire le attività a lunga esecuzione.

L'esempio seguente mostra come avviare un'attività di ricerca in background e eseguire il polling dei risultati.

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"

Cerca con i tuoi dati

Deep Research ha accesso a una serie di strumenti. Per impostazione predefinita, l'agente ha accesso alle informazioni su internet pubblico utilizzando gli strumenti google_search e url_context. Non è necessario specificare questi strumenti per impostazione predefinita. Tuttavia, se vuoi anche concedere all'agente l'accesso ai tuoi dati utilizzando lo strumento Ricerca file, dovrai aggiungerlo come mostrato nell'esempio seguente.

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"]},
    ]
}'

Sterzabilità e formattazione

Puoi controllare l'output dell'agente fornendo istruzioni di formattazione specifiche nel prompt. In questo modo puoi strutturare i report in sezioni e sottosezioni specifiche, includere tabelle di dati o regolare il tono per diversi segmenti di pubblico (ad es. "technical", "executive", "casual").

Definisci esplicitamente il formato di output desiderato nel testo di input.

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

Input multimodali

Deep Research supporta input multimodali, tra cui immagini, PDF, audio e video, consentendo all'agente di analizzare contenuti avanzati e quindi condurre ricerche basate sul web contestualizzate in base agli input forniti. Ad esempio, puoi fornire una fotografia e chiedere all'agente di identificare i soggetti, studiarne il comportamento o trovare informazioni correlate.

Il seguente esempio mostra una richiesta di analisi delle immagini che utilizza un URL immagine.

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"

Gestione di attività di lunga durata

Deep Research è un processo in più fasi che include pianificazione, ricerca, lettura e scrittura. Questo ciclo in genere supera i limiti di timeout standard delle chiamate API sincrone.

Gli agenti sono tenuti a utilizzare background=True. L'API restituisce immediatamente un oggetto Interaction parziale. Puoi utilizzare la proprietà id per recuperare un'interazione per il polling. Lo stato dell'interazione passerà da in_progress a completed o failed.

Streaming

Deep Research supporta lo streaming per ricevere aggiornamenti in tempo reale sull'avanzamento della ricerca. Devi impostare stream=True e background=True.

L'esempio seguente mostra come avviare un'attività di ricerca ed elaborare lo stream. aspetto fondamentale, mostra come monitorare interaction_id dall'evento interaction.start. Avrai bisogno di questo ID per riprendere lo stream in caso di interruzione della rete. Questo codice introduce anche una variabile event_id che ti consente di riprendere dal punto specifico in cui si è interrotta la connessione.

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.

Riconnessione allo stream

Durante le attività di ricerca a lunga esecuzione possono verificarsi interruzioni di rete. Per gestire questo problema in modo appropriato, la tua applicazione deve rilevare gli errori di connessione e riprendere lo stream utilizzando client.interactions.get().

Devi fornire due valori per riprendere:

  1. ID interazione:acquisito dall'evento interaction.start nello stream iniziale.
  2. ID ultimo evento:l'ID dell'ultimo evento elaborato correttamente. In questo modo, il server riprende a inviare eventi dopo quel punto specifico. Se non viene fornito, riceverai l'inizio dello stream.

Gli esempi seguenti mostrano un pattern resiliente: il tentativo di trasmettere in streaming la richiesta create iniziale e il fallback a un ciclo get se la connessione si interrompe.

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"

Domande aggiuntive e interazioni

Puoi continuare la conversazione dopo che l'agente ha restituito il report finale utilizzando previous_interaction_id. In questo modo, puoi chiedere chiarimenti, riepiloghi o approfondimenti su sezioni specifiche della ricerca senza riavviare l'intera attività.

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"
}'

Quando utilizzare Gemini Deep Research Agent

Deep Research è un agente, non solo un modello. È più adatta ai workload che richiedono un approccio "analista in una scatola" anziché una chat a bassa latenza.

Funzionalità Modelli Gemini standard Agente Deep Research di Gemini
Latenza Secondi Minuti (asincrono/in background)
Procedura Genera -> Output Pianificazione -> Ricerca -> Lettura -> Iterazione -> Output
Output Testo conversazionale, codice, riepiloghi brevi Report dettagliati, analisi in formato lungo, tabelle comparative
Ideale per Chatbot, estrazione, scrittura creativa Analisi di mercato, due diligence, revisioni della letteratura, panorama competitivo

Disponibilità e prezzi

Puoi accedere all'agente di ricerca approfondita Gemini utilizzando l'API Interactions in Google AI Studio e l'API Gemini.

I prezzi seguono un modello di pagamento a consumo basato sul modello Gemini 3 Pro sottostante e sugli strumenti specifici utilizzati dall'agente. A differenza delle richieste di chat standard, in cui una richiesta porta a un output, un'attività di Deep Research è un flusso di lavoro agentico. Una singola richiesta attiva un ciclo autonomo di pianificazione, ricerca, lettura e ragionamento.

Costi stimati

I costi variano in base alla profondità della ricerca richiesta. L'agente determina autonomamente la quantità di lettura e ricerca necessaria per rispondere al prompt.

  • Attività di ricerca standard:per una query tipica che richiede un'analisi moderata, l'agente potrebbe utilizzare circa 80 query di ricerca, circa 250.000 token di input (circa il 50-70% memorizzati nella cache) e circa 60.000 token di output.
    • Totale stimato: 2-3 $ per attività
  • Attività di ricerca complessa:per un'analisi approfondita del panorama competitivo o una due diligence estesa, l'agente potrebbe utilizzare fino a circa 160 query di ricerca, circa 900.000 token di input (circa il 50-70% memorizzati nella cache) e circa 80.000 token di output.
    • Totale stimato: 3-5 € per attività

Considerazioni sulla sicurezza

Concedere a un agente l'accesso al web e ai tuoi file privati richiede un'attenta valutazione dei rischi per la sicurezza.

  • Prompt injection tramite file:l'agente legge i contenuti dei file che fornisci. Assicurati che i documenti caricati (PDF, file di testo) provengano da fonti attendibili. Un file dannoso potrebbe contenere testo nascosto progettato per manipolare l'output dell'agente.
  • Rischi dei contenuti web:l'agente esegue ricerche sul web pubblico. Sebbene implementiamo filtri di sicurezza robusti, esiste il rischio che l'agente possa incontrare ed elaborare pagine web dannose. Ti consigliamo di esaminare le citations fornite nella risposta per verificare le fonti.
  • Esfiltrazione:fai attenzione quando chiedi all'agente di riassumere dati interni sensibili se gli consenti anche di navigare sul web.

Best practice

  • Richiesta per sconosciuti:indica all'agente come gestire i dati mancanti. Ad esempio, aggiungi "Se non sono disponibili cifre specifiche per il 2025, indica esplicitamente che si tratta di proiezioni o che non sono disponibili anziché stimarle" al prompt.
  • Fornisci il contesto:basa la ricerca dell'agente fornendo informazioni di base o vincoli direttamente nel prompt di input.
  • Input multimodali: Deep Research Agent supporta input multimodali. Utilizza con cautela, in quanto aumenta i costi e il rischio di overflow della finestra contestuale.

Limitazioni

  • Stato beta: l'API Interactions è in versione beta pubblica. Funzionalità e schemi possono cambiare.
  • Strumenti personalizzati: al momento non puoi fornire strumenti di chiamata di funzioni personalizzati o server MCP (Model Context Protocol) remoti all'agente Deep Research.
  • Output strutturato e approvazione del piano:l'agente Deep Research attualmente non supporta la pianificazione approvata da persone o gli output strutturati.
  • Tempo massimo di ricerca:l'agente Deep Research ha un tempo massimo di ricerca di 60 minuti. La maggior parte delle attività dovrebbe essere completata entro 20 minuti.
  • Requisito dello store:l'esecuzione dell'agente utilizzando background=True richiede store=True.
  • Ricerca Google:la Ricerca Google è attivata per impostazione predefinita e ai risultati fondati si applicano limitazioni specifiche.
  • Input audio:gli input audio non sono supportati.

Passaggi successivi