Начало работы с Gemini Deep Research API
@ai_longreadsРуководство по использованию нового агента Gemini Deep Research через Interactions API для выполнения сложных исследовательских задач, генерации изображений и перевода результатов.
Это AI-перевод статьи, сделанный каналом Про AI: Лучшие Статьи и Исследования.
Начало работы с Gemini Deep Research API
Getting Started with Gemini Deep Research API Автор: Philipp Schmid Оригинальный текст:
Это руководство демонстрирует, как использовать нового агента Gemini Deep Research через Interactions API для выполнения сложных исследовательских задач, генерации изображений на основе результатов и их перевода.
Предварительная версия: Агент Gemini Deep Research в настоящее время находится в режиме предварительного просмотра. Он доступен исключительно через Interactions API. Доступ через generate_content невозможен.
!uv pip install google-genai --upgrade
import time from google import genai from IPython.display import display, Markdown client = genai.Client()
1. Базовая исследовательская задача (Polling)
Следующий пример показывает, как запустить исследовательскую задачу в фоновом режиме и опрашивать результаты. Это стандартный способ взаимодействия с агентом Deep Research.
prompt = "Research the history of Google TPUs."
interaction = client.interactions.create(
agent='deep-research-pro-preview-12-2025',
input=prompt,
background=True
)
print(f"Research started: {interaction.id}")
# Опрос результатов
while True:
interaction = client.interactions.get(interaction.id)
if interaction.status == "completed":
print(f"Research completed: {interaction.id}")
break
elif interaction.status == "failed":
print(f"Research failed: {interaction.error}")
break
print(".", end="", flush=True)
time.sleep(10)
display(Markdown(interaction.outputs[-1].text))Пример вывода — развёрнутый анализ эволюции Google TPU:
- Истоки: Проект TPU (Tensor Processing Unit) был начат в 2013 году, когда инженеры Google осознали, что существующая инфраструктура на CPU и GPU не сможет выдержать вычислительные требования повсеместного голосового поиска и приложений глубокого обучения без удвоения площади дата-центров.
- Смена архитектурной парадигмы: В отличие от архитектуры фон Неймана в CPU, TPU используют архитектуру систолической матрицы. Данные проходят через тысячи арифметико-логических устройств без обращения к памяти для промежуточных результатов, что резко повышает эффективность матричных умножений.
2. Продвинутая исследовательская задача (Streaming, Thinking, Prompting)
Deep Research поддерживает streaming (потоковую передачу) для получения обновлений о ходе исследования в реальном времени (thinking_summaries). Вы можете направлять вывод агента, предоставляя конкретные инструкции в промпте.
# Определяем сложный промпт с инструкциями по форматированию
prompt = """
Research the history and future developments of the Google TPUs.
Focus on:
1. Key technological breakthroughs in the last 12 months.
2. Major competitors and their projected timelines for mass production.
3. Future developments and plans for 2026 and beyond
Format the output:
- as a strategic briefing document for an developer educating themselves about the Google TPU landscape.
- Include a table comparing the top 3 leading companies.
- Use short concise sentence and bullet points.
"""
stream = client.interactions.create(
agent="deep-research-pro-preview-12-2025",
input=prompt,
background=True,
stream=True,
agent_config={
"type": "deep-research",
"thinking_summaries": "auto"
}
)
interaction_id = None
last_event_id = None
report = ""
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":
report += chunk.delta.text
elif chunk.delta.type == "thought_summary":
print(f"{chunk.delta.content.text}\n", flush=True)
elif chunk.event_type == "interaction.complete":
print(chunk)
print("\nResearch Complete")
prev_ia = client.interactions.get(interaction_id)
print(prev_ia)
display(Markdown(report))Полный отчёт: https://gist.github.com/philschmid/68c5afacfd3a3555ca834ba27415ba88
3. Комбинирование Deep Research с взаимодействиями модели
Interactions API поддерживает stateful-взаимодействия (взаимодействия с сохранением состояния), что позволяет продолжить диалог после получения итогового отчёта, используя previous_interaction_id.
Вы можете продолжить разговор после получения итогового отчёта, используя модель для визуализации результатов или их перевода с помощью Gemini Flash.
import base64
from IPython.display import Image
print("Generating image...")
image_interaction = client.interactions.create(
model="gemini-3-pro-image-preview",
input="Visualize the report into a timeline slide",
previous_interaction_id=interaction_id,
)
image_data = [data for data in image_interaction.outputs if data.type == "image"]
for output in image_data:
image_data = base64.b64decode(output.data)
display(Image(data=image_data))print("Translating...")
translate_interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Translate the report into simple German.",
previous_interaction_id=interaction_id,
)
display(Markdown(translate_interaction.outputs[-1].text))Пример вывода перевода на немецкий:
Подпишитесь на канал и каждый день читайте лучшие материалы про AI переведенные на русский!
Нашли интересную статью для перевода? Пришлите нашему боту: @ailongreadsbot