Агент по глубоким исследованиям компании Gemini

Агент Gemini Deep Research автономно планирует, выполняет и анализирует многоэтапные исследовательские задачи. Работая на базе Gemini, он ориентируется в сложных информационных ландшафтах, создавая подробные отчеты с цитируемыми источниками. Новые возможности позволяют совместно планировать исследования с агентом, подключаться к внешним инструментам через серверы MCP, включать визуализации (например, диаграммы и графики) и предоставлять документы непосредственно в качестве входных данных.

Исследовательские задачи включают итеративный поиск и чтение и могут занимать несколько минут. Для асинхронного запуска агента и получения результатов или потоковой передачи обновлений необходимо использовать фоновое выполнение (установите background=true ). Дополнительные сведения см. в разделе «Обработка длительных задач» .

В следующем примере показано, как запустить исследовательскую задачу в фоновом режиме и запросить результаты.

Python

import time
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    input="Research the history of Google TPUs.",
    agent="deep-research-preview-04-2026",
    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-preview-04-2026',
    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));
}

ОТДЫХ

# 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-preview-04-2026",
    "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"

Поддерживаемые версии

Агент Deep Research выпускается в двух версиях:

  • Deep Research ( deep-research-preview-04-2026 ): Разработан для скорости и эффективности, идеально подходит для потоковой передачи данных обратно в пользовательский интерфейс клиента.
  • Deep Research Max ( deep-research-max-preview-04-2026 ): Максимальная всесторонность для автоматизированного сбора и синтеза контекста.

Совместное планирование

Совместное планирование позволяет контролировать направление исследования до того, как агент начнет свою работу. При включении этой функции агент возвращает предлагаемый план исследования вместо немедленного выполнения. Затем вы можете просмотреть, изменить или утвердить план в ходе многоэтапных взаимодействий.

Шаг 1: Запросите тарифный план

Установите collaborative_planning=True при первом взаимодействии. Агент вернет план исследования вместо полного отчета.

Python

from google import genai

client = genai.Client()

# First interaction: request a research plan
plan_interaction = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="Do some research on Google TPUs.",
    agent_config={
        "type": "deep-research",
        "thinking_summaries": "auto",
        "collaborative_planning": True,
    },
    background=True,
)

# Wait for and retrieve the plan
while (result := client.interactions.get(id=plan_interaction.id)).status != "completed":
    time.sleep(5)
print(result.outputs[-1].text)

JavaScript

const planInteraction = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'Do some research on Google TPUs.',
    agent_config: {
        type: 'deep-research',
        thinking_summaries: 'auto',
        collaborative_planning: true
    },
    background: true
});

let result;
while ((result = await client.interactions.get(planInteraction.id)).status !== 'completed') {
    await new Promise(r => setTimeout(r, 5000));
}
console.log(result.outputs[result.outputs.length - 1].text);

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": "Do some research on Google TPUs.",
    "agent_config": {
        "type": "deep-research",
        "thinking_summaries": "auto",
        "collaborative_planning": true
    },
    "background": true
}'

Шаг 2: Уточните план (необязательно)

Используйте previous_interaction_id , чтобы продолжить обсуждение и доработать план. Оставьте collaborative_planning=True , чтобы оставаться в режиме планирования.

Python

# Second interaction: refine the plan
refined_plan = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="Focus more on the differences between Google TPUs and competitor hardware, and less on the history.",
    agent_config={
        "type": "deep-research",
        "thinking_summaries": "auto",
        "collaborative_planning": True,
    },
    previous_interaction_id=plan_interaction.id,
    background=True,
)

while (result := client.interactions.get(id=refined_plan.id)).status != "completed":
    time.sleep(5)
print(result.outputs[-1].text)

JavaScript

const refinedPlan = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'Focus more on the differences between Google TPUs and competitor hardware, and less on the history.',
    agent_config: {
        type: 'deep-research',
        thinking_summaries: 'auto',
        collaborative_planning: true
    },
    previous_interaction_id: planInteraction.id,
    background: true
});

let result;
while ((result = await client.interactions.get(refinedPlan.id)).status !== 'completed') {
    await new Promise(r => setTimeout(r, 5000));
}
console.log(result.outputs[result.outputs.length - 1].text);

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": "Focus more on the differences between Google TPUs and competitor hardware, and less on the history.",
    "agent_config": {
        "type": "deep-research",
        "thinking_summaries": "auto",
        "collaborative_planning": true
    },
    "previous_interaction_id": "PREVIOUS_INTERACTION_ID",
    "background": true
}'

Шаг 3: Утвердить и выполнить

Установите параметр collaborative_planning=False (или опустите его), чтобы утвердить план и начать исследование.

Python

# Third interaction: approve the plan and kick off research
final_report = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="Plan looks good!",
    agent_config={
        "type": "deep-research",
        "thinking_summaries": "auto",
        "collaborative_planning": False,
    },
    previous_interaction_id=refined_plan.id,
    background=True,
)

while (result := client.interactions.get(id=final_report.id)).status != "completed":
    time.sleep(5)
print(result.outputs[-1].text)

JavaScript

const finalReport = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'Plan looks good!',
    agent_config: {
        type: 'deep-research',
        thinking_summaries: 'auto',
        collaborative_planning: false
    },
    previous_interaction_id: refinedPlan.id,
    background: true
});

let result;
while ((result = await client.interactions.get(finalReport.id)).status !== 'completed') {
    await new Promise(r => setTimeout(r, 5000));
}
console.log(result.outputs[result.outputs.length - 1].text);

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": "Plan looks good!",
    "agent_config": {
        "type": "deep-research",
        "thinking_summaries": "auto",
        "collaborative_planning": false
    },
    "previous_interaction_id": "PREVIOUS_INTERACTION_ID",
    "background": true
}'

Визуализация

Когда visualization установлен режим "auto" , агент может генерировать диаграммы, графики и другие визуальные элементы для подтверждения результатов исследования. Сгенерированные изображения включаются в выходные данные ответа и передаются в виде дельта image . Для достижения наилучших результатов явно укажите в запросе необходимость визуализации — например, «Включить диаграммы, показывающие тенденции во времени» или «Сгенерировать графики, сравнивающие долю рынка». Установка visualization в режим "auto" активирует эту возможность, но агент генерирует визуализацию только тогда, когда это запрашивается.

Python

import base64
from IPython.display import Image, display

interaction = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="Analyze global semiconductor market trends. Include graphics showing market share changes.",
    agent_config={
        "type": "deep-research",
        "visualization": "auto",
    },
    background=True,
)

print(f"Research started: {interaction.id}")

while (result := client.interactions.get(id=interaction.id)).status != "completed":
    time.sleep(5)

for output in result.outputs:
    if output.type == "text":
        print(output.text)
    elif output.type == "image" and output.data:
        image_bytes = base64.b64decode(output.data)
        print(f"Received image: {len(image_bytes)} bytes")
        # To display in a Jupyter notebook:
        # from IPython.display import display, Image
        # display(Image(data=image_bytes))

JavaScript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'Analyze global semiconductor market trends. Include graphics showing market share changes.',
    agent_config: {
        type: 'deep-research',
        visualization: 'auto'
    },
    background: true
});

console.log(`Research started: ${interaction.id}`);

let result;
while ((result = await client.interactions.get(interaction.id)).status !== 'completed') {
    await new Promise(r => setTimeout(r, 5000));
}

for (const output of result.outputs) {
    if (output.type === 'text') {
        console.log(output.text);
    } else if (output.type === 'image' && output.data) {
        console.log(`[Image Output: ${output.data.substring(0, 20)}...]`);
    }
}

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": "Analyze global semiconductor market trends. Include graphics showing market share changes.",
    "agent_config": {
        "type": "deep-research",
        "visualization": "auto"
    },
    "background": true
}'

Поддерживаемые инструменты

Deep Research поддерживает множество встроенных и внешних инструментов. По умолчанию (если параметр tools не указан) агент имеет доступ к поиску Google, контексту URL и выполнению кода. Вы можете явно указать инструменты, чтобы ограничить или расширить возможности агента.

Инструмент Тип значения Описание
Поиск Google google_search Поиск в открытом доступе в интернете. Включено по умолчанию.
Контекст URL url_context Чтение и краткое изложение содержимого веб-страницы. Включено по умолчанию.
Выполнение кода code_execution Выполнить код для проведения вычислений и анализа данных. Включено по умолчанию.
Сервер MCP mcp_server Для доступа к внешним инструментам подключитесь к удалённым серверам MCP.
Поиск файлов file_search Выполните поиск в загруженных вами корпусах документов.

Явно укажите Google Поиск в качестве единственного используемого инструмента:

Python

interaction = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="What are the latest developments in quantum computing?",
    tools=[{"type": "google_search"}],
    background=True,
)

JavaScript

const interaction = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'What are the latest developments in quantum computing?',
    tools: [{ type: 'google_search' }],
    background: true
});

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": "What are the latest developments in quantum computing?",
    "tools": [{"type": "google_search"}],
    "background": true
}'

Контекст URL

Предоставьте агенту возможность читать и кратко излагать содержание конкретных веб-страниц:

Python

interaction = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="Summarize the content of https://www.wikipedia.org/.",
    tools=[{"type": "url_context"}],
    background=True,
)

JavaScript

const interaction = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'Summarize the content of https://www.wikipedia.org/.',
    tools: [{ type: 'url_context' }],
    background: true
});

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": "Summarize the content of https://www.wikipedia.org/.",
    "tools": [{"type": "url_context"}],
    "background": true
}'

Выполнение кода

Разрешите агенту выполнять код для вычислений и анализа данных:

Python

interaction = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="Calculate the 50th Fibonacci number.",
    tools=[{"type": "code_execution"}],
    background=True,
)

JavaScript

const interaction = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'Calculate the 50th Fibonacci number.',
    tools: [{ type: 'code_execution' }],
    background: true
});

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": "Calculate the 50th Fibonacci number.",
    "tools": [{"type": "code_execution"}],
    "background": true
}'

Серверы MCP

Укажите name и url сервера в конфигурации инструментов. Вы также можете передать учетные данные для аутентификации и ограничить доступ агента к определенным инструментам.

Поле Тип Необходимый Описание
type string Да Должно быть "mcp_server" .
name string Нет Отображаемое имя для сервера MCP.
url string Нет Полный URL-адрес конечной точки сервера MCP.
headers object Нет Пары ключ-значение отправляются в качестве HTTP-заголовков с каждым запросом к серверу (например, токены аутентификации).
allowed_tools array Нет Ограничьте доступ агента к определенным инструментам на сервере.

Основное использование

Python

interaction = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="Check the status of my last server deployment.",
    tools=[
        {
            "type": "mcp_server",
            "name": "Deployment Tracker",
            "url": "https://mcp.example.com/mcp",
            "headers": {"Authorization": "Bearer my-token"},
        }
    ],
    background=True,
)

JavaScript

const interaction = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'Check the status of my last server deployment.',
    tools: [
        {
            type: 'mcp_server',
            name: 'Deployment Tracker',
            url: 'https://mcp.example.com/mcp',
            headers: { Authorization: 'Bearer my-token' }
        }
    ],
    background: true
});

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": "Check the status of my last server deployment.",
    "tools": [
        {
            "type": "mcp_server",
            "name": "Deployment Tracker",
            "url": "https://mcp.example.com/mcp",
            "headers": {"Authorization": "Bearer my-token"}
        }
    ],
    "background": true
}'

Предоставьте агенту доступ к вашим данным, используя инструмент поиска файлов .

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-preview-04-2026",
    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-preview-04-2026',
    background: true,
    tools: [
        { type: 'file_search', file_search_store_names: ['fileSearchStores/my-store-name'] },
    ]
});

ОТДЫХ

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-preview-04-2026",
    "background": true,
    "tools": [
        {"type": "file_search", "file_search_store_names": ["fileSearchStores/my-store-name"]},
    ]
}'

Управляемость и форматирование

Вы можете управлять выводом агента, указывая конкретные инструкции по форматированию в своем запросе. Это позволяет структурировать отчеты по определенным разделам и подразделам, включать таблицы данных или корректировать тон для разных аудиторий (например, «технические специалисты», «руководители», «неформальные пользователи»).

Укажите желаемый формат вывода явно во входном тексте.

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-preview-04-2026",
    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-preview-04-2026',
    background: true,
});

ОТДЫХ

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-preview-04-2026",
    "background": true
}'

Мультимодальные входные данные

Deep Research поддерживает мультимодальные входные данные, включая изображения и документы (PDF), что позволяет агенту анализировать визуальный контент и проводить веб-исследования в контексте предоставленных входных данных.

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-preview-04-2026",
    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-preview-04-2026',
    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));
}

ОТДЫХ

# 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-preview-04-2026",
    "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"

Понимание документа

Передайте документы напрямую в качестве мультимодального ввода. Агент анализирует предоставленные документы и проводит исследование, основанное на их содержании.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input=[
        {"type": "text", "text": "What is this document about?"},
        {
            "type": "document",
            "uri": "https://arxiv.org/pdf/1706.03762",
            "mime_type": "application/pdf",
        },
    ],
    background=True,
)

JavaScript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: [
        { type: 'text', text: 'What is this document about?' },
        {
            type: 'document',
            uri: 'https://arxiv.org/pdf/1706.03762',
            mime_type: 'application/pdf'
        }
    ],
    background: true
});

ОТДЫХ

# 1. Start the research task with document input
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "deep-research-preview-04-2026",
    "input": [
        {"type": "text", "text": "What is this document about?"},
        {"type": "document", "uri": "https://arxiv.org/pdf/1706.03762", "mime_type": "application/pdf"}
    ],
    "background": true
}'

Выполнение длительных задач

Глубокое исследование — это многоэтапный процесс, включающий планирование, поиск, чтение и запись. Этот цикл обычно превышает стандартные ограничения по времени ожидания для синхронных вызовов API.

Агентам необходимо использовать background=True . API немедленно возвращает частичный объект Interaction . Вы можете использовать свойство id для получения информации о взаимодействии для опроса. Состояние взаимодействия будет переходить из in_progress в completed или failed .

Стриминг

Deep Research поддерживает потоковую передачу данных для получения обновлений о ходе исследования в режиме реального времени, включая краткие обзоры идей, текстовый вывод и сгенерированные изображения. Необходимо установить stream=True и background=True .

Для получения промежуточных этапов рассуждений (мыслей) и обновлений о ходе выполнения необходимо включить сводки рассуждений , установив параметр thinking_summaries в значение "auto" в файле agent_config . Без этого поток может предоставлять только окончательные результаты.

Типы событий потока

Тип события Дельта-тип Описание
content.delta thought_summary Промежуточный этап рассуждений со стороны агента.
content.delta text Часть итогового текстового вывода.
content.delta image Сгенерированное изображение (закодированное в base64).

В следующем примере запускается исследовательская задача и обрабатывается поток с автоматическим переподключением. Он отслеживает interaction_id и last_event_id , чтобы в случае разрыва соединения (например, после истечения 600-секундного таймаута) можно было продолжить с того места, где остановилось.

Python

from google import genai

client = genai.Client()

interaction_id = None
last_event_id = None
is_complete = False

def process_stream(stream):
    global interaction_id, last_event_id, is_complete
    for chunk in stream:
        if chunk.event_type == "interaction.start":
            interaction_id = chunk.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 in ("interaction.complete", "error"):
            is_complete = True

stream = client.interactions.create(
    input="Research the history of Google TPUs.",
    agent="deep-research-preview-04-2026",
    background=True,
    stream=True,
    agent_config={"type": "deep-research", "thinking_summaries": "auto"},
)
process_stream(stream)

# Reconnect if the connection drops
while not is_complete and interaction_id:
    status = client.interactions.get(interaction_id)
    if status.status != "in_progress":
        break
    stream = client.interactions.get(
        id=interaction_id, stream=True, last_event_id=last_event_id,
    )
    process_stream(stream)

JavaScript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

let interactionId;
let lastEventId;
let isComplete = false;

async function processStream(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 (['interaction.complete', 'error'].includes(chunk.event_type)) {
            isComplete = true;
        }
    }
}

const stream = await client.interactions.create({
    input: 'Research the history of Google TPUs.',
    agent: 'deep-research-preview-04-2026',
    background: true,
    stream: true,
    agent_config: { type: 'deep-research', thinking_summaries: 'auto' },
});
await processStream(stream);

// Reconnect if the connection drops
while (!isComplete && interactionId) {
    const status = await client.interactions.get(interactionId);
    if (status.status !== 'in_progress') break;
    const resumeStream = await client.interactions.get(interactionId, {
        stream: true, last_event_id: lastEventId,
    });
    await processStream(resumeStream);
}

ОТДЫХ

# 1. Start the stream (save the INTERACTION_ID from the interaction.start event
#    and the last "event_id" you receive)
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-preview-04-2026",
    "background": true,
    "stream": true,
    "agent_config": {
        "type": "deep-research",
        "thinking_summaries": "auto"
    }
}'

# 2. If the connection drops, reconnect with your saved IDs
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID?stream=true&last_event_id=LAST_EVENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY"

Дополнительные вопросы и взаимодействие

После того, как агент вернет окончательный отчет, вы можете продолжить разговор, используя previous_interaction_id . Это позволит вам запросить уточнения, обобщения или дополнения по конкретным разделам исследования, не начиная всю задачу заново.

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[interaction.outputs.length - 1].text);

ОТДЫХ

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

Когда использовать Gemini Deep Research Agent

Deep Research — это агент , а не просто модель. Он лучше всего подходит для задач, требующих подхода «аналитик в коробке», а не для чата с низкой задержкой.

Особенность Стандартные модели Gemini Агент по глубоким исследованиям компании Gemini
Задержка Секунды Минуты (асинхронный/фоновый режим)
Процесс Сгенерировать -> Вывод Планирование -> Поиск -> Чтение -> Итерация -> Вывод
Выход Разговорный текст, код, краткие резюме Подробные отчеты, развернутый анализ, сравнительные таблицы.
Лучше всего подходит для Чат-боты, извлечение информации, креативное письмо Анализ рынка, комплексная проверка, обзор литературы, анализ конкурентной среды.

Конфигурация агента

Компания Deep Research использует параметр agent_config для управления поведением. Передайте его в виде словаря со следующими полями:

Поле Тип По умолчанию Описание
type string Необходимый Необходимо провести "deep-research" .
thinking_summaries string "none" Установите значение "auto" , чтобы получать промежуточные этапы анализа во время потоковой передачи. Установите значение "none" , чтобы отключить.
visualization string "auto" Установите значение "auto" , чтобы включить создание диаграмм и изображений агентом. Установите значение "off" , чтобы отключить.
collaborative_planning boolean false Установите значение true , чтобы включить многоэтапную проверку плана до начала исследования.

Python

agent_config = {
    "type": "deep-research",
    "thinking_summaries": "auto",
    "visualization": "auto",
    "collaborative_planning": False,
}

interaction = client.interactions.create(
    agent="deep-research-preview-04-2026",
    input="Research the competitive landscape of cloud GPUs.",
    agent_config=agent_config,
    background=True,
)

JavaScript

const interaction = await client.interactions.create({
    agent: 'deep-research-preview-04-2026',
    input: 'Research the competitive landscape of cloud GPUs.',
    agent_config: {
        type: 'deep-research',
        thinking_summaries: 'auto',
        visualization: 'auto',
        collaborative_planning: false,
    },
    background: true,
});

ОТДЫХ

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 cloud GPUs.",
    "agent": "deep-research-preview-04-2026",
    "agent_config": {
        "type": "deep-research",
        "thinking_summaries": "auto",
        "visualization": "auto",
        "collaborative_planning": false
    },
    "background": true
}'

