Panduan developer Interactions API

Interactions API menyediakan antarmuka terpadu dan stateful untuk membangun aplikasi AI generatif dengan model Gemini dan agen otonom di Gemini Enterprise Agent Platform. Gunakan Interactions API untuk menjalankan percakapan multi-giliran, melakukan streaming respons real-time, menerapkan output terstruktur, mengeksekusi panggilan fungsi, dan mengatur tugas latar belakang yang berjalan lama.

Panduan ini menunjukkan cara menginstal Google Gen AI SDK, mengautentikasi klien, dan menerapkan alur kerja interaksi umum. Untuk mengetahui detail konseptual tentang siklus proses interaksi, lihat Ringkasan Interactions API.

Sebelum memulai

Sebelum mengirim permintaan ke Interactions API, siapkan Google Cloud project dan lingkungan pengembangan Anda:

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  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.

Konsep utama

Tinjau konsep berikut untuk memahami cara Interactions API mengelola status dan respons:

  • Interaction: Interactions API berpusat pada resource inti: Interaction. Interaction mewakili giliran yang lengkap dalam percakapan atau tugas, yang melacak kronologi pemikiran model, panggilan alat, dan output akhir. Vertex AI menyediakan platform terpadu untuk interaksi prompt-respons dan alur kerja agen multilangkah yang kompleks.
  • Penyimpanan dengan status: Interaksi disimpan di sisi server secara default (store=True di Python atau store: true di TypeScript/JavaScript). Interaksi yang disimpan akan tetap ada selama 7 hari dan akan otomatis dihapus setelah jangka waktu tersebut. Menetapkan store=False memilih untuk menggunakan mode stateless, yang menonaktifkan retensi sisi server dan mematuhi Zero Data Retention (ZDR). Mode stateless juga menonaktifkan penggabungan previous_interaction_id dan eksekusi asinkron (background=True).
  • Helper respons: Google Gen AI SDK versi 2.3.0 dan yang lebih baru menyediakan properti praktis pada respons interaksi, termasuk interaction.output_text, interaction.output_image, dan interaction.output_audio. Gunakan interaction.output_text untuk membaca respons teks, bukan mengindeks secara manual ke dalam array langkah (seperti interaction.steps[-1].content[0].text).

Persyaratan

Pastikan lingkungan dan permintaan Anda memenuhi persyaratan berikut sebelum melakukan integrasi dengan Interactions API:

  • Dukungan versi SDK: Gunakan Google Gen AI SDK terpadu (>= 2.3.0 untuk Python atau @google/genai >= 2.3.0 untuk TypeScript dan JavaScript).

    • Versi 2.3.0 atau yang lebih baru diperlukan untuk properti helper respons dan kemampuan agen, sedangkan versi 2.0.0 mendukung skema steps dasar.
    • SDK lama (google-cloud-aiplatform, @google-cloud/vertexai, dan google-generativeai) tidak mendukung Interactions API.
  • Model yang didukung: Gunakan model Gemini 3 yang didukung atau yang lebih baru. Seri model sebelumnya tidak mendukung API ini. Untuk mengetahui daftar lengkap model yang didukung, lihat Model yang didukung dan Bermigrasi ke versi model terbaru.

  • Parameter cakupan giliran: Parameter konfigurasi seperti tools, system_instruction, dan generation_config hanya berlaku untuk giliran saat ini. Teruskan parameter ini pada setiap giliran interaksi berikutnya jika alur kerja Anda memerlukannya di seluruh percakapan multi-turn.

Menginstal Google Gen AI SDK

Instal atau upgrade Google Gen AI SDK (>= 2.3.0) untuk bahasa pilihan Anda:

Python

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

TypeScript / JavaScript

npm install "@google/genai>=2.3.0"

Mengautentikasi klien Anda

Anda dapat terhubung ke Interactions API di Agent Platform menggunakan salah satu metode autentikasi berikut:

Menghubungkan menggunakan project Google Cloud dengan Kredensial Default Aplikasi (ADC)

Sebaiknya gunakan metode autentikasi ini untuk workload perusahaan dan deployment produksi di Google Cloud. Untuk melakukan autentikasi dengan Kredensial Default Aplikasi (ADC), lakukan inisialisasi klien dengan properti berikut:

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

Jika Anda belum mengonfigurasi kredensial lokal, jalankan gcloud auth application-default login.

Pada contoh kode berikut, ganti PROJECT_ID dengan Google Cloud project ID Anda.

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."
      }]
    }]
  }'

Menghubungkan menggunakan mode ekspres (kunci API)

Sebaiknya gunakan metode autentikasi ini untuk pembuatan prototipe cepat, skrip ringan, atau lingkungan yang melakukan autentikasi dengan kunci API. Teruskan kunci API Anda saat menginisialisasi klien atau di header HTTP x-goog-api-key.

Pada contoh kode berikut, ganti API_KEY dengan kunci API Anda.

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."
      }]
    }]
  }'

Alur kerja interaksi umum

Setelah mengonfigurasi klien, Anda dapat menggunakan metode interactions.create untuk membangun percakapan multi-giliran, melakukan streaming token output secara real time, membuat JSON yang divalidasi skemanya, memanggil fungsi eksternal, dan menjalankan agen otonom.

Mengelola percakapan multi-giliran dengan status

Tidak seperti API chat tanpa status yang mengharuskan Anda mengirim ulang histori pesan lengkap dengan setiap permintaan, Interactions API mengelola status percakapan di server secara default (store=True di Python atau store: true di TypeScript/JavaScript).

Untuk melanjutkan percakapan yang ada, teruskan id interaksi sebelumnya ke parameter previous_interaction_id. Agent Platform secara otomatis mengambil konteks percakapan yang disimpan dan menambahkan giliran baru. Jika Anda menetapkan store=False (store: false di TypeScript/JavaScript), persistensi sisi server dinonaktifkan dan Anda tidak dapat menggabungkan giliran berikutnya dengan 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}`);

Streaming respons secara real time

Untuk mengurangi latensi yang dirasakan pada aplikasi interaktif, Anda dapat melakukan streaming respons model saat respons tersebut dibuat. Tetapkan stream=True (stream: true di TypeScript/JavaScript) saat memanggil interactions.create untuk menerima aliran iterable peristiwa yang dikirim server. Filter untuk peristiwa step.delta guna merender potongan teks inkremental saat tiba:

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();

Membuat output terstruktur

Jika aplikasi Anda memerlukan respons dalam format yang dapat diprediksi dan dapat dibaca mesin, Anda dapat membatasi output model agar sesuai dengan skema JSON tertentu. Teruskan skema target Anda—seperti skema JSON model Pydantic di Python atau objek skema Type di TypeScript/JavaScript—langsung ke parameter polimorfik 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);

Menggunakan panggilan fungsi (penggunaan alat)

Panggilan fungsi memungkinkan model meminta eksekusi fungsi kustom atau API eksternal untuk mengumpulkan informasi sebelum merumuskan respons akhir. Dalam alur kerja interaksi yang memiliki status, panggilan fungsi mengikuti pola dua giliran:

  1. Mendeklarasikan dan meneruskan alat: Berikan deklarasi fungsi Anda dalam parameter tools pada permintaan awal.
  2. Jalankan dan tampilkan hasil: Periksa langkah-langkah respons (interaction.steps) untuk langkah-langkah function_call, jalankan fungsi lokal menggunakan arguments yang disediakan model, dan kirim interaksi lanjutan yang berisi item function_result yang ditautkan oleh call_id dan 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);
    }
}

Menjalankan agen dan tugas latar belakang yang berjalan lama

Selain model dasar, Interactions API memungkinkan Anda memanggil agen otonom khusus menggunakan parameter agent:

  • antigravity-preview-05-2026: Agen terkelola serbaguna dengan eksekusi kode, pengelolaan file, dan penjelajahan web di lingkungan Linux sandbox yang aman. Untuk mengetahui informasi selengkapnya, lihat Berinteraksi dengan agen.
  • deep-research-preview-04-2026: Agen Deep Research Gemini, yang merencanakan dan menjalankan tugas riset web multilangkah serta menyintesis temuan dari berbagai sumber menjadi laporan yang komprehensif. Untuk mengetahui informasi selengkapnya, lihat Menggunakan Agen Deep Research Gemini.
  • Agen kustom: Resource agen kustom yang dikonfigurasi dan disediakan dengan client.agents.create().

Karena alur kerja agen sering kali memerlukan waktu beberapa menit untuk diselesaikan, jalankan alur kerja tersebut secara asinkron di latar belakang dengan menetapkan background=True. API segera menampilkan objek Interaction dengan id yang dapat Anda polling menggunakan client.interactions.get() hingga interaction.status bertransisi ke completed:

Sebelum mencoba contoh ini, ganti PROJECT_ID dengan Google Cloud project ID Anda.

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)

Mengakses file Cloud Storage yang diupload

Anda dapat menggunakan Interactions API untuk mengakses file Cloud Storage yang diupload. Lihat contoh berikut:

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)

Saat meneruskan URI Cloud Storage (misalnya, gs://bucket-name/path/to/file) ke Interactions API, permintaan akan dievaluasi menggunakan kredensial pengguna akhir (EUC). API mengambil objek Cloud Storage menggunakan identitas pemanggil yang diautentikasi bukan agen layanan project latar belakang.

Untuk meneruskan file Cloud Storage dalam permintaan interaksi, akun utama yang memanggil (akun pengguna, akun layanan, atau identitas gabungan) harus memiliki izin storage.objects.get untuk semua objek yang dirujuk.

Mengonfigurasi peran IAM untuk mengakses file Cloud Storage

Berikan salah satu peran bawaan standar yang mencakup izin storage.objects.get:

  • Storage Object Viewer (roles/storage.objectViewer): Akses baca ke objek (direkomendasikan).
  • Pengguna Objek Penyimpanan (roles/storage.objectUser): Akses baca dan tulis ke objek.

Untuk memberikan akses ke akun pengguna menggunakan Google Cloud CLI, gunakan perintah berikut:

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

Untuk memberikan akses ke akun layanan panggilan tertentu, gunakan perintah berikut:

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

Memecahkan masalah akses file Cloud Storage

Jika akun utama yang memanggil tidak memiliki izin yang memadai, Interactions API akan menampilkan error 403 Forbidden yang mirip dengan berikut:

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

Untuk mengatasi masalah ini, berikan peran Storage Object Viewer (roles/storage.objectViewer) pada bucket atau objek kepada pemanggil yang diautentikasi.

Jika objek yang ditentukan tidak ada, atau jika izin bucket mencegah pemanggil melihat apakah objek ada, Interactions API akan menampilkan error 404 Not Found yang mirip dengan berikut ini:

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

Untuk mengatasi masalah ini, pastikan URI Cloud Storage sudah benar dan konfirmasi bahwa pemanggil yang diautentikasi memiliki akses baca ke bucket.

Alur kerja REST lanjutan

Untuk otomatisasi berbasis shell, pipeline CI/CD, atau lingkungan tanpa runtime Python atau TypeScript/JavaScript, Anda dapat memanggil Interactions API secara langsung melalui HTTP menggunakan curl.

Endpoint REST

Kirim permintaan POST ke endpoint Interactions API berikut:

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

Ganti variabel berikut dalam permintaan Anda:

  • PROJECT_ID: Project ID Google Cloud Anda.
  • LOCATION: Setel ke global (atau wilayah kustom yang didukung jika diperlukan oleh konfigurasi Anda).

Menetapkan variabel lingkungan dan autentikasi

Sebelum menjalankan contoh curl di bagian berikut, ekspor project ID, ID model atau agen target, dan token akses OAuth 2.0 yang dibuat dari Kredensial Default Aplikasi:

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

Format respons sinkron

Permintaan POST sinkron menampilkan objek JSON interaction yang mencakup metadata id interaksi, status eksekusi, steps percakapan, dan usage token yang unik:

{
  "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"
}

Melanjutkan interaksi stateful multi-giliran

Untuk melanjutkan percakapan tersimpan melalui REST, teruskan id dari respons sebelumnya di kolom previous_interaction_id isi permintaan JSON.

Sebelum mencoba contoh ini, ganti PREVIOUS_INTERACTION_ID dengan id yang ditampilkan oleh interaksi sebelumnya.

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?"
      }]
    }]
  }'

Streaming output dengan peristiwa yang dikirim server

Untuk melakukan streaming update inkremental melalui REST, sertakan "stream": true dalam isi permintaan 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."
      }]
    }]
  }'

Jika "stream": true disetel, server akan merespons dengan Transfer-Encoding: chunked dan Content-Type: text/event-stream (Server-Sent Events). Setiap peristiwa dalam aliran menyertakan awalan data: yang berisi payload JSON dengan konten delta langkah dan event_type. curl secara otomatis membiarkan koneksi HTTP tetap terbuka dan menulis potongan masuk ke stdout secara real time hingga interaksi selesai.

Menjalankan agen terkelola di latar belakang

Untuk memulai tugas agen terkelola yang berjalan lama secara asinkron melalui REST, tentukan target agent, tetapkan "background": true, dan konfigurasi "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."
      }]
    }]
  }'

Langkah berikutnya