Bắt đầu nhanh API Gemini

Phần bắt đầu nhanh này hướng dẫn bạn cách cài đặt thư viện của chúng tôi và tạo yêu cầu API Gemini đầu tiên.

Trước khi bắt đầu

Bạn cần có khoá Gemini API. Nếu chưa có, bạn có thể tải ứng dụng này miễn phí trong Google AI Studio.

Cài đặt SDK Google GenAI

Sử dụng Python 3.9 trở lên, hãy cài đặt gói google-genai bằng cách sử dụng lệnh pip sau:

pip install -q -U google-genai

Sử dụng Node.js v18 trở lên, hãy cài đặt SDK AI tạo sinh của Google cho TypeScript và JavaScript bằng lệnh npm sau:

npm install @google/genai

Cài đặt google.golang.org/genai trong thư mục mô-đun bằng lệnh go get:

go get google.golang.org/genai
  1. Để tạo một dự án Apps Script mới, hãy truy cập vào script.new.
  2. Nhấp vào Untitled project (Dự án chưa có tiêu đề).
  3. Đổi tên dự án Apps Script thành AI Studio rồi nhấp vào Rename (Đổi tên).
  4. Đặt khoá API
    1. Ở bên trái, hãy nhấp vào biểu tượng Cài đặt dự án Biểu tượng cài đặt dự án.
    2. Trong phần Thuộc tính tập lệnh, hãy nhấp vào Thêm thuộc tính tập lệnh.
    3. Đối với Tài sản, hãy nhập tên khoá: GEMINI_API_KEY.
    4. Đối với Giá trị, hãy nhập giá trị cho khoá API.
    5. Nhấp vào Lưu thuộc tính tập lệnh.
  5. Thay thế nội dung tệp Code.gs bằng mã sau:

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

Sử dụng phương thức generateContent để gửi yêu cầu đến Gemini API.

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: "Explain how AI works in a few words",
  });
  console.log(response.text);
}

main();
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  "YOUR_API_KEY",
        Backend: genai.BackendGeminiAPI,
    })
    if err != nil {
        log.Fatal(err)
    }

    result, err := client.Models.GenerateContent(
        ctx,
        "gemini-2.0-flash",
        genai.Text("Explain how AI works in a few words"),
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.Text())
}
// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
  const payload = {
    contents: [
      {
        parts: [
          { text: 'Explain how AI works in a few words' },
        ],
      },
    ],
  };

  const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
  const options = {
    method: 'POST',
    contentType: 'application/json',
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response);
  const content = data['candidates'][0]['content']['parts'][0]['text'];
  console.log(content);
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$YOUR_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
  }'

Bước tiếp theo

Giờ đây, khi đã tạo yêu cầu API đầu tiên, bạn nên khám phá các hướng dẫn sau đây về cách Gemini hoạt động: