Bắt đầu

Hướng dẫn này giúp bạn bắt đầu sử dụng Gemini API bằng Interactions API. Bạn sẽ thực hiện lệnh gọi API đầu tiên trong vòng chưa đầy một phút và khám phá tính năng tạo văn bản, khả năng hiểu đa phương thức, tạo hình ảnh, đầu ra có cấu trúc, công cụ, gọi hàm, tác nhân và thực thi ở chế độ nền.

Bạn có thể sử dụng Interactions API thông qua SDK PythonJavaScript, cũng như thông qua REST.

1. Lấy khoá API

Để sử dụng Gemini API, bạn cần có một khoá API để xác thực các yêu cầu, thực thi giới hạn bảo mật và theo dõi mức sử dụng cho tài khoản của bạn.

  • Google AI Studio sẽ tự động tạo một dự án và khoá API cho người dùng mới. Bạn có thể sao chép khoá này từ trang khoá API.
  • Nếu bạn cần một khoá mới, hãy nhấp vào Tạo khoá API trong AI Studio rồi làm theo hộp thoại để thêm một cặp khoá-dự án mới.

Tạo khoá Gemini API

Đặt khoá của bạn làm biến môi trường:

export GEMINI_API_KEY="YOUR_API_KEY"

Nâng cấp lên gói trả phí

Việc nâng cấp lên gói trả phí sẽ giúp bạn tăng hạn mức sử dụng và yêu cầu bạn thiết lập dịch vụ Thanh toán trên đám mây.

  • Nhấp vào Thiết lập thông tin thanh toán trên trang Khoá API hoặc Dự án của AI Studio.
  • Làm theo hộp thoại Thanh toán trên Cloud để tạo hoặc liên kết một tài khoản thanh toán, thêm một phương thức thanh toán và trả trước tối thiểu 10 USD (hoặc số tiền tương đương bằng đơn vị tiền tệ khác) dưới dạng tín dụng có tính phí.
  • Xem mức sử dụng API trong Google AI Studio trong mục Trang tổng quan > Mức sử dụng.

Hãy xem trang Thanh toán để biết thêm thông tin.

2. Cài đặt SDK và thực hiện cuộc gọi đầu tiên

Cài đặt SDK và tạo văn bản bằng một lệnh gọi API duy nhất.

Python

Cài đặt SDK:

pip install -U google-genai

Khởi động ứng dụng và đưa ra yêu cầu:

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.6-flash",
    input="Explain how AI works in a few words"
)
print(interaction.output_text)

JavaScript

Cài đặt SDK:

npm install @google/genai

Khởi động ứng dụng và đưa ra yêu cầu:

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

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-3.6-flash",
  input: "Explain how AI works in a few words",
});
console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.6-flash",
    "input": "Explain how AI works in a few words"
  }'

Câu trả lời:

{
  "id": "v1_ChdpQUFvYXI...",
  "status": "completed",
  "usage": {
    "total_tokens": 197,
    "total_input_tokens": 8,
    "total_output_tokens": 12
  },
  "created": "2026-06-09T12:01:25Z",
  "steps": [
    {
      "type": "thought",
      "signature": "EvEFCu4FAQw..."
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "AI learns patterns from data, then uses those patterns to make predictions or decisions on new data."
        }
      ]
    }
  ],
  "object": "interaction",
  "model": "gemini-3.6-flash",
}

Khi sử dụng REST, API sẽ trả về tài nguyên Interaction đầy đủ chứa siêu dữ liệu, số liệu thống kê về mức sử dụng và nhật ký từng bước của lượt tương tác.

Mặc dù các SDK này hiển thị toàn bộ phản hồi, nhưng chúng cũng cung cấp các thuộc tính tiện lợi như interaction.output_textinteraction.output_image để truy cập trực tiếp vào đầu ra cuối cùng. Tìm hiểu thêm về cấu trúc phản hồi trong phần Tổng quan về các lượt tương tác hoặc đọc hướng dẫn tạo văn bản để biết thông tin chi tiết về hướng dẫn hệ thống và cấu hình tạo.

3. Hiện câu trả lời theo thời gian thực

Để có các lượt tương tác mượt mà hơn, hãy truyền trực tuyến câu trả lời khi câu trả lời được tạo. Mỗi sự kiện step.delta sẽ gửi một đoạn văn bản mà bạn có thể hiển thị ngay lập tức.

Python

from google import genai

client = genai.Client()

stream = client.interactions.create(
    model="gemini-3.6-flash",
    input="Explain how AI works",
    stream=True
)
for event in stream:
    print(event)

JavaScript

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

const ai = new GoogleGenAI({});

const stream = await ai.interactions.create({
  model: "gemini-3.6-flash",
  input: "Explain how AI works",
  stream: true,
});

for await (const event of stream) {
  console.log(event);
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  --no-buffer \
  -d '{
    "model": "gemini-3.6-flash",
    "input": "Explain how AI works",
    "stream": true
  }'

Khi phát trực tuyến, máy chủ sẽ phản hồi bằng một luồng sự kiện do máy chủ gửi (SSE). Mỗi sự kiện đều có một loại và dữ liệu JSON.

Câu trả lời:

event: interaction.created
data: {"interaction":{"id":"v1_Chd...","status":"in_progress","model":"gemini-3.6-flash"},"event_type":"interaction.created"}

event: step.start
data: {"index":0,"step":{"type":"thought"},"event_type":"step.start"}

event: step.delta
data: {"index":0,"delta":{"signature":"EvEFCu4F...","type":"thought_signature"},"event_type":"step.delta"}

event: step.stop
data: {"index":0,"event_type":"step.stop"}

event: step.start
data: {"index":1,"step":{"type":"model_output"},"event_type":"step.start"}

event: step.delta
data: {"index":1,"delta":{"text":"AI ","type":"text"},"event_type":"step.delta"}

event: step.delta
data: {"index":1,"delta":{"text":"works ","type":"text"},"event_type":"step.delta"}

event: step.stop
data: {"index":1,"event_type":"step.stop"}

event: interaction.completed
data: {"interaction":{"id":"v1_Chd...","status":"completed","usage":{"total_tokens":197}},"event_type":"interaction.completed"}

Để xem chi tiết về cách xử lý các sự kiện truyền phát trực tiếp và các loại delta, hãy xem hướng dẫn về các tương tác truyền phát trực tiếp.

4. Cuộc trò chuyện nhiều lượt

Interactions API hỗ trợ các cuộc trò chuyện nhiều lượt với 2 phương pháp:

  • Có trạng thái (nên dùng): Tiếp tục cuộc trò chuyện trên máy chủ bằng cách sử dụng previous_interaction_id. Lý tưởng cho hầu hết các quy trình trò chuyện và quy trình dựa trên tác nhân mà bạn muốn máy chủ quản lý nhật ký và tối ưu hoá việc lưu vào bộ nhớ đệm.
  • Không trạng thái: Quản lý nhật ký cuộc trò chuyện trên ứng dụng bằng cách truyền tất cả các lượt trước đó (bao gồm cả suy nghĩ và các bước sử dụng công cụ của mô hình trung gian) trong mỗi yêu cầu.

Tạo chuỗi tương tác bằng cách truyền previous_interaction_id. Máy chủ sẽ quản lý toàn bộ nhật ký trò chuyện cho bạn.

Python

from google import genai

client = genai.Client()

# Server-side state (recommended)
interaction1 = client.interactions.create(
    model="gemini-3.6-flash",
    input="I have 2 dogs in my house.",
)
print("Response 1:", interaction1.output_text)

interaction2 = client.interactions.create(
    model="gemini-3.6-flash",
    input="How many paws are in my house?",
    previous_interaction_id=interaction1.id,
)
print("Response 2:", interaction2.output_text)

JavaScript

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

const ai = new GoogleGenAI({});

// Server-side state (recommended)
const interaction1 = await ai.interactions.create({
  model: "gemini-3.6-flash",
  input: "I have 2 dogs in my house.",
});
console.log("Response 1:", interaction1.output_text);

