Guía para desarrolladores de la API de Interactions

La API de Interactions proporciona una interfaz unificada y con estado para crear aplicaciones de IA generativa con modelos de Gemini y agentes autónomos en Gemini Enterprise Agent Platform. Usa la API de Interactions para ejecutar conversaciones de varios turnos, transmitir respuestas en tiempo real, aplicar resultados estructurados, ejecutar llamadas a funciones y coordinar tareas en segundo plano de larga duración.

En esta guía, se muestra cómo instalar el SDK de IA generativa de Google, autenticar tu cliente y, luego, implementar flujos de trabajo de interacción comunes. Para obtener detalles conceptuales sobre el ciclo de vida de la interacción, consulta la descripción general de la API de Interactions.

Antes de comenzar

Antes de enviar solicitudes a la API de Interactions, configura tu proyecto Google Cloudy tu entorno de desarrollo:

  1. Accede a tu cuenta de Google Cloud . Si es la primera vez que usas Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  5. Make sure that you have the following role or roles on the project: Agent Platform User (roles/aiplatform.user)

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. Click Grant access.
    4. In the New principals field, enter your user identifier. This is typically the email address for a Google Account.

    5. Click Select a role, then search for the role.
    6. To grant additional roles, click Add another role and add each additional role.
    7. Click Save.
  6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  7. Verify that billing is enabled for your Google Cloud project.

  8. Enable the Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  9. Make sure that you have the following role or roles on the project: Agent Platform User (roles/aiplatform.user)

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. Click Grant access.
    4. In the New principals field, enter your user identifier. This is typically the email address for a Google Account.

    5. Click Select a role, then search for the role.
    6. To grant additional roles, click Add another role and add each additional role.
    7. Click Save.

Conceptos clave

Revisa los siguientes conceptos para comprender cómo la API de Interactions administra el estado y las respuestas:

  • Interaction: La API de Interactions se centra en un recurso principal: un Interaction. Un Interaction representa un turno completo en una conversación o tarea, y hace un seguimiento de la cronología de las reflexiones del modelo, las llamadas a herramientas y los resultados finales. Proporciona un sobre unificado para las interacciones de solicitud-respuesta y los flujos de trabajo complejos de varios pasos del agente.
  • Retención con estado: Las interacciones se almacenan de forma predeterminada en el servidor (store=True en Python o store: true en TypeScript/JavaScript). Las interacciones almacenadas persisten durante 7 días y se borran automáticamente después de ese tiempo. El parámetro de configuración store=False habilita el modo sin estado, que inhabilita la retención del servidor y cumple con la retención de datos cero (ZDR). El modo sin estado también inhabilita el encadenamiento de previous_interaction_id y la ejecución asíncrona (background=True).
  • Ayudantes de respuesta: La versión 2.3.0 y las posteriores del SDK de IA generativa de Google proporcionan propiedades convenientes en la respuesta de interacción, incluidas interaction.output_text, interaction.output_image y interaction.output_audio. Usa interaction.output_text para leer respuestas de texto en lugar de indexar manualmente el array de pasos (como interaction.steps[-1].content[0].text).

Requisitos

Antes de integrar la API de Interactions, asegúrate de que tu entorno y tus solicitudes cumplan con los siguientes requisitos:

  • Compatibilidad con versiones del SDK: Usa el SDK unificado de IA generativa de Google (>= 2.3.0 para Python o @google/genai >= 2.3.0 para TypeScript y JavaScript).

    • Se requiere la versión 2.3.0 o posterior para las propiedades de ayuda de respuesta y las capacidades del agente, mientras que la versión 2.0.0 admite el esquema steps básico.
    • Los SDKs heredados (google-cloud-aiplatform, @google-cloud/vertexai y google-generativeai) no admiten la API de Interactions.
  • Modelos admitidos: Usa modelos de Gemini 3 o versiones posteriores admitidos. Las familias de modelos anteriores no admiten esta API. Para obtener una lista completa de los modelos compatibles, consulta Modelos compatibles y Migra a las versiones de modelos más recientes.

  • Parámetros específicos del turno: Los parámetros de configuración, como tools, system_instruction y generation_config, solo se aplican al turno actual. Pasa estos parámetros en cada turno de interacción posterior si tu flujo de trabajo los requiere en una conversación de varios turnos.

Instala el SDK de IA generativa de Google

Instala o actualiza el SDK de IA generativa de Google (>= 2.3.0) para tu lenguaje preferido:

Python

pip install --upgrade "google-genai>=2.3.0"

TypeScript / JavaScript

npm install "@google/genai>=2.3.0"

Autentica tu cliente

Puedes conectarte a la API de Interactions en Agent Platform con cualquiera de los siguientes métodos de autenticación:

Conéctate con un proyecto de Google Cloud con credenciales predeterminadas de la aplicación (ADC)

Recomendamos usar este método de autenticación para las cargas de trabajo empresariales y las implementaciones de producción en Google Cloud. Para autenticarte con las credenciales predeterminadas de la aplicación (ADC), inicializa el cliente con las siguientes propiedades:

  • enterprise=True
  • project= Google Cloud project ID
  • location="global"

Si aún no configuraste credenciales locales, ejecuta gcloud auth application-default login.

En la siguiente muestra de código, reemplaza PROJECT_ID por el ID del proyecto deGoogle Cloud .

Python

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Explain serverless computing in one sentence.",
)

print(interaction.output_text)

TypeScript / JavaScript

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

const ai = new GoogleGenAI({
    enterprise: true,
    project: "PROJECT_ID",
    location: "global",
});

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Explain serverless computing in one sentence.",
});

console.log(interaction.output_text);

REST

curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [{
      "role": "user",
      "content": [{
        "type": "text",
        "text": "Explain serverless computing in one sentence."
      }]
    }]
  }'

Conéctate con el modo exprés (clave de API)

Recomendamos usar este método de autenticación para la creación rápida de prototipos, los secuencias de comandos ligeros o los entornos que se autentican con una clave de API. Pasa tu clave de API cuando inicialices el cliente o en el encabezado HTTP x-goog-api-key.

En la siguiente muestra de código, reemplaza API_KEY por tu clave de API.

Python

from google import genai

client = genai.Client(
    enterprise=True,
    api_key="API_KEY",
)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Explain serverless computing in one sentence.",
)

print(interaction.output_text)

TypeScript / JavaScript

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

const ai = new GoogleGenAI({
    enterprise: true,
    apiKey: "API_KEY",
});

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Explain serverless computing in one sentence.",
});

console.log(interaction.output_text);

REST

curl -X POST "https://aiplatform.googleapis.com/v1beta1/locations/global/interactions" \
  -H "x-goog-api-key: API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [{
      "role": "user",
      "content": [{
        "type": "text",
        "text": "Explain serverless computing in one sentence."
      }]
    }]
  }'

Flujos de trabajo de interacción comunes

Después de configurar tu cliente, puedes usar el método interactions.create para crear conversaciones de varios turnos, transmitir tokens de salida en tiempo real, generar JSON validados por esquema, llamar a funciones externas y ejecutar agentes autónomos.

Administra conversaciones de varios turnos con estado

A diferencia de las APIs de chat sin estado que requieren que vuelvas a enviar el historial de mensajes completo con cada solicitud, la API de Interactions administra el estado de la conversación en el servidor de forma predeterminada (store=True en Python o store: true en TypeScript/JavaScript).

Para continuar una conversación existente, pasa el id de la interacción anterior al parámetro previous_interaction_id. La Agent Platform recupera automáticamente el contexto de la conversación almacenado y agrega el nuevo turno. Si configuras store=False (store: false en TypeScript/JavaScript), se inhabilitará la persistencia del servidor y no podrás encadenar turnos posteriores con previous_interaction_id.

Python

# Turn 1: Start a conversation (store=True by default)
turn1 = client.interactions.create(
    model="gemini-3.8-flash",
    input="Hi! My name is John. I am working on AI agents.",
    store=True,
)
print(f"Turn 1: {turn1.output_text}")

# Turn 2: Reference the stored conversation state using previous_interaction_id
turn2 = client.interactions.create(
    model="gemini-3.8-flash",
    input="What is my name?",
    previous_interaction_id=turn1.id,
)
print(f"Turn 2: {turn2.output_text}")

TypeScript / JavaScript

// Turn 1: Start a conversation (store: true by default)
const turn1 = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Hi! My name is John. I am working on AI agents.",
    store: true,
});
console.log(`Turn 1: ${turn1.output_text}`);

// Turn 2: Reference the stored conversation state using previous_interaction_id
const turn2 = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "What is my name?",
    previous_interaction_id: turn1.id,
});
console.log(`Turn 2: ${turn2.output_text}`);

Transmite respuestas en tiempo real

Para reducir la latencia percibida en las aplicaciones interactivas, puedes transmitir las respuestas del modelo a medida que se generan. Establece stream=True (stream: true en TypeScript/JavaScript) cuando llames a interactions.create para recibir un flujo iterable de eventos enviados por el servidor. Filtra los eventos de step.delta para renderizar fragmentos de texto incrementales a medida que llegan:

Python

response = client.interactions.create(
    model="gemini-3.8-flash",
    input="Write a short poem about debugging.",
    stream=True,
)

for event in response:
    if event.event_type == "step.delta" and hasattr(event.delta, "text"):
        print(event.delta.text, end="", flush=True)
print()

TypeScript / JavaScript

const responseStream = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Write a short poem about debugging.",
    stream: true,
});

for await (const event of responseStream) {
    if (event.event_type === "step.delta" && event.delta && "text" in event.delta) {
        process.stdout.write(event.delta.text);
    }
}
console.log();

Genera resultados estructurados

Cuando tu aplicación requiere respuestas en un formato predecible y legible por máquina, puedes restringir el resultado del modelo para que coincida con un esquema JSON específico. Pasa tu esquema de destino, como un esquema JSON del modelo de Pydantic en Python o un objeto de esquema Type en TypeScript/JavaScript, directamente al parámetro polimórfico response_format:

Python

from pydantic import BaseModel, Field

class Book(BaseModel):
    title: str = Field(description="The title of the book")
    author: str = Field(description="The book's author")
    year_published: int

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Recommend one famous sci-fi book.",
    response_format=Book.model_json_schema(),
)

# The output text is valid JSON matching the Book schema
print(interaction.output_text)

TypeScript / JavaScript

import { Type } from "@google/genai";

const BookSchema = {
    type: Type.OBJECT,
    properties: {
        title: { type: Type.STRING, description: "The title of the book" },
        author: { type: Type.STRING, description: "The book's author" },
        yearPublished: { type: Type.INTEGER },
    },
    required: ["title", "author", "yearPublished"],
};

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Recommend one famous sci-fi book.",
    response_format: BookSchema,
});

console.log(interaction.output_text);

Usar llamadas a funciones (uso de herramientas)

La llamada a funciones permite que un modelo solicite la ejecución de funciones personalizadas o APIs externas para recopilar información antes de formular una respuesta final. En un flujo de trabajo de interacción con estado, la llamada a función sigue un patrón de dos turnos:

  1. Declara y pasa herramientas: Proporciona tus declaraciones de funciones en el parámetro tools de la solicitud inicial.
  2. Ejecuta y devuelve resultados: Inspecciona los pasos de respuesta (interaction.steps) para los pasos function_call, ejecuta tu función local con el arguments proporcionado por el modelo y envía una interacción de seguimiento que contenga un elemento function_result vinculado por call_id y previous_interaction_id.

Python

# Define a declarative function tool schema
stock_tool = {
    "type": "function",
    "name": "get_stock_price",
    "description": "Gets the stock price for a given ticker symbol.",
    "parameters": {
        "type": "object",
        "properties": {
            "ticker": {"type": "string", "description": "The stock ticker symbol"}
        },
        "required": ["ticker"],
    },
}

def get_stock_price(ticker: str) -> float:
    """Executes the local tool function."""
    if ticker.upper() == "GOOG":
        return 175.50
    return 100.0

# Turn 1: Pass the tool declaration to the model
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="What is the stock price of GOOG?",
    tools=[stock_tool],
)

# Inspect the interaction steps for function call requests
for step in interaction.steps:
    if step.type == "function_call" and step.name == "get_stock_price":
        ticker_arg = step.arguments.get("ticker")
        price = get_stock_price(ticker_arg)

        # Turn 2: Submit the function execution result to the conversation
        final_turn = client.interactions.create(
            model="gemini-3.8-flash",
            input=[{
                "type": "function_result",
                "call_id": step.id,
                "result": {"price": price},
            }],
            previous_interaction_id=interaction.id,
        )
        print(final_turn.output_text)

TypeScript / JavaScript

// Define a declarative function tool schema
const stockTool = {
    type: "function",
    name: "getStockPrice",
    description: "Gets the stock price for a given ticker symbol.",
    parameters: {
        type: "object",
        properties: {
            ticker: { type: "string", description: "The stock ticker symbol" },
        },
        required: ["ticker"],
    },
};

function getStockPrice({ ticker }: { ticker: string }): number {
    if (ticker.toUpperCase() === "GOOG") return 175.50;
    return 100.00;
}

// Turn 1: Pass the tool declaration to the model
const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "What is the stock price of GOOG?",
    tools: [stockTool],
});

// Inspect the interaction steps for function call requests
for (const step of interaction.steps ?? []) {
    if (step.type === "function_call" && step.name === "getStockPrice") {
        const tickerArg = step.arguments.ticker as string;
        const price = getStockPrice({ ticker: tickerArg });

        // Turn 2: Submit the function execution result to the conversation
        const finalTurn = await ai.interactions.create({
            model: "gemini-3.8-flash",
            input: [{
                type: "function_result",
                call_id: step.id,
                result: { price },
            }],
            previous_interaction_id: interaction.id,
        });
        console.log(finalTurn.output_text);
    }
}

Ejecutar agentes y tareas en segundo plano de larga duración

Además de los modelos base, la API de Interactions te permite invocar agentes autónomos especializados con el parámetro agent:

  • antigravity-preview-05-2026: Es un agente administrado de uso general con ejecución de código, administración de archivos y navegación web en un entorno de Linux seguro en zona de pruebas. Para obtener más información, consulta Cómo interactuar con agentes.
  • deep-research-preview-04-2026: Agente de Deep Research de Gemini, que planifica y ejecuta tareas de investigación web de varios pasos, y sintetiza los hallazgos de múltiples fuentes en informes integrales. Para obtener más información, consulta Cómo usar el agente de Deep Research de Gemini.
  • Agentes personalizados: Son recursos de agentes personalizados configurados y aprovisionados con client.agents.create().

Dado que los flujos de trabajo de los agentes suelen tardar varios minutos en completarse, configúralos para que se ejecuten de forma asíncrona en segundo plano con background=True. La API devuelve de inmediato un objeto Interaction con un id que puedes sondear con client.interactions.get() hasta que interaction.status haga la transición a completed:

Antes de probar este ejemplo, reemplaza PROJECT_ID por el ID de tu proyecto deGoogle Cloud .

import time
from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

interaction = client.interactions.create(
    input="Analyze competitive positioning for solar energy providers.",
    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.output_text)
        break
    elif interaction.status in ("failed", "cancelled"):
        print(f"Research ended with status: {interaction.status}")
        break
    time.sleep(10)

Accede a los archivos subidos a Cloud Storage

Puedes usar la API de Interactions para acceder a los archivos subidos de Cloud Storage. Consulta el siguiente ejemplo:

from google import genai

# Credentials must belong to an identity with storage.objects.get permissions
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "text", "text": "Summarize the attached document:"},
        {
            "type": "document",
            "uri": "gs://my-secure-bucket/quarterly_report.pdf",
            "mime_type": "application/pdf"
        }
    ],
)

print(interaction.output_text)

Cuando se pasan URIs de Cloud Storage (por ejemplo, gs://bucket-name/path/to/file) a la API de Interactions, las solicitudes se evalúan con las credenciales del usuario final (EUC). La API recupera objetos de Cloud Storage con la identidad del llamador autenticado en lugar de un agente de servicio del proyecto en segundo plano.

Para pasar archivos de Cloud Storage en una solicitud de interacción, la principal que realiza la llamada (cuenta de usuario, cuenta de servicio o identidad federada) debe tener el permiso storage.objects.get para todos los objetos a los que se hace referencia.

Configura roles de IAM para acceder a archivos de Cloud Storage

Otorga uno de los roles predefinidos estándares que incluyen el permiso storage.objects.get:

  • Visualizador de objetos de Storage (roles/storage.objectViewer): Acceso de lectura a los objetos (recomendado).
  • Usuario de objetos de almacenamiento (roles/storage.objectUser): Acceso de lectura y escritura a objetos.

Para otorgar acceso a una cuenta de usuario con Google Cloud CLI, usa el siguiente comando:

gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
    --member="user:user-email@example.com" \
    --role="roles/storage.objectViewer"

Para otorgar acceso a una cuenta de servicio de llamada específica, usa el siguiente comando:

gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
    --member="serviceAccount:sa-name@PROJECT_ID.iam.gserviceaccount.com" \
    --role="roles/storage.objectViewer"

Soluciona problemas de acceso a archivos de Cloud Storage

Si la principal que realiza la llamada no tiene permisos suficientes, la API de Interactions devuelve un error 403 Forbidden similar al siguiente:

Access error:
PERMISSION_DENIED - 403 Forbidden: Calling principal lacks
storage.objects.get on one or more GCS URIs.

Para resolver este problema, otorga el rol de visualizador de objetos de Storage (roles/storage.objectViewer) en el bucket o el objeto al llamador autenticado.

Si el objeto especificado no existe o si los permisos del bucket impiden que el llamador vea si el objeto existe, la API de Interactions devuelve un error 404 Not Found similar al siguiente:

Access error:
NOT_FOUND - 404 Not Found: The object does not exist, or bucket
permissions prevent revealing object existence.

Para resolver este problema, verifica que el URI de Cloud Storage sea correcto y confirma que la entidad llamadora autenticada tenga acceso de lectura al bucket.

Flujos de trabajo de REST avanzados

Para la automatización basada en shell, las canalizaciones de CI/CD o los entornos sin un entorno de ejecución de Python o TypeScript/JavaScript, puedes llamar a la API de Interactions directamente a través de HTTP con curl.

Extremo de REST

Envía solicitudes POST al siguiente extremo de API de Interactions:

POST https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/interactions

Reemplaza las siguientes variables en tus solicitudes:

  • PROJECT_ID: Es el ID del proyecto de Google Cloud .
  • LOCATION: Se debe establecer en global (o en una región personalizada compatible si tu configuración lo requiere).

Configura variables de entorno y autenticación

Antes de ejecutar los ejemplos de curl en las siguientes secciones, exporta tu ID del proyecto, el ID del modelo o del agente de destino, y un token de acceso de OAuth 2.0 generado a partir de las credenciales predeterminadas de la aplicación:

PROJECT_ID="PROJECT_ID"
MODEL_ID="gemini-3.8-flash"
AGENT_ID="deep-research-preview-04-2026"
ACCESS_TOKEN=$(gcloud auth print-access-token)

Formato de respuesta síncrona

Una solicitud POST síncrona devuelve un objeto interaction JSON que incluye los metadatos únicos de interacción id, ejecución status, conversación steps y token usage:

{
  "id": "your-interaction-id",
  "status": "completed",
  "steps": [
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "Serverless computing is a cloud execution model where the cloud provider dynamically manages the allocation and provisioning of servers, charging customers based on actual usage rather than pre-purchased capacity."
        }
      ]
    }
  ],
  "usage": {
    "total_tokens": 24751,
    "total_input_tokens": 23894,
    "total_output_tokens": 857
  },
  "created": "2026-05-08T10:44:43Z",
  "updated": "2026-05-08T10:44:43Z",
  "environment_id": "your-environment-id",
  "object": "interaction"
}

Cómo continuar una interacción con estado de varios turnos

Para continuar una conversación almacenada a través de REST, pasa el id de una respuesta anterior en el campo previous_interaction_id del cuerpo de la solicitud JSON.

Antes de probar esta muestra, reemplaza PREVIOUS_INTERACTION_ID por el id que devolvió una interacción anterior.

curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"${MODEL_ID}"'",
    "store": true,
    "previous_interaction_id": "PREVIOUS_INTERACTION_ID",
    "input": [{
      "role": "user",
      "content": [{
        "type": "text",
        "text": "Can you elaborate on that?"
      }]
    }]
  }'

Transmite la salida con eventos enviados por el servidor

Para transmitir actualizaciones incrementales a través de REST, incluye "stream": true en el cuerpo de la solicitud JSON:

curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"${MODEL_ID}"'",
    "stream": true,
    "input": [{
      "role": "user",
      "content": [{
        "type": "text",
        "text": "Write a long story about space travel."
      }]
    }]
  }'

Cuando se establece "stream": true, el servidor responde con Transfer-Encoding: chunked y Content-Type: text/event-stream (eventos enviados por el servidor). Cada evento de la transmisión incluye un prefijo data: que contiene una carga útil JSON con el contenido de event_type y el delta del paso. curl mantiene automáticamente abierta la conexión HTTP y escribe los fragmentos entrantes en stdout en tiempo real hasta que se completa la interacción.

Ejecuta un agente administrado en segundo plano

Para iniciar de forma asíncrona una tarea de agente administrado de larga duración a través de REST, especifica el agent de destino, establece "background": true y configura "environment": "remote":

curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "agent": "'"${AGENT_ID}"'",
    "environment": "remote",
    "background": true,
    "input": [{
      "role": "user",
      "content": [{
        "type": "text",
        "text": "Analyze competitive positioning for commercial solar energy providers."
      }]
    }]
  }'

¿Qué sigue?