Руководство по миграции в связи с критическими изменениями API взаимодействия (май 2026 г.)

В версии v1beta API взаимодействия вносятся существенные изменения, которые перестраивают структуру API для поддержки будущих возможностей, таких как управление в процессе выполнения и асинхронные вызовы инструментов. На этой странице объясняется, что меняется, и приводятся примеры кода до и после изменений, которые помогут вам осуществить миграцию. Изменения делятся на две категории:

  1. Схема шагов : Новый массив steps заменяет массив outputs , обеспечивая структурированную временную шкалу каждого этапа взаимодействия.
  2. Настройка формата вывода : Новый полиморфный response_format объединяет все элементы управления форматом вывода и удаляет response_mime_type .

Чтобы обновить интеграцию, выполните действия, описанные в разделе «Как перейти на новую схему» .

Ключевое изменение: outputs в steps

В новой схеме массив outputs заменен массивом steps .

  • Устаревший вариант : В ответах возвращался плоский массив outputs , содержащий только сгенерированный моделью контент.
  • Новая схема : Ответы возвращают массив steps , содержащий структурированные шаги с дискриминаторами типов.

POST /interactions возвращает только этапы вывода. GET /interactions/{id} возвращает полную временную шкалу этапов, включая начальный этап user_input .

Базовый ввод/вывод (унарный)

До (наследие)

Python

# Request
interaction = client.interactions.create(
    model="gemini-3-flash-preview", input="Tell me a joke."
)

# Response access
print(interaction.outputs[-1].text)

JavaScript

// Request
const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Tell me a joke.'
});

// Response access
console.log(interaction.outputs[-1].text);

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Tell me a joke."
  }'
// Response
{
  "id": "int_123",
  "role": "model",
  "outputs": [
    {
      "type": "text",
      "text": "Why did the chicken cross the road?"
    }
  ]
}

После (новой схемы)

Python

# Request
interaction = client.interactions.create(
    model="gemini-3-flash-preview", input="Tell me a joke."
)

# Response access
print(interaction.steps[-1].content[0].text)  # CHANGED: steps instead of outputs

JavaScript

// Request
const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Tell me a joke.'
});

// Response access
console.log(interaction.steps.at(-1).content[0].text);

ОТДЫХ

# Opt-in needed before May 26th
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Tell me a joke."
  }'
// POST Response
{
  "id": "int_123",
  "steps": [
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "Why did the chicken cross the road?"
        }
      ]
    }
  ]
}

// GET /v1beta/interactions/int_123 (returns full timeline including input)
{
  "id": "int_123",
  "steps": [
    {
      "type": "user_input",
      "content": [
        { "type": "text", "text": "Tell me a joke." }
      ]
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "Why did the chicken cross the road?"
        }
      ]
    }
  ]
}

Вызов функции

Структура запроса остается неизменной, но в ответе плоское содержимое outputs заменяется структурированными шагами.

До (наследие)

Python

# Accessing function call in legacy schema
for output in interaction.outputs:
    if output.type == "function_call":
        print(f"Calling {output.name} with {output.arguments}")

JavaScript

// Accessing function call in legacy schema
for (const output of interaction.outputs) {
    if (output.type === 'function_call') {
        console.log(`Calling {output.name} with {JSON.stringify(output.arguments)}`);
    }
}

ОТДЫХ

// Response
{
  "id": "int_001",
  "role": "model",
  "status": "requires_action",
  "outputs": [
    {
      "type": "thought",
      "signature": "abc123..."
    },
    {
      "type": "function_call",
      "id": "fc_1",
      "name": "get_weather",
      "arguments": { "location": "Boston, MA" }
    }
  ]
}

После (новой схемы)

Python

# Accessing function call in new steps schema
for step in interaction.steps:
    if step.type == "function_call":
        print(f"Calling {step.name} with {step.arguments}")

JavaScript

// Accessing function call in new steps schema
for (const step of interaction.steps) {
    if (step.type === 'function_call') {
        console.log(`Calling {step.name} with {JSON.stringify(step.arguments)}`);
    }
}

ОТДЫХ

// POST Response
{
  "id": "int_001",
  "status": "requires_action",
  "steps": [
    {
      "type": "thought",
      "summary": [{
        "type": "text",
        "text": "I need to check the weather in Boston..."
      }],
      "signature": "abc123..."
    },
    {
      "type": "function_call",
      "id": "fc_1",
      "name": "get_weather",
      "arguments": { "location": "Boston, MA" }
    }
  ]
}

Инструменты на стороне сервера

Инструменты на стороне сервера (например, поиск Google или выполнение кода) теперь выдают определенные типы шагов в массиве steps . Если в старой схеме эти операции возвращались как определенные типы контента в массиве outputs , то в новой схеме они перемещены в массив steps . В следующих примерах используется поиск Google.

До (наследие)

Python

# Accessing search results in legacy schema
for output in interaction.outputs:
    if output.type == "google_search_call":
        print(f"Searched for: {output.arguments.queries}")
    elif output.type == "google_search_result":
        print(f"Found results: {output.result.rendered_content}")

JavaScript

// Accessing search results in legacy schema
for (const output of interaction.outputs) {
    if (output.type === 'google_search_call') {
        console.log(`Searched for: {output.arguments.queries}`);
    } else if (output.type === 'google_search_result') {
        console.log(`Found results: {output.result.renderedContent}`);
    }
}

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Who won the last Super Bowl?",
    "tools": [
      { "type": "google_search" }
    ]
  }'
// Response
{
  "id": "int_456",
  "outputs": [
    {
      "type": "google_search_call",
      "id": "gs_1",
      "arguments": { "queries": ["last Super Bowl winner"] }
    },
    {
      "type": "google_search_result",
      "call_id": "gs_1",
      "result": {
        "rendered_content": "<div>...</div>",
        "url": "https://www.nfl.com/super-bowl"
      }
    },
    {
      "type": "text",
      "text": "The Kansas City Chiefs won the last Super Bowl.",
      "annotations": [
        {
          "start_index": 4,
          "end_index": 22,
          "source": "https://www.nfl.com/super-bowl"
        }
      ]
    }
  ],
  "status": "completed"
}

После (новой схемы)

Python

# Accessing search results in new steps schema
for step in interaction.steps:
    if step.type == "google_search_call":
        print(f"Searched for: {step.arguments.queries}")
    elif step.type == "google_search_result":
        print(f"Found results: {step.result.search_suggestions}")

JavaScript

// Accessing search results in new steps schema
for (const step of interaction.steps) {
    if (step.type === 'google_search_call') {
        console.log(`Searched for: {step.arguments.queries}`);
    } else if (step.type === 'google_search_result') {
        console.log(`Found results: {step.result.searchSuggestions}`);
    }
}

ОТДЫХ

# Opt-in needed before May 26th
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Who won the last Super Bowl?",
    "tools": [
      { "type": "google_search" }
    ]
  }'
// POST Response
{
  "id": "int_456",
  "steps": [
    {
      "type": "google_search_call",
      "id": "gs_1",
      "arguments": { "queries": ["last Super Bowl winner"] },
      "signature": "abc123..."
    },
    {
      "type": "google_search_result",
      "call_id": "gs_1",
      "result": {
        "search_suggestions": "<div>...</div>"
      },
      "signature": "abc123..."
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "The Kansas City Chiefs won the last Super Bowl.",
          "annotations": [
            {
              "type": "url_citation",
              "url": "https://www.nfl.com/super-bowl",
              "title": "NFL.com",
              "start_index": 4,
              "end_index": 22
            }
          ]
        }
      ]
    }
  ],
  "status": "completed"
}

Стриминг

Потоковая передача данных открывает доступ к новым типам событий:

Новые типы событий

  • interaction.created
  • interaction.completed
  • interaction.in_progress
  • interaction.requires_action
  • interaction.error
  • step.start
  • step.delta
  • step.stop

Устаревшие типы событий

Следующие устаревшие типы событий заменены новыми событиями, перечисленными выше:

  • interaction.startinteraction.created
  • content.startstep.start
  • content.deltastep.delta
  • content.stopstep.stop
  • interaction.completeinteraction.completed
  • errorinteraction.error
  • interaction.status_update → заменяется на interaction.in_progress , interaction.requires_action и т. д.

Потоковая передача вызовов функций : При использовании потоковой передачи при вызове функции событие step.start передает имя функции, а события step.delta передают аргументы в виде частичных JSON-строк (с помощью arguments_delta ). Необходимо накапливать эти дельты, чтобы получить полные аргументы. Это отличается от унарных вызовов, где вы получаете полный объект вызова функции сразу.

Примеры

До (наследие)

Python

# Legacy streaming used content.delta
stream = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Explain quantum entanglement in simple terms.",
    stream=True,
)

for chunk in stream:
    if chunk.event_type == "content.delta":
        if chunk.delta.type == "text":
            print(chunk.delta.text, end="", flush=True)

JavaScript

// Legacy streaming used content.delta
const stream = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Explain quantum entanglement in simple terms.',
    stream: true,
});

for await (const chunk of stream) {
    if (chunk.event_type === 'content.delta') {
        if (chunk.delta.type === 'text') {
            process.stdout.write(chunk.delta.text);
        }
    }
}

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Explain quantum entanglement in simple terms.",
    "stream": true
  }'
// Response (SSE Lines)
// event: interaction.start
// data: {"id": "int_123", "status": "in_progress"}
//
// event: content.start
// data: {"index": 0, "type": "text"}
//
// event: content.delta
// data: {"delta": {"type": "text", "text": "Quantum entanglement is..."}}
//
// event: content.stop
// data: {"index": 0}
//
// event: interaction.complete
// data: {"id": "int_123", "status": "done", "usage": {"total_tokens": 42}}
После (новой схемы)

Python

# Consuming stream and handling new event types
for event in client.interactions.create(
    model="gemini-3-flash-preview",
    input="Tell me a story.",
    stream=True,
):
    if event.type == "step.delta":  # CHANGED: step.delta instead of content.delta
        if event.delta.type == "text":
            print(event.delta.text, end="")

JavaScript

// Consuming stream and handling new event types
const stream = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Tell me a story.',
    stream: true,
});

for await (const event of stream) {
    if (event.type === 'step.delta') {  // CHANGED: step.delta instead of content.delta
        if (event.delta.type === 'text') {
            process.stdout.write(event.delta.text);
        }
    }
}

ОТДЫХ

 # Opt-in needed before May 26th
 curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
   -H "Content-Type: application/json" \
   -H "Accept: text/event-stream" \
   -H "Api-Revision: 2026-05-20" \
   -d '{
     "model": "gemini-3-flash-preview",
     "input": "Tell me a story.",
     "stream": true
   }'
 // Response (SSE Lines)
 // event: interaction.created
 // data: {"interaction": {"id": "int_xyz", "status": "in_progress", "object": "interaction", "model": "gemini-3-flash-preview"}, "event_type": "interaction.created"}
 //
 // event: interaction.in_progress
 // data: {"interaction_id": "int_xyz", "event_type": "interaction.in_progress"}
 //
 // event: step.start
 // data: {"index": 0, "step": {"type": "thought", "signature": "abc123..."}, "event_type": "step.start"}
 //
 // event: step.stop
 // data: {"index": 0, "event_type": "step.stop"}
 //
 // event: step.start
 // data: {"index": 1, "step": {"content": [{"text": "Once upon", "type": "text"}], "type": "model_output"}, "event_type": "step.start"}
 //
 // event: step.delta
 // data: {"index": 1, "delta": {"text": " a time...", "type": "text"}, "event_type": "step.delta"}
 //
 // event: step.stop
 // data: {"type": "step.stop", "index": 1, "status": "done"}
 //
 // event: interaction.completed
 // data: {"type": "interaction.completed", "interaction": {"id": "int_xyz", "status": "completed", "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}} // NEW: Dedicated completion event

История разговоров без гражданства

Если вы управляете историей переписки вручную на стороне клиента (сценарий использования без сохранения состояния), вам необходимо обновить способ связывания предыдущих ходов.

  • Устаревшая практика : Разработчики часто собирали массив outputs из ответов и отправляли его обратно в поле input на следующем ходу.
  • Новая схема : Теперь вам следует получить массив steps из ответа и передать его в поле input следующего запроса, добавив новый ход пользователя в качестве шага user_input .

Настройка формата вывода: изменения response_format

Обновленный API объединяет все элементы управления форматом вывода в единое полиморфное поле response_format . Это централизует конфигурацию вывода на верхнем уровне и позволяет generation_config сосредоточиться на поведении модели (например, температуре, top_p и процессе мышления).

Ключевые изменения

  • API удаляет response_mime_type . Теперь вы можете указывать MIME-тип для каждой записи формата внутри response_format .
  • response_format теперь является полиморфным объектом (или массивом). Каждая запись имеет дискриминатор type ( text , audio , image ) и поля, специфичные для типа. Для запроса нескольких вариантов вывода передайте массив записей формата.
  • image_config перемещен из generation_config в response_format . Теперь параметры вывода изображения, такие как aspect_ratio и image_size указываются в записи response_format с помощью параметра "type": "image" .

Структурированный вывод (JSON)

В новой схеме поле response_mime_type удалено. Вместо этого тип MIME и схема JSON указываются внутри объекта response_format с помощью "type": "text" .

До (наследие)

Python

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Summarize this article.",
    response_mime_type="application/json",
    response_format={
        "type": "object",
        "properties": {
            "summary": {"type": "string"}
        }
    },
)

print(interaction.outputs[-1].text)

JavaScript

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Summarize this article.',
    responseMimeType: 'application/json',
    responseFormat: {
        type: 'object',
        properties: {
            summary: { type: 'string' }
        }
    },
});

console.log(interaction.outputs[-1].text);

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Summarize this article.",
    "response_mime_type": "application/json",
    "response_format": {
      "type": "object",
      "properties": {
        "summary": { "type": "string" }
      }
    }
  }'

После (новой схемы)

Python

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Summarize this article.",
    # response_mime_type is removed — specify mime_type inside response_format
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": {
            "type": "object",
            "properties": {
                "summary": {"type": "string"}
            }
        }
    },
)

print(interaction.steps[-1].content[0].text)

JavaScript

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Summarize this article.',
    // responseMimeType is removed — specify mimeType inside responseFormat
    responseFormat: {
        type: 'text',
        mimeType: 'application/json',
        schema: {
            type: 'object',
            properties: {
                summary: { type: 'string' }
            }
        }
    },
});

console.log(interaction.steps.at(-1).content[0].text);

ОТДЫХ

# Opt-in needed before May 26th
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Summarize this article.",
    "response_format": {
      "type": "text",
      "mime_type": "application/json",
      "schema": {
        "type": "object",
        "properties": {
          "summary": { "type": "string" }
        }
      }
    }
  }'

Конфигурация изображения

Новая схема удаляет image_config из generation_config . Теперь параметры вывода изображения указываются в записи response_format с помощью "type": "image" .

До (наследие)

Python

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Generate an image of a sunset over the ocean.",
    generation_config={
        "image_config": {
            "aspect_ratio": "1:1",
            "image_size": "1K"
        }
    },
)

JavaScript

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Generate an image of a sunset over the ocean.',
    generationConfig: {
        imageConfig: {
            aspectRatio: '1:1',
            imageSize: '1K'
        }
    },
});

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Generate an image of a sunset over the ocean.",
    "generation_config": {
      "image_config": {
        "aspect_ratio": "1:1",
        "image_size": "1K"
      }
    }
  }'

После (новой схемы)

Python

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Generate an image of a sunset over the ocean.",
    # image_config is removed from generation_config — use response_format
    response_format={
        "type": "image",
        "mime_type": "image/jpeg",
        "delivery": "inline",
        "aspect_ratio": "1:1",
        "image_size": "1K"
    },
)

JavaScript

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Generate an image of a sunset over the ocean.',
    // imageConfig is removed from generationConfig — use responseFormat
    responseFormat: {
        type: 'image',
        mimeType: 'image/jpeg',
        delivery: 'inline',
        aspectRatio: '1:1',
        imageSize: '1K'
    },
});

ОТДЫХ

# Opt-in needed before May 26th
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Generate an image of a sunset over the ocean.",
    "response_format": {
      "type": "image",
      "mime_type": "image/jpeg",
      "delivery": "inline",
      "aspect_ratio": "1:1",
      "image_size": "1K"
    }
  }'

Чтобы запросить несколько вариантов вывода (например, текст и аудио одновременно), передайте массив записей формата в функцию response_format вместо одного объекта.

Как выполнить миграцию на новую схему

пользователи SDK

Обновите SDK до последней версии (Python ≥2.0.0, JavaScript ≥2.0.0). SDK автоматически переключится на новую схему — никаких изменений в коде не потребуется, кроме обновления способа чтения ответов (см. примеры выше). Обратите внимание, что в этих версиях SDK поддерживается только новая схема. Более старые версии SDK (Python 1.xx, JavaScript 1.xx) будут продолжать работать до удаления устаревшей схемы 8 июня 2026 года .

Пользователи REST API

Добавьте заголовок Api-Revision: 2026-05-20 к своим запросам, чтобы подключиться к новой схеме. После 26 мая новая схема станет схемой по умолчанию для всех запросов. Вы можете временно отключить её, добавив заголовок Api-Revision: 2026-05-07 до 8 июня , когда API навсегда удалит устаревшую схему.

Хронология

Дата Фаза пользователи SDK Пользователи REST API
7 мая Согласие на участие Доступна новая версия SDK (Python ≥2.0.0, JS ≥2.0.0). Обновите версию, чтобы автоматически получить новую схему. Добавьте заголовок Api-Revision: 2026-05-20 для включения этой функции. По умолчанию используется устаревшая версия.
26 мая Переворот по умолчанию Если обновление уже выполнено, никаких действий не требуется. Более старые SDK (Python 1.xx, JS 1.xx) по-прежнему работают, но возвращают устаревшие ответы. Новая схема теперь используется по умолчанию. Чтобы отказаться от её использования, отправьте заголовок Api-Revision: 2026-05-07 .
8 июня Закат В версиях SDK Python 1.xx и JS 1.xx вызовы API взаимодействия будут некорректными. Устаревшая схема удалена для API взаимодействий. Заголовок Api-Revision игнорируется.

Контрольный список миграции

Схема шагов ( steps )

  • Обновите код, чтобы он считывал содержимое ответа из массива steps , а не из outputs . См. примеры .
  • Убедитесь, что ваш код обрабатывает как ввод user_input , так и вывод model_output . См. примеры .
  • (Вызов функции) Обновите код, чтобы находить шаги function_call в массиве steps . См. примеры .
  • (Серверные инструменты) Обновите код для обработки шагов, специфичных для конкретного инструмента (например, google_search_call , google_search_result ). См. примеры .
  • (История без сохранения состояния) Обновите управление историей, чтобы передавать массив steps в поле input следующего запроса. Подробнее см . здесь.
  • (Только потоковая передача) Обновите клиент, чтобы он отслеживал новые типы событий SSE ( interaction.created , step.delta и т. д.). См. примеры .

Настройка формата вывода ( response_format )

  • Замените response_mime_type на поле mime_type внутри response_format . См. примеры .
  • Оберните существующую JSON-схему response_format в объект {"type": "text", "schema": ...} . См. примеры .
  • (Генерация изображений) Переместите image_config из generation_config в запись {"type": "image", ...} в response_format . См. примеры .
  • (Мультимодальный) Преобразовывать response_format из одного объекта в массив при запросе нескольких вариантов вывода.