const interaction2 = await ai.interactions.create({
  model: "gemini-3.6-flash",
  input: "How many paws are in my house?",
  previous_interaction_id: interaction1.id,
});
console.log("Response 2:", interaction2.output_text);

REST

RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.6-flash",
    "input": "I have 2 dogs in my house."
  }')

INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')
echo "Interaction 1 ID: $INTERACTION_ID"

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.6-flash",
    "input": "How many paws are in my house?",
    "previous_interaction_id": "'$INTERACTION_ID'"
  }'

Không có trạng thái

Đặt store=false và quản lý nhật ký cuộc trò chuyện ở phía máy khách. Bạn phải giữ nguyên và gửi lại tất cả các bước do mô hình tạo (bao gồm cả các bước thoughtfunction_call) đúng như những gì bạn nhận được.

Python

from google import genai

client = genai.Client()

history = [
    {
        "type": "user_input",
        "content": [{"type": "text", "text": "I have 2 dogs in my house."}]
    }
]

interaction1 = client.interactions.create(
    model="gemini-3.6-flash",
    store=False,
    input=history
)
print("Response 1:", interaction1.steps[-1].content[0].text)

for step in interaction1.steps:
    history.append(step.model_dump())

history.append({
    "type": "user_input",
    "content": [{"type": "text", "text": "How many paws are in my house?"}]
})

interaction2 = client.interactions.create(
    model="gemini-3.6-flash",
    store=False,
    input=history
)
print("Response 2:", interaction2.steps[-1].content[0].text)

JavaScript

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

const ai = new GoogleGenAI({});

const history = [
  {
    type: "user_input",
    content: [{ type: "text", text: "I have 2 dogs in my house." }]
  }
];

const interaction1 = await ai.interactions.create({
  model: "gemini-3.6-flash",
  store: false,
  input: history
});
console.log("Response 1:", interaction1.steps.at(-1).content[0].text);

history.push(...interaction1.steps);

history.push({
  type: "user_input",
  content: [{ type: "text", text: "How many paws are in my house?" }]
});

const interaction2 = await ai.interactions.create({
  model: "gemini-3.6-flash",
  store: false,
  input: history
});
console.log("Response 2:", interaction2.steps.at(-1).content[0].text);

REST

# Turn 1: Send with store: false
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.6-flash",
    "store": false,
    "input": [
      {
        "type": "user_input",
        "content": "I have 2 dogs in my house."
      }
    ]
  }')

MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')

# Turn 2: Build full history
HISTORY=$(jq -n \
  --argjson first_input '[{"type": "user_input", "content": "I have 2 dogs in my house."}]' \
  --argjson model_steps "$MODEL_STEPS" \
  --argjson second_input '[{"type": "user_input", "content": "How many paws are in my house?"}]' \
  '$first_input + $model_steps + $second_input')

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d "{
    \"model\": \"gemini-3.6-flash\",
    \"store\": false,
    \"input\": $HISTORY
  }"

Câu trả lời:

{
  "id": "v2_Chd...",
  "status": "completed",
  "usage": {
    "total_tokens": 240,
    "total_input_tokens": 60,
    "total_output_tokens": 20
  },
  "steps": [
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "There are 8 paws in your house. 2 dogs \u00d7 4 paws = 8 paws."
        }
      ]
    }
  ],
  "object": "interaction",
  "model": "gemini-3.6-flash"
}

Lần tương tác thứ hai sẽ trả về một đối tượng phản hồi hoàn chỉnh chỉ bao gồm các bước mới, nhưng dựa trên ngữ cảnh của lượt tương tác trước đó. Tìm hiểu thêm về cách duy trì trạng thái trong hướng dẫn về cuộc trò chuyện nhiều lượt hoặc khám phá chế độ không trạng thái để quản lý nhật ký phía máy khách.

5. Khả năng hiểu đa phương thức

Các mô hình Gemini có thể hiểu được hình ảnh, âm thanh, video và tài liệu một cách tự nhiên. Truyền nội dung nghe nhìn cùng với văn bản trong một yêu cầu duy nhất.

Python

import base64
from google import genai

client = genai.Client()

# Load a local image
with open("sample.jpg", "rb") as f:
    image_bytes = f.