Hướng dẫn nhanh về Gemini API

Hướng dẫn nhanh này cho bạn biết cách cài đặt các thư viện của chúng tôi và thực hiện yêu cầu API đầu tiên đối với Gemini API bằng Interactions API.

Trước khi bắt đầu

Để sử dụng Gemini API, bạn cần có một khoá API. Bạn có thể tạo khoá API miễn phí để bắt đầu.

Tạo khoá Gemini API

Cài đặt Google GenAI SDK

Python

Khi dùng Python 3.9 trở lên, hãy cài đặt gói google-genai bằng lệnh pip sau:

pip install -q -U google-genai

JavaScript

Sử dụng Node.js phiên bản 18 trở lên, hãy cài đặt Google Gen AI SDK cho TypeScript và JavaScript bằng lệnh npm sau:

npm install @google/genai

Tạo yêu cầu đầu tiên

Dưới đây là ví dụ sử dụng Interactions API để gửi yêu cầu đến Gemini API bằng mô hình Gemini 3 Flash.

Nếu bạn đặt khoá API làm biến môi trường GEMINI_API_KEY, thì ứng dụng sẽ tự động chọn khoá này khi sử dụng Thư viện Gemini API. Nếu không, bạn sẽ cần truyền khoá API làm đối số khi khởi chạy ứng dụng.

Xin lưu ý rằng tất cả các mẫu mã trong tài liệu Gemini API đều giả định rằng bạn đã đặt biến môi trường GEMINI_API_KEY.

Python

from google import genai

# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()

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

# Print the model's text response
for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)

JavaScript

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

// The client gets the API key from the environment variable `GEMINI_API_KEY`.
const ai = new GoogleGenAI({});

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "Explain how AI works in a few words",
  });

  const modelStep = interaction.steps.find(s => s.type === 'model_output');
  if (modelStep) {
    for (const contentBlock of modelStep.content) {
      if (contentBlock.type === 'text') console.log(contentBlock.text);
    }
  }
}

main();

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-flash-preview",
    "input": "Explain how AI works in a few words"
  }'

Bước tiếp theo

Giờ đây, khi đã thực hiện yêu cầu API đầu tiên, bạn có thể muốn khám phá các hướng dẫn sau đây cho thấy Gemini đang hoạt động: