Bắt đầu nhanh API Gemini

Hướng dẫn bắt đầu 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à đưa ra yêu cầu đầu tiên cho Gemini API.

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 miễn phí trong Google AI Studio.

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

Go

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

Java

Nếu đang sử dụng Maven, bạn có thể cài đặt google-genai bằng cách thêm nội dung sau vào các phần phụ thuộc:

<dependencies>
  <dependency>
    <groupId>com.google.genai</groupId>
    <artifactId>google-genai</artifactId>
    <version>1.0.0</version>
  </dependency>
</dependencies>

Apps Script

  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 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 Cài đặt dự án Biểu tượng cho chế độ cài đặt dự án.
    2. Trong phần Script Properties (Thuộc tính tập lệnh), hãy nhấp vào Add script property (Thêm thuộc tính tập lệnh).
    3. Đối với Thuộc tính, 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 của tập lệnh.
  5. Thay thế nội dung tệp Code.gs bằng đoạn mã sau:

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

Dưới đây là một ví dụ sử dụng phương thức generateContent để gửi yêu cầu đến Gemini API bằng mô hình Gemini 2.5 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 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()

response = client.models.generate_content(
    model="gemini-2.5-flash", contents="Explain how AI works in a few words"
)
print(response.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 response = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents: "Explain how AI works in a few words",
  });
  console.log(response.text);
}

main();

Go

package main

import (
    "context"
    "fmt"
    "log"
    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    // The client gets the API key from the environment variable `GEMINI_API_KEY`.
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    result, err := client.Models.GenerateContent(
        ctx,
        "gemini-2.5-flash",
        genai.Text("Explain how AI works in a few words"),
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.Text())
}

Java

package com.example;

import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;

public class GenerateTextFromTextInput {
  public static void main(String[] args) {
    // The client gets the API key from the environment variable `GEMINI_API_KEY`.
    Client client = new Client();

    GenerateContentResponse response =
        client.models.generateContent(
            "gemini-2.5-flash",
            "Explain how AI works in a few words",
            null);

    System.out.println(response.text());
  }
}

Apps Script

// 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.5-flash:generateContent';
  const options = {
    method: 'POST',
    contentType: 'application/json',
    headers: {
      'x-goog-api-key': apiKey,
    },
    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);
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
  }'

Theo mặc định, chế độ "Đang suy nghĩ" sẽ bật trên nhiều mẫu mã của chúng tôi

Nhiều mẫu mã trên trang web này sử dụng mô hình Gemini 2.5 Flash. Mô hình này có tính năng "suy nghĩ" được bật theo mặc định để nâng cao chất lượng câu trả lời. Xin lưu ý rằng việc này có thể làm tăng thời gian phản hồi và mức sử dụng mã thông báo. Nếu ưu tiên tốc độ hoặc muốn giảm thiểu chi phí, bạn có thể tắt tính năng này bằng cách đặt ngân sách suy nghĩ thành 0, như minh hoạ trong các ví dụ bên dưới. Để biết thêm thông tin, hãy xem hướng dẫn tư duy.

Python

from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Explain how AI works in a few words",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(thinking_budget=0) # Disables thinking
    ),
)
print(response.text)

JavaScript

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

const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents: "Explain how AI works in a few words",
    config: {
      thinkingConfig: {
        thinkingBudget: 0, // Disables thinking
      },
    }
  });
  console.log(response.text);
}

await main();

Go

package main

import (
  "context"
  "fmt"
  "os"
  "google.golang.org/genai"
)

func main() {

  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }

  result, _ := client.Models.GenerateContent(
      ctx,
      "gemini-2.5-flash",
      genai.Text("Explain how AI works in a few words"),
      &genai.GenerateContentConfig{
        ThinkingConfig: &genai.ThinkingConfig{
            ThinkingBudget: int32(0), // Disables thinking
        },
      }
  )

  fmt.Println(result.Text())
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
    "generationConfig": {
      "thinkingConfig": {
        "thinkingBudget": 0
      }
    }
  }'

Apps Script

// 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.5-flash:generateContent';
  const options = {
    method: 'POST',
    contentType: 'application/json',
    headers: {
      'x-goog-api-key': apiKey,
    },
    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);
}

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: