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

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

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

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

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

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

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

Унарные (не потоковые) ответы повторяют ваши входные данные в качестве первого шага в массиве steps . Потоковые ответы пропускают шаг ввода и передают только изменения сгенерированного контента.

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

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

Python

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

# Response access
print(interaction.outputs[0].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[0].text);

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "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);

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "model": "gemini-3-flash-preview",
  "input": "Tell me a joke."
}

// Response
{
  "id": "int_123",
  "steps": [
    {
      "type": "user_input",
      "status": "done",
      "content": [
        {
          "type": "text",
          "text": "Tell me a joke."
        }
      ]
    },
    {
      "type": "model_output",
      "status": "done",
      "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)}`);
    }
}

ОТДЫХ

// Response
{
  "id": "int_001",
  "status": "requires_action",
  "steps": [
    {
      "type": "user_input",
      "status": "done",
      "content": [
        { "type": "text", "text": "What's the weather in Boston?" }
      ]
    },
    {
      "type": "thought",
      "status": "done",
      "signature": "abc123..."
    },
    {
      "type": "function_call",
      "status": "waiting",
      "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}`);
    }
}

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "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}`);
    }
}

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "model": "gemini-3-flash-preview",
  "input": "Who won the last Super Bowl?",
  "tools": [
    { "type": "google_search" }
  ]
}

// Response
{
  "id": "int_456",
  "steps": [
    {
      "type": "user_input",
      "status": "done",
      "content": [
        { "type": "text", "text": "Who won the last Super Bowl?" }
      ]
    },
    {
      "type": "google_search_call",
      "status": "done",
      "id": "gs_1",
      "arguments": { "queries": ["last Super Bowl winner"] },
      "signature": "abc123..."
    },
    {
      "type": "google_search_result",
      "status": "done",
      "call_id": "gs_1",
      "result": {
        "search_suggestions": "<div>...</div>"
      },
      "signature": "abc123..."
    },
    {
      "type": "model_output",
      "status": "done",
      "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.status_update — теперь охватывает все состояния жизненного цикла, включая завершение и ошибки (см. статусы ниже).
  • step.start
  • step.delta
  • step.stop
interaction.status_update statuses
  • in_progress
  • active
  • completed
  • interrupted
  • requires_action
  • error

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

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

  • interaction.startinteraction.created
  • content.startstep.start
  • content.deltastep.delta
  • content.stopstep.stop
  • interaction.completeinteraction.status_update со status: "completed"
  • errorinteraction.status_update со status: "error"
  • interaction.status_updateinteraction.status_update (без изменений, но теперь охватывает дополнительные состояния)

Потоковая передача вызовов функций : При использовании потоковой передачи при вызове функции событие 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);
        }
    }
}

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "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);
        }
    }
}

ОТДЫХ

 // Request: POST /v1beta/interactions
 // Accept: text/event-stream
 {
   "model": "gemini-3-flash-preview",
   "input": "Tell me a story."
 }

 // Response (SSE Lines)
 // event: interaction.created
 // data: {"type": "interaction.created", "interaction": {"id": "int_xyz", "status": "created"}} // CHANGED: 'type' instead of 'event_type'
 //
 // event: interaction.status_update
 // data: {"type": "interaction.status_update", "status": "in_progress"} // NEW: Lifecycle status updates in stream (postpone until Sessions launch dependency)
 //
 // event: step.start
 // data: {"type": "step.start", "index": 0, "step": {"type": "thought"}} // NEW: Replaces content.start, 'step' instead of 'content'
 //
 // event: step.delta
 // data: {"type": "step.delta", "index": 0, "delta": {"type": "thought", "text": "User wants an explanation."}} // NEW: Delta type matches step type
 //
 // event: step.stop
 // data: {"type": "step.stop", "index": 0, "status": "done"} // NEW: Includes status
 //
 // event: step.start
 // data: {"type": "step.start", "index": 1, "step": {"type": "model_output"}} // NEW: Step wrapper for output
 //
 // event: step.delta
 // data: {"type": "step.delta", "index": 1, "delta": {"type": "text", "text": "Hello"}}
 //
 // event: step.stop
 // data: {"type": "step.stop", "index": 1, "status": "done"}
 //
 // event: interaction.complete
 // data: {"type": "interaction.complete", "interaction": {"id": "int_xyz", "status": "completed", "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}} // NEW: End of stream event with interaction details

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

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

  • Устаревший подход : Разработчики часто собирали массив 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[0].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[0].text);

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "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);

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "model": "gemini-3-flash-preview",
  "input": "Summarize this article.",
  // response_mime_type is removed
  "response_format": {
    "type": "text",                          // NEW: type discriminator
    "mime_type": "application/json",          // MOVED: from response_mime_type
    "schema": {                              // RENAMED: was response_format directly
      "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'
        }
    },
});

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "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'
    },
});

ОТДЫХ

// Request: POST /v1beta/interactions
{
  "model": "gemini-3-flash-preview",
  "input": "Generate an image of a sunset over the ocean.",
  // image_config removed from generation_config
  "response_format": {
    "type": "image",                         // NEW: type discriminator
    "mime_type": "image/jpeg",
    "delivery": "inline",
    "aspect_ratio": "1:1",                   // MOVED: from generation_config.image_config
    "image_size": "1K"                       // MOVED: from generation_config.image_config
  }
}

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

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

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

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

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

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

Хронология

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