Chạy Gemma bằng Gemini API

Gemini API cung cấp quyền truy cập được lưu trữ vào Gemma dưới dạng API lập trình mà bạn có thể sử dụng trong quá trình phát triển ứng dụng hoặc tạo mẫu thử. API này là một giải pháp thay thế thuận tiện cho việc thiết lập phiên bản cục bộ của riêng bạn về Gemma và dịch vụ web để xử lý các tác vụ AI tạo sinh.

Mô hình được hỗ trợ

Gemini API hỗ trợ các mô hình Gemma 4 sau đây:

  • gemma-4-31b-it
  • gemma-4-26b-a4b-it

Ví dụ sau đây cho thấy cách sử dụng Gemma với Gemini API:

Python

from google import genai

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

response = client.models.generate_content(
    model="gemma-4-31b-it",
    contents="Roses are red...",
)

print(response.text)

Node.js

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

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

const response = await ai.models.generateContent({
  model: "gemma-4-31b-it",
  contents: "Roses are red...",
});
console.log(response.text);

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-31b-it:generateContent?key=YOUR_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
  "contents": [{
    "parts":[{"text": "Roses are red..."}]
    }]
   }'

Nhận khoá API

Bạn có thể truy cập vào Gemini API trên nhiều nền tảng, chẳng hạn như dịch vụ di động, web và đám mây, cũng như bằng nhiều ngôn ngữ lập trình. Để biết thêm thông tin về các gói SDK Gemini API, hãy xem trang Tải SDK Gemini API xuống. Để biết thông tin giới thiệu chung về Gemini API, hãy xem bài viết Bắt đầu nhanh với Gemini API.

Tư duy

Gemma 4 sử dụng "quy trình tư duy" nội bộ để tối ưu hoá khả năng suy luận đa bước, mang lại hiệu suất vượt trội trong các miền đòi hỏi tính logic như mã hoá thuật toán và chứng minh toán học nâng cao.

Mặc dù Gemma 4 chỉ hỗ trợ bật hoặc tắt tính năng này, nhưng bạn có thể bật tính năng này trong API bằng cách đặt mức tư duy thành "high".

Ví dụ sau đây minh hoạ cách kích hoạt quy trình tư duy:

Python

from google import genai

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

response = client.models.generate_content(
    model="gemma-4-31b-it",
    contents="What is the water formula?",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(thinking_level="high")
    ),
)

print(response.text)

Node.js

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

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

const response = await ai.models.generateContent({
  model: "gemma-4-31b-it",
  contents: "What is the water formula?",
  config: {
    thinkingConfig: {
      thinkingLevel: ThinkingLevel.HIGH,
    },
  },
});
console.log(response.text);

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-31b-it:generateContent?key=YOUR_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
  "contents": [{
    "parts":[{"text": "What is the water formula?"}]
    }],
    "generationConfig": {
      "thinkingConfig": {
            "thinkingLevel": "high"
      }
    }
   }'

Tìm hiểu thêm về tính năng Tư duy:

Hiểu hình ảnh

Các mô hình Gemma 4 có thể xử lý hình ảnh, cho phép nhiều trường hợp sử dụng tiên tiến dành cho nhà phát triển mà trước đây cần có các mô hình dành riêng cho miền.

Ví dụ sau đây cho thấy cách sử dụng dữ liệu đầu vào Hình ảnh của Gemma với Gemini API:

Python

from google import genai

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

my_file = client.files.upload(file="path/to/sample.jpg")

response = client.models.generate_content(
    model="gemma-4-31b-it",
    contents=[my_file, "Caption this image."],
)

print(response.text)

Node.js

import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

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

const myfile = await ai.files.upload({
  file: "path/to/sample.jpg",
  config: { mimeType: "image/jpeg" },
});

const response = await ai.models.generateContent({
  model: "gemma-4-31b-it",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
    "Caption this image.",
  ]),
});
console.log(response.text);
 ```

REST

IMAGE_PATH="cats-and-dogs.jpg"
MIME_TYPE=$(file -b --mime-type "${IMAGE_PATH}")
NUM_BYTES=$(wc -c < "${IMAGE_PATH}")
DISPLAY_NAME=IMAGE

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=YOUR_API_KEY" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${IMAGE_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq -r ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-31b-it:generateContent?key=YOUR_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"file_data":{"mime_type": "'"${MIME_TYPE}"'", "file_uri": "'"${file_uri}"'"}},
          {"text": "Caption this image."}]
        }]
      }' 2> /dev/null > response.json

cat response.json
echo

jq -r ".candidates[].content.parts[].text" response.json

Tìm hiểu thêm về tính năng Hiểu hình ảnh: