В v1beta Interactions API вносятся критические изменения, которые меняют структуру API, чтобы обеспечить поддержку будущих возможностей, таких как управление в процессе выполнения и асинхронные вызовы инструментов. На этой странице рассказывается о том, что изменится, и приводятся примеры кода до и после изменений, которые помогут вам перейти на новую версию. Изменения делятся на две категории:
- Схема шагов:
Новый массив
stepsзаменяет массивoutputsи предоставляет структурированную временную шкалу каждого взаимодействия. - Настройка формата вывода. Новый полиморфный элемент
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.8-flash", input="Tell me a joke."
)
# Response access
print(interaction.outputs[-1].text)
JavaScript
// Request
const interaction = await client.interactions.create({
model: 'gemini-3.8-flash',
input: 'Tell me a joke.'
});
// Response access
console.log(interaction.outputs[-1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"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.8-flash", input="Tell me a joke."
)
# Response access (Recommended sugar)
print(interaction.output_text)
JavaScript
// Request
const interaction = await client.interactions.create({
model: 'gemini-3.8-flash',
input: 'Tell me a joke.'
});
// Response access (Recommended sugar)
console.log(interaction.output_text);
[sdk-convenience]: /gemini-api/docs/interactions-overview#sdk-sugar
REST
# 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.8-flash",
"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)}`);
}
}
REST
// 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)}`);
}
}
REST
// 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}`);
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"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[0].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[0].search_suggestions}`);
}
}
REST
# 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.8-flash",
"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.createdinteraction.completedinteraction.in_progressinteraction.requires_actionstep.startstep.deltastep.stop
Устаревшие типы событий
Перечисленные выше новые события заменяют следующие устаревшие типы событий:
interaction.start→interaction.createdcontent.start→step.startcontent.delta→step.deltacontent.stop→step.stopinteraction.complete→interaction.completedinteraction.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.8-flash",
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.8-flash',
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);
}
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"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.8-flash",
input="Tell me a story.",
stream=True,
):
if event.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.8-flash',
input: 'Tell me a story.',
stream: true,
});
for await (const event of stream) {
if (event.event_type === 'step.delta') { // CHANGED: step.delta instead of content.delta
if (event.delta.type === 'text') {
process.stdout.write(event.delta.text);
}
}
}
REST
# 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.8-flash",
"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.8-flash"}, "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
История чатов без отслеживания состояния
Если вы управляете историей чата вручную на стороне клиента (используете stateless-подход), вам нужно изменить способ объединения предыдущих сообщений.
- Устаревшая версия. Разработчики часто собирали массив
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.8-flash",
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.8-flash',
input: 'Summarize this article.',
response_mime_type: 'application/json',
response_format: {
type: 'object',
properties: {
summary: { type: 'string' }
}
},
});
console.log(interaction.outputs[-1].text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"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.8-flash",
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 response
print(interaction.output_text)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3.8-flash',
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 response
console.log(interaction.output_text);
REST
# 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.8-flash",
"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.8-flash",
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.8-flash',
input: 'Generate an image of a sunset over the ocean.',
generation_config: {
image_config: {
aspect_ratio: '1:1',
image_size: '1K'
}
},
});
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"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.8-flash",
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",
"aspect_ratio": "1:1",
"image_size": "1K"
},
)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3.8-flash',
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',
aspect_ratio: '1:1',
image_size: '1K'
},
});
REST
# 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.8-flash",
"input": "Generate an image of a sunset over the ocean.",
"response_format": {
"type": "image",
"mime_type": "image/jpeg",
"aspect_ratio": "1:1",
"image_size": "1K"
}
}'
Конфигурация аудио
В новой схеме response_modalities: ["audio"] заменяется на запись response_format со значением "type": "audio".
До (устаревшая версия)
Python
interaction = client.interactions.create(
model="gemini-3.1-flash-tts-preview",
input="Say cheerfully: Have a wonderful day!",
response_modalities=["audio"],
generation_config={
"speech_config": [
{"voice": "Kore"}
]
}
)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3.1-flash-tts-preview',
input: 'Say cheerfully: Have a wonderful day!',
response_modalities: ['audio'],
generation_config: {
speech_config: [
{ voice: 'Kore' }
]
},
});
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?key=$GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.1-flash-tts-preview",
"input": "Say cheerfully: Have a wonderful day!",
"response_modalities": ["audio"],
"generation_config": {
"speech_config": [
{ "voice": "Kore" }
]
}
}'
После (новая схема)
Python
interaction = client.interactions.create(
model="gemini-3.1-flash-tts-preview",
input="Say cheerfully: Have a wonderful day!",
# response_modalities is removed — use response_format
response_format={
"type": "audio"
},
generation_config={
"speech_config": [
{"voice": "Kore"}
]
}
)
JavaScript
const interaction = await client.interactions.create({
model: 'gemini-3.1-flash-tts-preview',
input: 'Say cheerfully: Have a wonderful day!',
// response_modalities is removed — use response_format
response_format: {
type: 'audio'
},
generation_config: {
speech_config: [
{ voice: 'Kore' }
]
},
});
REST
# 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.1-flash-tts-preview",
"input": "Say cheerfully: Have a wonderful day!",
"response_format": {
"type": "audio"
},
"generation_config": {
"speech_config": [
{ "voice": "Kore" }
]
}
}'
Чтобы запросить несколько способов вывода (например, текст и аудио), передайте в response_format массив записей формата вместо одного объекта.
Как перейти на новую схему
Пользователи SDK
Перейдите на последнюю версию SDK (Python ≥2.0.0, JavaScript ≥2.0.0). SDK автоматически переводит вас на новую схему. Вам не нужно менять код, кроме того, как вы читаете ответы (см. примеры выше). Обратите внимание, что в этих версиях SDK поддерживается только новая схема. Более старые версии SDK (Python 1.x.x, JavaScript 1.x.x) будут работать до удаления устаревшей схемы 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.x.x, JS 1.x.x) по-прежнему работают, но возвращают устаревшие ответы. | Новая схема теперь используется по умолчанию. Чтобы отказаться от этого, отправьте заголовок Api-Revision: 2026-05-07. |
| 8 июня | Закат | Версии Python 1.x.x и JS 1.x.x SDK перестанут работать для вызовов Interactions API. | Удалена устаревшая схема для API взаимодействий. Заголовок Api-Revision проигнорирован. |
На что следует обратить внимание при переносе
Схема Steps (steps)
- Обновите код, чтобы считывать контент ответа из массива
steps, а неoutputs. Показать примеры - Убедитесь, что ваш код обрабатывает оба типа шагов:
user_inputиmodel_output. Показать примеры - (Вызов функций) Обновите код, чтобы найти шаги
function_callв массивеsteps. Показать примеры - (Инструменты на стороне сервера) Обновите код, чтобы он выполнял шаги, необходимые для работы с определенным инструментом (например,
google_search_call,google_search_result). Посмотреть примеры. - (Stateless History) Обновите управление историей, чтобы передавать массив
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_modalities=["audio"]записью{"type": "audio"}вresponse_format. Примеры - (Мультимодальный) Преобразуйте
response_formatиз одного объекта в массив при запросе нескольких модальностей вывода.