Наличие и цены

Вы можете получить доступ к Gemini Deep Research Agent, используя Interactions API в Google AI Studio и Gemini API.

Ценообразование основано на модели оплаты по мере использования, исходя из базовых моделей Gemini и конкретных инструментов, используемых агентом. В отличие от стандартных запросов в чате, где запрос приводит к одному результату, задача «Глубокое исследование» представляет собой рабочий процесс агента. Один запрос запускает автономный цикл планирования, поиска, чтения и анализа.

Ориентировочные затраты

Стоимость зависит от глубины необходимого исследования. Агент самостоятельно определяет, сколько чтения и поиска потребуется для ответа на ваш запрос.

  • Глубокое исследование ( deep-research-preview-04-2026 ): Для типичного запроса, требующего умеренного анализа, агент может использовать около 80 поисковых запросов, около 250 тыс. входных токенов (примерно 50-70% кэшированы) и около 60 тыс. выходных токенов.
    • Ориентировочная общая стоимость: ~1,00–3,00 доллара за задание.
  • Deep Research Max ( deep-research-max-preview-04-2026 ): Для глубокого анализа конкурентной среды или проведения всесторонней комплексной проверки агент может использовать до ~160 поисковых запросов, ~900 тыс. входных токенов (~50-70% кэшируются) и ~80 тыс. выходных токенов.
    • Ориентировочная общая стоимость: ~3,00–7,00 долларов за задание.

Вопросы безопасности

Предоставление агенту доступа к интернету и вашим личным файлам требует тщательного учета рисков для безопасности.

  • Внедрение подсказок с использованием файлов: агент считывает содержимое предоставленных вами файлов. Убедитесь, что загружаемые документы (PDF-файлы, текстовые файлы) поступают из надежных источников. Вредоносный файл может содержать скрытый текст, предназначенный для манипулирования выводом агента.
  • Риски, связанные с веб-контентом: Агент осуществляет поиск в общедоступной сети Интернет. Хотя мы используем надежные фильтры безопасности, существует риск того, что агент может столкнуться с вредоносными веб-страницами и обработать их. Мы рекомендуем проверить citations предоставленные в ответе, чтобы убедиться в достоверности источников.
  • Извлечение информации: Будьте осторожны, запрашивая у агента краткое изложение конфиденциальных внутренних данных, если вы также разрешаете ему просматривать веб-страницы.

Передовые методы

  • Подсказка для неизвестных данных: проинструктируйте агента, как обрабатывать отсутствующие данные. Например, добавьте в подсказку фразу : «Если конкретные данные за 2025 год недоступны, явно укажите, что это прогнозы или данные, которые не доступны, а не оценки» .
  • Предоставьте контекст: обоснуйте исследование агента, предоставив справочную информацию или ограничения непосредственно в подсказке для ввода.
  • Используйте совместное планирование: для сложных запросов включите совместное планирование, чтобы просмотреть и уточнить план исследования перед его выполнением.
  • Мультимодальный ввод: Deep Research Agent поддерживает мультимодальный ввод. Используйте с осторожностью, так как это увеличивает затраты и риск переполнения контекстного окна.

Ограничения

  • Статус бета-версии : API взаимодействий находится в стадии публичного бета-тестирования. Функции и схемы могут изменяться.
  • Пользовательские инструменты: В настоящее время вы не можете предоставлять пользовательские инструменты вызова функций, но вы можете использовать удаленные серверы MCP (Model Context Protocol) с агентом Deep Research.
  • Структурированный вывод: В настоящее время Deep Research Agent не поддерживает структурированный вывод.
  • Максимальное время исследования: Агент Deep Research может проводить исследование максимум 60 минут. Большинство задач должны быть выполнены в течение 20 минут.
  • Требование к хранилищу: Для выполнения агента с background=True требуется store=True .
  • Поиск Google: Поиск Google включен по умолчанию, и к полученным результатам применяются определенные ограничения .

Что дальше?