SPB Git

Repository Public

deep-research.md 41.2 KB 1,156 lines markdown

1The Gemini Deep Research Agent autonomously plans, executes, and synthesizes2multi-step research tasks. Powered by Gemini, it navigates complex3information landscapes to produce detailed, cited reports. New4capabilities allow you to collaboratively plan with the agent, connect to5external tools using MCP servers, include6visualizations (like charts and graphs), and provide documents directly7as input.89Research tasks involve iterative searching and reading and can take several10minutes to complete. You must use background execution (set `background=true`)11to run the agent asynchronously and poll for results or stream updates. See12[Handling long running tasks](https://ai.google.dev/gemini-api/docs/interactions/deep-research#long-running-tasks) for more details.1314> [!WARNING]15> **Preview:** The Gemini Deep Research Agent is currently in preview. The Deep Research agent is exclusively available using the [Interactions16> API](https://ai.google.dev/gemini-api/docs/interactions). You cannot access it through `generate_content`.1718The following example shows how to start a research task in the background19and poll for results.2021### Python2223    import time24    from google import genai2526    client = genai.Client()2728    interaction = client.interactions.create(29        input="Research the history of Google TPUs.",30        agent="deep-research-preview-04-2026",31        background=True,32    )3334    print(f"Research started: {interaction.id}")3536    while True:37        interaction = client.interactions.get(interaction.id)38        if interaction.status == "completed":39            print(interaction.output_text)40            break41        elif interaction.status == "failed":42            print(f"Research failed: {interaction.error}")43            break44        time.sleep(10)4546### JavaScript4748    import { GoogleGenAI } from '@google/genai';4950    const client = new GoogleGenAI({});5152    const interaction = await client.interactions.create({53        input: 'Research the history of Google TPUs.',54        agent: 'deep-research-preview-04-2026',55        background: true56    });5758    console.log(`Research started: ${interaction.id}`);5960    while (true) {61        const result = await client.interactions.get(interaction.id);62        if (result.status === 'completed') {63            console.log(result.output_text);64            break;65        } else if (result.status === 'failed') {66            console.log(`Research failed: ${result.error}`);67            break;68        }69        await new Promise(resolve => setTimeout(resolve, 10000));70    }7172### REST7374    # 1. Start the research task75    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \76    -H "Content-Type: application/json" \77    -H "x-goog-api-key: $GEMINI_API_KEY" \78    -H "Api-Revision: 2026-05-20" \79    -d '{80        "input": "Research the history of Google TPUs.",81        "agent": "deep-research-preview-04-2026",82        "background": true83    }'8485    # 2. Poll for results (Replace INTERACTION_ID)86    # curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID" \87    # -H "x-goog-api-key: $GEMINI_API_KEY"8889## Supported Versions9091The Deep Research agent comes in two versions:9293- **Deep Research** (`deep-research-preview-04-2026`): Designed for speed and efficiency, ideal to be streamed back to a client UI.94- **Deep Research Max** (`deep-research-max-preview-04-2026`): Maximum comprehensiveness for automated context gathering and synthesis.9596## Collaborative planning9798> [!WARNING]99> **Preview:** Collaborative planning allows you to review and refine the research plan before execution.100101Collaborative planning gives you control over the research direction102before the agent starts its work. When enabled, the agent returns a103proposed research plan instead of executing immediately. You can then104review, modify, or approve the plan through multi-turn interactions.105106### Step 1: Request a plan107108Set `collaborative_planning=True` in the first interaction. The agent109returns a research plan instead of a full report.110111### Python112113    from google import genai114115    client = genai.Client()116117    plan_interaction = client.interactions.create(118        agent="deep-research-preview-04-2026",119        input="Do some research on Google TPUs.",120        agent_config={121            "type": "deep-research",122            "thinking_summaries": "auto",123            "collaborative_planning": True,124        },125        background=True,126    )127128    while (result := client.interactions.get(id=plan_interaction.id)).status != "completed":129        time.sleep(5)130    print(result.output_text)131132### JavaScript133134    const planInteraction = await client.interactions.create({135        agent: 'deep-research-preview-04-2026',136        input: 'Do some research on Google TPUs.',137        agent_config: {138            type: 'deep-research',139            thinking_summaries: 'auto',140            collaborative_planning: true141        },142        background: true143    });144145    let result;146    while ((result = await client.interactions.get(planInteraction.id)).status !== 'completed') {147        await new Promise(r => setTimeout(r, 5000));148    }149    console.log(result.output_text);150151### REST152153    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \154    -H "Content-Type: application/json" \155    -H "x-goog-api-key: $GEMINI_API_KEY" \156    -H "Api-Revision: 2026-05-20" \157    -d '{158        "agent": "deep-research-preview-04-2026",159        "input": "Do some research on Google TPUs.",160        "agent_config": {161            "type": "deep-research",162            "thinking_summaries": "auto",163            "collaborative_planning": true164        },165        "background": true166    }'167168### Step 2: Refine the plan (optional)169170Use `previous_interaction_id` to continue the conversation and iterate171on the plan. Keep `collaborative_planning=True` to stay in planning172mode.173174### Python175176    refined_plan = client.interactions.create(177        agent="deep-research-preview-04-2026",178        input="Focus more on the differences between Google TPUs and competitor hardware, and less on the history.",179        agent_config={180            "type": "deep-research",181            "thinking_summaries": "auto",182            "collaborative_planning": True,183        },184        previous_interaction_id=plan_interaction.id,185        background=True,186    )187188    while (result := client.interactions.get(id=refined_plan.id)).status != "completed":189        time.sleep(5)190    print(result.output_text)191192### JavaScript193194    const refinedPlan = await client.interactions.create({195        agent: 'deep-research-preview-04-2026',196        input: 'Focus more on the differences between Google TPUs and competitor hardware, and less on the history.',197        agent_config: {198            type: 'deep-research',199            thinking_summaries: 'auto',200            collaborative_planning: true201        },202        previous_interaction_id: planInteraction.id,203        background: true204    });205206    let result;207    while ((result = await client.interactions.get(refinedPlan.id)).status !== 'completed') {208        await new Promise(r => setTimeout(r, 5000));209    }210    console.log(result.output_text);211212### REST213214    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \215    -H "Content-Type: application/json" \216    -H "x-goog-api-key: $GEMINI_API_KEY" \217    -H "Api-Revision: 2026-05-20" \218    -d '{219        "agent": "deep-research-preview-04-2026",220        "input": "Focus more on the differences between Google TPUs and competitor hardware, and less on the history.",221        "agent_config": {222            "type": "deep-research",223            "thinking_summaries": "auto",224            "collaborative_planning": true225        },226        "previous_interaction_id": "PREVIOUS_INTERACTION_ID",227        "background": true228    }'229230### Step 3: Approve and execute231232Set `collaborative_planning=False` (or omit it) to approve the plan and233start the research.234235### Python236237    final_report = client.interactions.create(238        agent="deep-research-preview-04-2026",239        input="Plan looks good!",240        agent_config={241            "type": "deep-research",242            "thinking_summaries": "auto",243            "collaborative_planning": False,244        },245        previous_interaction_id=refined_plan.id,246        background=True,247    )248249    while (result := client.interactions.get(id=final_report.id)).status != "completed":250        time.sleep(5)251    print(result.output_text)252253### JavaScript254255    const finalReport = await client.interactions.create({256        agent: 'deep-research-preview-04-2026',257        input: 'Plan looks good!',258        agent_config: {259            type: 'deep-research',260            thinking_summaries: 'auto',261            collaborative_planning: false262        },263        previous_interaction_id: refinedPlan.id,264        background: true265    });266267    let result;268    while ((result = await client.interactions.get(finalReport.id)).status !== 'completed') {269        await new Promise(r => setTimeout(r, 5000));270    }271    console.log(result.output_text);272273### REST274275    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \276    -H "Content-Type: application/json" \277    -H "x-goog-api-key: $GEMINI_API_KEY" \278    -H "Api-Revision: 2026-05-20" \279    -d '{280        "agent": "deep-research-preview-04-2026",281        "input": "Plan looks good!",282        "agent_config": {283            "type": "deep-research",284            "thinking_summaries": "auto",285            "collaborative_planning": false286        },287        "previous_interaction_id": "PREVIOUS_INTERACTION_ID",288        "background": true289    }'290291## Visualization292293> [!WARNING]294> **Preview:** Visualization allows the agent to generate charts and graphs to support its findings.295296When `visualization` is set to `"auto"`, the agent can generate charts,297graphs, and other visual elements to support its research findings.298Generated images are included in the response steps and streamed as299`image` deltas. For best results, explicitly ask for visuals in your300query --- for example, "Include charts showing trends over time" or301"Generate graphics comparing market share." Setting `visualization` to302`"auto"` enables the capability, but the agent generates visuals only303when the prompt requests them.304305### Python306307    import base64308309    interaction = client.interactions.create(310        agent="deep-research-preview-04-2026",311        input="Analyze global semiconductor market trends. Include graphics showing market share changes.",312        agent_config={313            "type": "deep-research",314            "visualization": "auto",315        },316        background=True,317    )318319    print(f"Research started: {interaction.id}")320321    while (result := client.interactions.get(id=interaction.id)).status != "completed":322        time.sleep(5)323324    for step in result.steps:325        if step.type == "model_output":326            for content_item in step.content:327                if content_item.type == "text":328                    print(content_item.text)329                elif content_item.type == "image" and content_item.data:330                    image_bytes = base64.b64decode(content_item.data)331                    print(f"Received image: {len(image_bytes)} bytes")332333### JavaScript334335    import { GoogleGenAI } from '@google/genai';336337    const client = new GoogleGenAI({});338339    const interaction = await client.interactions.create({340        agent: 'deep-research-preview-04-2026',341        input: 'Analyze global semiconductor market trends. Include graphics showing market share changes.',342        agent_config: {343            type: 'deep-research',344            visualization: 'auto'345        },346        background: true347    });348349    console.log(`Research started: ${interaction.id}`);350351    let result;352    while ((result = await client.interactions.get(interaction.id)).status !== 'completed') {353        await new Promise(r => setTimeout(r, 5000));354    }355356    for (const step of result.steps) {357        if (step.type === 'model_output') {358            for (const contentItem of step.content) {359                if (contentItem.type === 'text') {360                    console.log(contentItem.text);361                } else if (contentItem.type === 'image' && contentItem.data) {362                    console.log(`[Image Output: ${contentItem.data.substring(0, 20)}...]`);363                }364            }365        }366    }367368### REST369370    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \371    -H "Content-Type: application/json" \372    -H "x-goog-api-key: $GEMINI_API_KEY" \373    -H "Api-Revision: 2026-05-20" \374    -d '{375        "agent": "deep-research-preview-04-2026",376        "input": "Analyze global semiconductor market trends. Include graphics showing market share changes.",377        "agent_config": {378            "type": "deep-research",379            "visualization": "auto"380        },381        "background": true382    }'383384## Supported tools385386Deep Research supports multiple built-in and external tools. By default387(when no `tools` parameter is provided), the agent has access to Google388Search, URL Context, and Code Execution. You can explicitly389specify tools to restrict or extend the agent's capabilities.390391| Tool | Type value | Description |392|---|---|---|393| Google Search | `google_search` | Search the public web. Enabled by default. |394| URL Context | `url_context` | Read and summarize web page content. Enabled by default. |395| Code Execution | `code_execution` | Execute code to perform calculations and data analysis. Enabled by default. |396| MCP Server | `mcp_server` | Connect to remote MCP servers for external tool access. |397| File Search | `file_search` | Search your uploaded document corpora. |398399### Google Search400401Explicitly enable Google Search as the only tool:402403### Python404405    interaction = client.interactions.create(406        agent="deep-research-preview-04-2026",407        input="What are the latest developments in quantum computing?",408        tools=[{"type": "google_search"}],409        background=True,410    )411412### JavaScript413414    const interaction = await client.interactions.create({415        agent: 'deep-research-preview-04-2026',416        input: 'What are the latest developments in quantum computing?',417        tools: [{ type: 'google_search' }],418        background: true419    });420421### REST422423    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \424    -H "Content-Type: application/json" \425    -H "x-goog-api-key: $GEMINI_API_KEY" \426    -H "Api-Revision: 2026-05-20" \427    -d '{428        "agent": "deep-research-preview-04-2026",429        "input": "What are the latest developments in quantum computing?",430        "tools": [{"type": "google_search"}],431        "background": true432    }'433434### URL Context435436Give the agent the ability to read and summarize specific web pages:437438### Python439440    interaction = client.interactions.create(441        agent="deep-research-preview-04-2026",442        input="Summarize the content of https://www.wikipedia.org/.",443        tools=[{"type": "url_context"}],444        background=True,445    )446447### JavaScript448449    const interaction = await client.interactions.create({450        agent: 'deep-research-preview-04-2026',451        input: 'Summarize the content of https://www.wikipedia.org/.',452        tools: [{ type: 'url_context' }],453        background: true454    });455456### REST457458    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \459    -H "Content-Type: application/json" \460    -H "x-goog-api-key: $GEMINI_API_KEY" \461    -H "Api-Revision: 2026-05-20" \462    -d '{463        "agent": "deep-research-preview-04-2026",464        "input": "Summarize the content of https://www.wikipedia.org/.",465        "tools": [{"type": "url_context"}],466        "background": true467    }'468469### Code Execution470471Allow the agent to execute code for calculations and data analysis:472473### Python474475    interaction = client.interactions.create(476        agent="deep-research-preview-04-2026",477        input="Calculate the 50th Fibonacci number.",478        tools=[{"type": "code_execution"}],479        background=True,480    )481482### JavaScript483484    const interaction = await client.interactions.create({485        agent: 'deep-research-preview-04-2026',486        input: 'Calculate the 50th Fibonacci number.',487        tools: [{ type: 'code_execution' }],488        background: true489    });490491### REST492493    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \494    -H "Content-Type: application/json" \495    -H "x-goog-api-key: $GEMINI_API_KEY" \496    -H "Api-Revision: 2026-05-20" \497    -d '{498        "input": "Calculate the 50th Fibonacci number.",499        "agent": "deep-research-preview-04-2026",500        "tools": [{"type": "code_execution"}],501        "background": true502    }'503504### MCP servers505506> [!WARNING]507> **Preview:** Connect to remote MCP servers to give the agent access to external tools and services.508509Provide the server `name` and `url` in the tools configuration. You can also pass authentication credentials and restrict which tools the agent can call.510511| Field | Type | Required | Description |512|---|---|---|---|513| `type` | `string` | Yes | Must be `"mcp_server"`. |514| `name` | `string` | No | A display name for the MCP server. |515| `url` | `string` | No | The full URL for the MCP server endpoint. |516| `headers` | `object` | No | Key-value pairs sent as HTTP headers with every request to the server (for example, authentication tokens). |517| `allowed_tools` | `array` | No | Restrict which tools from the server the agent may call. |518519#### Basic usage520521### Python522523    interaction = client.interactions.create(524        agent="deep-research-preview-04-2026",525        input="Check the status of my last server deployment.",526        tools=[527            {528                "type": "mcp_server",529                "name": "Deployment Tracker",530                "url": "https://mcp.example.com/mcp",531                "headers": {"Authorization": "Bearer my-token"},532            }533        ],534        background=True,535    )536537### JavaScript538539    const interaction = await client.interactions.create({540        agent: 'deep-research-preview-04-2026',541        input: 'Check the status of my last server deployment.',542        tools: [543            {544                type: 'mcp_server',545                name: 'Deployment Tracker',546                url: 'https://mcp.example.com/mcp',547                headers: { Authorization: 'Bearer my-token' }548            }549        ],550        background: true551    });552553### REST554555    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \556    -H "Content-Type: application/json" \557    -H "x-goog-api-key: $GEMINI_API_KEY" \558    -H "Api-Revision: 2026-05-20" \559    -d '{560        "agent": "deep-research-preview-04-2026",561        "input": "Check the status of my last server deployment.",562        "tools": [563            {564                "type": "mcp_server",565                "name": "Deployment Tracker",566                "url": "https://mcp.example.com/mcp",567                "headers": {"Authorization": "Bearer my-token"}568            }569        ],570        "background": true571    }'572573### File Search574575Give the agent access to your own data by using the [File Search](https://ai.google.dev/gemini-api/docs/interactions/file-search) tool.576577### Python578579    import time580    from google import genai581582    client = genai.Client()583584    interaction = client.interactions.create(585        input="Compare our 2025 fiscal year report against current public web news.",586        agent="deep-research-preview-04-2026",587        background=True,588        tools=[589            {590                "type": "file_search",591                "file_search_store_names": ['fileSearchStores/my-store-name']592            }593        ]594    )595596### JavaScript597598    const interaction = await client.interactions.create({599        input: 'Compare our 2025 fiscal year report against current public web news.',600        agent: 'deep-research-preview-04-2026',601        background: true,602        tools: [603            { type: 'file_search', file_search_store_names: ['fileSearchStores/my-store-name'] },604        ]605    });606607### REST608609    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \610    -H "Content-Type: application/json" \611    -H "x-goog-api-key: $GEMINI_API_KEY" \612    -H "Api-Revision: 2026-05-20" \613    -d '{614        "input": "Compare our 2025 fiscal year report against current public web news.",615        "agent": "deep-research-preview-04-2026",616        "background": true,617        "tools": [618            {"type": "file_search", "file_search_store_names": ["fileSearchStores/my-store-name"]},619        ]620    }'621622## Steerability and formatting623624You can steer the agent's output by providing specific formatting instructions625in your prompt. This allows you to structure reports into specific sections and626subsections, include data tables, or adjust tone for different audiences (e.g.,627"technical," "executive," "casual").628629Define the desired output format explicitly in your input text.630631### Python632633    prompt = """634    Research the competitive landscape of EV batteries.635636    Format the output as a technical report with the following structure:637    1. Executive Summary638    2. Key Players (Must include a data table comparing capacity and chemistry)639    3. Supply Chain Risks640    """641642    interaction = client.interactions.create(643        input=prompt,644        agent="deep-research-preview-04-2026",645        background=True646    )647648### JavaScript649650    const prompt = `651    Research the competitive landscape of EV batteries.652653    Format the output as a technical report with the following structure:654    1. Executive Summary655    2. Key Players (Must include a data table comparing capacity and chemistry)656    3. Supply Chain Risks657    `;658659    const interaction = await client.interactions.create({660        input: prompt,661        agent: 'deep-research-preview-04-2026',662        background: true,663    });664665### REST666667    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \668    -H "Content-Type: application/json" \669    -H "x-goog-api-key: $GEMINI_API_KEY" \670    -H "Api-Revision: 2026-05-20" \671    -d '{672        "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",673        "agent": "deep-research-preview-04-2026",674        "background": true675    }'676677## Multimodal inputs678679Deep Research supports multimodal inputs, including images and documents (PDFs), allowing680the agent to analyze visual content and conduct web-based research681contextualized by the provided inputs.682683### Python684685    import time686    from google import genai687688    client = genai.Client()689690    prompt = """Analyze the interspecies dynamics and behavioral risks present691    in the provided image of the African watering hole. Specifically, investigate692    the symbiotic relationship between the avian species and the pachyderms693    shown, and conduct a risk assessment for the reticulated giraffes based on694    their drinking posture relative to the specific predator visible in the695    foreground."""696697    interaction = client.interactions.create(698        input=[699            {"type": "text", "text": prompt},700            {701                "type": "image",702                "mime_type": "image/jpeg",703                "uri": "https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg"704            }705        ],706        agent="deep-research-preview-04-2026",707        background=True708    )709710    print(f"Research started: {interaction.id}")711712    while True:713        interaction = client.interactions.get(interaction.id)714        if interaction.status == "completed":715            print(interaction.output_text)716            break717        elif interaction.status == "failed":718            print(f"Research failed: {interaction.error}")719            break720        time.sleep(10)721722### JavaScript723724    import { GoogleGenAI } from '@google/genai';725726    const client = new GoogleGenAI({});727728    const prompt = `Analyze the interspecies dynamics and behavioral risks present729    in the provided image of the African watering hole. Specifically, investigate730    the symbiotic relationship between the avian species and the pachyderms731    shown, and conduct a risk assessment for the reticulated giraffes based on732    their drinking posture relative to the specific predator visible in the733    foreground.`;734735    const interaction = await client.interactions.create({736        input: [737            { type: 'text', text: prompt },738            {739                type: 'image',740                mime_type: "image/jpeg",741                uri: 'https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg'742            }743        ],744        agent: 'deep-research-preview-04-2026',745        background: true746    });747748    console.log(`Research started: ${interaction.id}`);749750    while (true) {751        const result = await client.interactions.get(interaction.id);752        if (result.status === 'completed') {753            console.log(result.output_text);754            break;755        } else if (result.status === 'failed') {756            console.log(`Research failed: ${result.error}`);757            break;758        }759        await new Promise(resolve => setTimeout(resolve, 10000));760    }761762### REST763764    # 1. Start the research task with image input765    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \766    -H "Content-Type: application/json" \767    -H "x-goog-api-key: $GEMINI_API_KEY" \768    -H "Api-Revision: 2026-05-20" \769    -d '{770        "input": [771            {"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."},772            {"type": "image", "mime_type": "image/jpeg", "uri": "https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg"}773        ],774        "agent": "deep-research-preview-04-2026",775        "background": true776    }'777778    # 2. Poll for results (Replace INTERACTION_ID)779    # curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID" \780    # -H "x-goog-api-key: $GEMINI_API_KEY"781782### Document understanding783784> [!WARNING]785> **Preview:** Document understanding allows passing documents directly as multimodal input.786787Pass documents directly as multimodal input. The agent analyzes the788provided documents and conducts research grounded in their content.789790### Python791792    from google import genai793794    client = genai.Client()795796    interaction = client.interactions.create(797        agent="deep-research-preview-04-2026",798        input=[799            {"type": "text", "text": "What is this document about?"},800            {801                "type": "document",802                "uri": "https://arxiv.org/pdf/1706.03762",803                "mime_type": "application/pdf",804            },805        ],806        background=True,807    )808809### JavaScript810811    import { GoogleGenAI } from '@google/genai';812813    const client = new GoogleGenAI({});814815    const interaction = await client.interactions.create({816        agent: 'deep-research-preview-04-2026',817        input: [818            { type: 'text', text: 'What is this document about?' },819            {820                type: 'document',821                uri: 'https://arxiv.org/pdf/1706.03762',822                mime_type: 'application/pdf'823            }824        ],825        background: true826    });827828### REST829830    # 1. Start the research task with document input831    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \832    -H "Content-Type: application/json" \833    -H "x-goog-api-key: $GEMINI_API_KEY" \834    -H "Api-Revision: 2026-05-20" \835    -d '{836        "agent": "deep-research-preview-04-2026",837        "input": [838            {"type": "text", "text": "What is this document about?"},839            {"type": "document", "uri": "https://arxiv.org/pdf/1706.03762", "mime_type": "application/pdf"}840        ],841        "background": true842    }'843844## Handling long-running tasks845846Deep Research is a multi-step process involving planning, searching, reading,847and writing. This cycle typically exceeds the standard timeout limits of848synchronous API calls.849850Agents are required to use `background=True`. The API returns a partial851`Interaction` object immediately. You can use the `id` property to retrieve an852interaction for polling. The interaction state will transition from853`in_progress` to `completed` or `failed`.854855### Streaming856857Deep Research supports streaming to receive real-time updates on the research858progress including thought summaries, text output, and generated images.859You must set `stream=True` and `background=True`. For a comprehensive guide to streaming, including event types, tool streaming, and thinking, see [Streaming interactions](https://ai.google.dev/gemini-api/docs/interactions/streaming).860861To receive intermediate reasoning steps (thoughts) and progress updates,862you must enable **thinking summaries** by setting `thinking_summaries` to863`"auto"` in the `agent_config`. Without this, the stream may only provide the864final results.865866> [!NOTE]867> **Note:** The streaming connection can drop or expire. Since Deep Research tasks can run longer, your application should check the interaction status and reconnect as shown in the examples below.868869#### Stream event types870871| Event type | Delta type | Description |872|---|---|---|873| `step.delta` | `thought` | Intermediate reasoning step from the agent. |874| `step.delta` | `text` | Part of the final text output. |875| `step.delta` | `image` | A generated image (base64-encoded). |876877The following example starts a research task and processes the stream with878automatic reconnection. It tracks the `interaction_id` and `last_event_id` so879that if the connection drops (for example, after the 600-second timeout), it can880resume from where it left off.881882### Python883884    from google import genai885886    client = genai.Client()887888    interaction_id = None889    last_event_id = None890    is_complete = False891892    def process_stream(stream):893        global interaction_id, last_event_id, is_complete894        for event in stream:895            if event.event_type == "interaction.created":896                interaction_id = event.interaction.id897            if event.event_id:898                last_event_id = event.event_id899            if event.event_type == "step.delta":900                if event.delta.type == "text":901                    print(event.delta.text, end="", flush=True)902                elif event.delta.type == "thought":903                    print(f"Thought: {event.delta.text}", flush=True)904            elif event.event_type in ("interaction.completed", "error"):905                is_complete = True906907    stream = client.interactions.create(908        input="Research the history of Google TPUs.",909        agent="deep-research-preview-04-2026",910        background=True,911        stream=True,912        agent_config={"type": "deep-research", "thinking_summaries": "auto"},913    )914    process_stream(stream)915916    while not is_complete and interaction_id:917        status = client.interactions.get(interaction_id)918        if status.status != "in_progress":919            break920        stream = client.interactions.get(921            id=interaction_id, stream=True, last_event_id=last_event_id,922        )923        process_stream(stream)924925### JavaScript926927    import { GoogleGenAI } from '@google/genai';928929    const client = new GoogleGenAI({});930931    let interactionId;932    let lastEventId;933    let isComplete = false;934935    async function processStream(stream) {936        for await (const event of stream) {937            if (event.type === 'interaction.created') {938                interactionId = event.interaction.id;939            }940            if (event.event_id) lastEventId = event.event_id;941            if (event.type === 'step.delta') {942                if (event.delta.type === 'text') {943                    process.stdout.write(event.delta.text);944                } else if (event.delta.type === 'thought') {945                    console.log(`Thought: ${event.delta.text}`);946                }947            } else if (['interaction.completed', 'error'].includes(event.type)) {948                isComplete = true;949            }950        }951    }952953    const stream = await client.interactions.create({954        input: 'Research the history of Google TPUs.',955        agent: 'deep-research-preview-04-2026',956        background: true,957        stream: true,958        agent_config: { type: 'deep-research', thinking_summaries: 'auto' },959    });960    await processStream(stream);961962    while (!isComplete && interactionId) {963        const status = await client.interactions.get(interactionId);964        if (status.status !== 'in_progress') break;965        const resumeStream = await client.interactions.get(interactionId, {966            stream: true, last_event_id: lastEventId,967        });968        await processStream(resumeStream);969    }970971### REST972973    # 1. Start the stream (save the INTERACTION_ID from the interaction.start event974    #    and the last "event_id" you receive)975    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \976    -H "Content-Type: application/json" \977    -H "x-goog-api-key: $GEMINI_API_KEY" \978    -d '{979        "input": "Research the history of Google TPUs.",980        "agent": "deep-research-preview-04-2026",981        "background": true,982        "stream": true,983        "agent_config": {984            "type": "deep-research",985            "thinking_summaries": "auto"986        }987    }'988989    # 2. If the connection drops, reconnect with your saved IDs990    curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID?stream=true&last_event_id=LAST_EVENT_ID" \991    -H "x-goog-api-key: $GEMINI_API_KEY"992993## Follow-up questions and interactions994995You can continue the conversation after the agent returns the final report by996using the `previous_interaction_id`. This lets you to ask for clarification,997summarization or elaboration on specific sections of the research without998restarting the entire task.9991000### Python10011002    import time1003    from google import genai10041005    client = genai.Client()10061007    interaction = client.interactions.create(1008        input="Can you elaborate on the second point in the report?",1009        model="gemini-3.1-pro-preview",1010        previous_interaction_id="COMPLETED_INTERACTION_ID"1011    )10121013    print(interaction.output_text)10141015### JavaScript10161017    const interaction = await client.interactions.create({1018        input: 'Can you elaborate on the second point in the report?',1019        model: 'gemini-3.1-pro-preview',1020        previous_interaction_id: 'COMPLETED_INTERACTION_ID'1021    });1022    console.log(interaction.output_text);10231024### REST10251026    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1027    -H "Content-Type: application/json" \1028    -H "x-goog-api-key: $GEMINI_API_KEY" \1029    -d '{1030        "input": "Can you elaborate on the second point in the report?",1031        "model": "gemini-3.1-pro-preview",1032        "previous_interaction_id": "COMPLETED_INTERACTION_ID"1033    }'10341035## When to use Gemini Deep Research Agent10361037Deep Research is an **agent**, not just a model. It is best suited for workloads1038that require an "analyst-in-a-box" approach rather than low-latency chat.10391040| Feature | Standard Gemini Models | Gemini Deep Research Agent |1041|---|---|---|1042| **Latency** | Seconds | Minutes (Async/Background) |1043| **Process** | Generate -\> Output | Plan -\> Search -\> Read -\> Iterate -\> Output |1044| **Output** | Conversational text, code, short summaries | Detailed reports, long-form analysis, comparative tables |1045| **Best For** | Chatbots, extraction, creative writing | Market analysis, due diligence, literature reviews, competitive landscaping |10461047## Agent configuration10481049Deep Research uses the `agent_config` parameter to control behavior.1050Pass it as a dictionary with the following fields:10511052| Field | Type | Default | Description |1053|---|---|---|---|1054| `type` | `string` | Required | Must be `"deep-research"`. |1055| `thinking_summaries` | `string` | `"none"` | Set to `"auto"` to receive intermediate reasoning steps during streaming. Set to `"none"` to disable. |1056| `visualization` | `string` | `"auto"` | Set to `"auto"` to enable agent-generated charts and images. Set to `"off"` to disable. |1057| `collaborative_planning` | `boolean` | `false` | Set to `true` to enable multi-turn plan review before research begins. |10581059### Python10601061    agent_config = {1062        "type": "deep-research",1063        "thinking_summaries": "auto",1064        "visualization": "auto",1065        "collaborative_planning": False,1066    }10671068    interaction = client.interactions.create(1069        agent="deep-research-preview-04-2026",1070        input="Research the competitive landscape of cloud GPUs.",1071        agent_config=agent_config,1072        background=True,1073    )10741075### JavaScript10761077    const interaction = await client.interactions.create({1078        agent: 'deep-research-preview-04-2026',1079        input: 'Research the competitive landscape of cloud GPUs.',1080        agent_config: {1081            type: 'deep-research',1082            thinking_summaries: 'auto',1083            visualization: 'auto',1084            collaborative_planning: false,1085        },1086        background: true,1087    });10881089### REST10901091    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1092    -H "Content-Type: application/json" \1093    -H "x-goog-api-key: $GEMINI_API_KEY" \1094    -d '{1095        "input": "Research the competitive landscape of cloud GPUs.",1096        "agent": "deep-research-preview-04-2026",1097        "agent_config": {1098            "type": "deep-research",1099            "thinking_summaries": "auto",1100            "visualization": "auto",1101            "collaborative_planning": false1102        },1103        "background": true1104    }'11051106## Availability and pricing11071108You can access the Gemini Deep Research Agent using the Interactions API in Google AI Studio and the Gemini API.11091110Pricing follows a [pay-as-you-go model](https://ai.google.dev/gemini-api/docs/pricing#pricing-for-agents) based on the underlying Gemini models and the specific tools the agent utilizes. Unlike standard chat requests, where a request leads to one output, a Deep Research task is an agentic workflow. A single request triggers an autonomous loop of planning, searching, reading, and reasoning.11111112### Estimated costs11131114Costs vary based on the depth of research required. The agent autonomously determines how much reading and searching is necessary to answer your prompt.11151116- **Deep Research** (`deep-research-preview-04-2026`): For a typical query requiring moderate analysis, the agent might use \~80 search queries, \~250k input tokens (\~50-70% cached), and \~60k output tokens.1117  - **Estimated total:** \~$1.00 -- $3.00 per task1118- **Deep Research Max** (`deep-research-max-preview-04-2026`): For deep competitive landscape analysis or extensive due diligence, the agent might use up to \~160 search queries, \~900k input tokens (\~50-70% cached), and \~80k output tokens.1119  - **Estimated total:** \~$3.00 -- $7.00 per task11201121> [!NOTE]1122> **Note:** These figures are estimates based on preview rates and are subject to change.11231124## Safety considerations11251126Giving an agent access to the web and your private files requires careful1127consideration of safety risks.11281129- **Prompt injection using files:** The agent reads the contents of the files you provide. Ensure that uploaded documents (PDFs, text files) come from trusted sources. A malicious file could contain hidden text designed to manipulate the agent's output.1130- **Web content risks:** The agent searches the public web. While we implement robust safety filters, there is a risk that the agent may encounter and process malicious web pages. We recommend reviewing the `citations` provided in the response to verify the sources.1131- **Exfiltration:** Be cautious when asking the agent to summarize sensitive internal data if you are also allowing it to browse the web.11321133## Best practices11341135- **Prompt for unknowns:** Instruct the agent on how to handle missing data. For example, add *"If specific figures for 2025 are not available,1136  explicitly state they are projections or unavailable rather than1137  estimating"* to your prompt.1138- **Provide context:** Ground the agent's research by providing background information or constraints directly in the input prompt.1139- **Use collaborative planning:** For complex queries, enable collaborative planning to review and refine the research plan before execution.1140- **Multimodal inputs:** Deep Research Agent supports multi-modal inputs. Use cautiously, as this increases costs and risks context window overflow.11411142## Limitations11431144- **Beta status**: The Interactions API is in public beta. Features and schemas may change.1145- **Custom tools:** You cannot currently provide custom Function Calling tools but you can use remote MCP (Model Context Protocol) servers with the Deep Research agent.1146- **Structured output:** The Deep Research Agent currently doesn't support structured outputs.1147- **Max research time:** The Deep Research agent has a maximum research time of 60 minutes. Most tasks should complete within 20 minutes.1148- **Store requirement:** Agent execution using `background=True` requires `store=True`.1149- **Google search:** [Google1150  Search](https://ai.google.dev/gemini-api/docs/interactions/google-search) is enabled by default and [specific1151  restrictions](https://ai.google.dev/gemini-api/terms#use-restrictions2) apply to the grounded results.11521153## What's next11541155- Learn more about the [Interactions API](https://ai.google.dev/gemini-api/docs/interactions).1156- Learn how to use your own data using the [File Search](https://ai.google.dev/gemini-api/docs/interactions/file-search) tool.
Files main
Menu

Theme