Generating content

Gemini API 支援使用圖片、音訊、程式碼、工具等生成內容。如要進一步瞭解各項功能,請繼續閱讀並查看以工作為主的程式碼範例,或參閱完整指南。

方法:models.generateContent

根據輸入內容 GenerateContentRequest 生成模型回覆。如需詳細的使用資訊,請參閱文字生成指南。不同模型 (包括經過調整的模型) 的輸入功能不盡相同。詳情請參閱模型指南和調整指南。

端點

貼文 https://generativelanguage.googleapis.com/v1beta/{model=models/*}:generateContent

路徑參數

model string

必填。要用來生成補全內容的Model名稱。

格式:models/{model}。格式為 models/{model}。

要求主體

要求主體會包含結構如下的資料:

欄位
contents[] object (Content)

必填。與模型目前對話的內容。

如果是單輪查詢,這會是單一執行個體。如果是 chat 等多輪查詢,這個重複欄位會包含對話記錄和最新要求。

tools[] object (Tool)

(選用步驟) Model 可能會用來生成下一個回覆的Tools清單。

Tool是一段程式碼,可讓系統與外部系統互動,執行 Model 知識和範圍以外的一或多項動作。支援的 Tool 為 Function 和 codeExecution。詳情請參閱呼叫函式和執行程式碼指南。

toolConfig object (ToolConfig)

(選用步驟) 要求中指定的任何 Tool 工具設定。如需使用範例,請參閱函式呼叫指南。

safetySettings[] object (SafetySetting)

(選用步驟) 用於封鎖不安全內容的不重複 SafetySetting 執行個體清單。

這項規定將於 GenerateContentRequest.contents和GenerateContentResponse.candidates強制執行。每個 SafetyCategory 類型不應有多個設定。API 會封鎖不符合這些設定門檻的內容和回覆。這份清單會覆寫 safetySettings 中指定的每個 SafetyCategory 預設設定。如果清單中未提供特定 SafetyCategory 的 SafetySetting,API 會使用該類別的預設安全設定。支援的危害類別包括 HARM_CATEGORY_HATE_SPEECH、HARM_CATEGORY_SEXUALLY_EXPLICIT、HARM_CATEGORY_DANGEROUS_CONTENT、HARM_CATEGORY_HARASSMENT、HARM_CATEGORY_CIVIC_INTEGRITY、HARM_CATEGORY_JAILBREAK。如要進一步瞭解可用的安全設定,請參閱指南。另請參閱安全指南,瞭解如何在 AI 應用程式中納入安全考量。

continuationToken string (bytes format)

(選用步驟) 不透明的接續權杖,用於從先前的 models.generateContent 或 models.streamGenerateContent 回應繼續生成,該回應在 finishReason 設為 CONTINUATION 時停止。請注意,contents 為必要欄位,且在要求中提供接續權杖時,必須與初始要求中的提示和對話記錄完全相同。

Base64 編碼字串。

labels map (key: string, value: string)

(選用步驟) 要求的使用者定義中繼資料標籤。

(選用步驟) 標籤必須符合標準統一 Cloud 標籤規定:- 標籤鍵開頭須為英文字母。- 標籤鍵和值的長度不得超過 63 個字元 (Unicode 碼點),且只能包含小寫英文字母、數字、底線和破折號。- 可以使用國際字元。

用法:- 來自集結網站的安全 ID:使用 safety_identifier 鍵 (例如 {"safety_identifier": "user_session_123"})

這個物件中包含 "key": value 組合的清單,範例:{ "name": "wrench", "mass": "1.3kg", "count": "3" }。

systemInstruction object (Content)

(選用步驟) 開發人員設定的系統指令。目前僅支援文字。

generationConfig object (GenerationConfig)

(選用步驟) 模型生成和輸出的設定選項。

cachedContent string

(選用步驟) 快取內容的名稱,做為提供預測結果的背景資訊。格式:cachedContents/{cachedContent}

serviceTier enum (ServiceTier)

(選用步驟) 要求的服務層級。

store boolean

(選用步驟) 設定特定要求的記錄行為。如果設定,則優先順序高於專案層級的記錄設定。

要求範例

文字

Python

from google import genai

client = genai.Client()
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Write a story about a magic backpack.",
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: 'Write a story about a magic backpack.',
});
console.log(response.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
contents := []*genai.Content{
	genai.NewContentFromText("Write a story about a magic backpack.", genai.RoleUser),
}
response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

貝殼

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[{"text": "Write a story about a magic backpack."}]
        }]
       }' 2> /dev/null

Java

Client client = new Client();

GenerateContentResponse response =
    client.models.generateContent(
        "gemini-3.8-flash", "Write a story about a magic backpack.", null);

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

圖片

Python

from google import genai
import PIL.Image

client = genai.Client()
organ = PIL.Image.open(media / "organ.jpg")
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=["Tell me about this instrument", organ],
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

const organ = await ai.files.upload({
  file: path.join(media, 'organ.jpg'),
});

const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: [
    createUserContent([
      'Tell me about this instrument',
      createPartFromUri(organ.uri, organ.mimeType)
    ]),
  ],
});
console.log(response.text);

Go

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

file, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "organ.jpg"),
	&genai.UploadFileConfig{
		MIMEType: "image/jpeg",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromText("Tell me about this instrument"),
	genai.NewPartFromURI(file.URI, file.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

貝殼

# Use a temporary file to hold the base64 encoded image data
TEMP_B64=$(mktemp)
trap 'rm -f "$TEMP_B64"' EXIT
base64 $B64FLAGS $IMG_PATH > "$TEMP_B64"

# Use a temporary file to hold the JSON payload
TEMP_JSON=$(mktemp)
trap 'rm -f "$TEMP_JSON"' EXIT

cat > "$TEMP_JSON" << EOF
{
  "contents": [{
    "parts":[
      {"text": "Tell me about this instrument"},
      {
        "inline_data": {
          "mime_type":"image/jpeg",
          "data": "$(cat "$TEMP_B64")"
        }
      }
    ]
  }]
}
EOF

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d "@$TEMP_JSON" 2> /dev/null

Java

Client client = new Client();

String path = media_path + "organ.jpg";
byte[] imageData = Files.readAllBytes(Paths.get(path));

Content content =
    Content.fromParts(
        Part.fromText("Tell me about this instrument."),
        Part.fromBytes(imageData, "image/jpeg"));

GenerateContentResponse response =
    client.models.generateContent("gemini-3.8-flash", content, null);

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

音訊

Python

from google import genai

client = genai.Client()
sample_audio = client.files.upload(file=media / "sample.mp3")
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

const audio = await ai.files.upload({
  file: path.join(media, 'sample.mp3'),
});

const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: [
    createUserContent([
      'Give me a summary of this audio file.',
      createPartFromUri(audio.uri, audio.mimeType),
    ]),
  ],
});
console.log(response.text);

Go

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

file, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "sample.mp3"),
	&genai.UploadFileConfig{
		MIMEType: "audio/mpeg",
	},
)
if err != nil {
	log.Fatal(err)
}

parts := []*genai.Part{
	genai.NewPartFromText("Give me a summary of this audio file."),
	genai.NewPartFromURI(file.URI, file.MIMEType),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

貝殼

# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

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 "${BASE_URL}/upload/v1beta/files?key=${GEMINI_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 "@${AUDIO_PATH}" 2> /dev/null > file_info.json

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Please describe this file."},
          {"file_data":{"mime_type": "audio/mpeg", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

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

影片

Python

from google import genai
import time

client = genai.Client()
# Video clip (CC BY 3.0) from https://peach.blender.org/download/
myfile = client.files.upload(file=media / "Big_Buck_Bunny.mp4")
print(f"{myfile=}")

# Poll until the video file is completely processed (state becomes ACTIVE).
while not myfile.state or myfile.state.name != "ACTIVE":
  print("Processing video...")
  print("File state:", myfile.state)
  time.sleep(5)
  myfile = client.files.get(name=myfile.name)

response = client.models.generate_content(
    model="gemini-3.8-flash", contents=[myfile, "Describe this video clip"]
)
print(f"{response.text=}")

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

let video = await ai.files.upload({
  file: path.join(media, 'Big_Buck_Bunny.mp4'),
});

// Poll until the video file is completely processed (state becomes ACTIVE).
while (!video.state || video.state.toString() !== 'ACTIVE') {
  console.log('Processing video...');
  console.log('File state: ', video.state);
  await sleep(5000);
  video = await ai.files.get({name: video.name});
}

const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: [
    createUserContent([
      'Describe this video clip',
      createPartFromUri(video.uri, video.mimeType),
    ]),
  ],
});
console.log(response.text);

Go

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

file, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "Big_Buck_Bunny.mp4"),
	&genai.UploadFileConfig{
		MIMEType: "video/mp4",
	},
)
if err != nil {
	log.Fatal(err)
}

// Poll until the video file is completely processed (state becomes ACTIVE).
for file.State == genai.FileStateUnspecified || file.State != genai.FileStateActive {
	fmt.Println("Processing video...")
	fmt.Println("File state:", file.State)
	time.Sleep(5 * time.Second)

	file, err = client.Files.Get(ctx, file.Name, nil)
	if err != nil {
		log.Fatal(err)
	}
}

parts := []*genai.Part{
	genai.NewPartFromText("Describe this video clip"),
	genai.NewPartFromURI(file.URI, file.MIMEType),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

貝殼

# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${VIDEO_PATH}")
NUM_BYTES=$(wc -c < "${VIDEO_PATH}")
DISPLAY_NAME=VIDEO

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GEMINI_API_KEY}" \
  -D "${tmp_header_file}" \
  -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 "@${VIDEO_PATH}" 2> /dev/null > file_info.json

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

state=$(jq ".file.state" file_info.json)
echo state=$state

name=$(jq ".file.name" file_info.json)
echo name=$name

while [[ "($state)" = *"PROCESSING"* ]];
do
  echo "Processing video..."
  sleep 5
  # Get the file of interest to check state
  curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
  state=$(jq ".file.state" file_info.json)
done

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions."},
          {"file_data":{"mime_type": "video/mp4", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

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

PDF

Python

from google import genai

client = genai.Client()
sample_pdf = client.files.upload(file=media / "test.pdf")
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=["Give me a summary of this document:", sample_pdf],
)
print(f"{response.text=}")

Go

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

file, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "test.pdf"),
	&genai.UploadFileConfig{
		MIMEType: "application/pdf",
	},
)
if err != nil {
	log.Fatal(err)
}

parts := []*genai.Part{
	genai.NewPartFromText("Give me a summary of this document:"),
	genai.NewPartFromURI(file.URI, file.MIMEType),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

貝殼

MIME_TYPE=$(file -b --mime-type "${PDF_PATH}")
NUM_BYTES=$(wc -c < "${PDF_PATH}")
DISPLAY_NAME=TEXT


echo $MIME_TYPE
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 "${BASE_URL}/upload/v1beta/files?key=${GEMINI_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 "@${PDF_PATH}" 2> /dev/null > file_info.json

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

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Can you add a few more lines to this poem?"},
          {"file_data":{"mime_type": "application/pdf", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

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

即時通訊

Python

from google import genai
from google.genai import types

client = genai.Client()
# Pass initial history using the "history" argument
chat = client.chats.create(
    model="gemini-3.8-flash",
    history=[
        types.Content(role="user", parts=[types.Part(text="Hello")]),
        types.Content(
            role="model",
            parts=[
                types.Part(
                    text="Great to meet you. What would you like to know?"
                )
            ],
        ),
    ],
)
response = chat.send_message(message="I have 2 dogs in my house.")
print(response.text)
response = chat.send_message(message="How many paws are in my house?")
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});
const chat = ai.chats.create({
  model: 'gemini-3.8-flash',
  history: [
    {
      role: 'user',
      parts: [{text: 'Hello'}],
    },
    {
      role: 'model',
      parts: [{text: 'Great to meet you. What would you like to know?'}],
    },
  ],
});

const response1 = await chat.sendMessage({
  message: 'I have 2 dogs in my house.',
});
console.log('Chat response 1:', response1.text);

const response2 = await chat.sendMessage({
  message: 'How many paws are in my house?',
});
console.log('Chat response 2:', response2.text);

Go

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

// Pass initial history using the History field.
history := []*genai.Content{
	genai.NewContentFromText("Hello", genai.RoleUser),
	genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),
}

chat, err := client.Chats.Create(ctx, "gemini-3.8-flash", nil, history)
if err != nil {
	log.Fatal(err)
}

firstResp, err := chat.SendMessage(ctx, genai.Part{Text: "I have 2 dogs in my house."})
if err != nil {
	log.Fatal(err)
}
fmt.Println(firstResp.Text())

secondResp, err := chat.SendMessage(ctx, genai.Part{Text: "How many paws are in my house?"})
if err != nil {
	log.Fatal(err)
}
fmt.Println(secondResp.Text())

貝殼

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role":"user",
         "parts":[{
           "text": "Hello"}]},
        {"role": "model",
         "parts":[{
           "text": "Great to meet you. What would you like to know?"}]},
        {"role":"user",
         "parts":[{
           "text": "I have two dogs in my house. How many paws are in my house?"}]},
      ]
    }' 2> /dev/null | grep "text"

Java

Client client = new Client();

Content userContent = Content.fromParts(Part.fromText("Hello"));
Content modelContent =
    Content.builder()
        .role("model")
        .parts(
            Collections.singletonList(
                Part.fromText("Great to meet you. What would you like to know?")))
        .build();

Chat chat =
    client.chats.create(
        "gemini-3.8-flash",
        GenerateContentConfig.builder()
            .systemInstruction(userContent)
            .systemInstruction(modelContent)
            .build());

GenerateContentResponse response1 = chat.sendMessage("I have 2 dogs in my house.");
System.out.println(response1.text());

GenerateContentResponse response2 = chat.sendMessage("How many paws are in my house?");
System.out.println(response2.text());

快取

Python

from google import genai
from google.genai import types

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.8-flash"

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
print(cache)

response = client.models.generate_content(
    model=model_name,
    contents="Please summarize this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});
const filePath = path.join(media, 'a11.txt');
const document = await ai.files.upload({
  file: filePath,
  config: {mimeType: 'text/plain'},
});
console.log('Uploaded file name:', document.name);
const modelName = 'gemini-3.8-flash';

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: 'You are an expert analyzing transcripts.',
  },
});
console.log('Cache created:', cache);

const response = await ai.models.generateContent({
  model: modelName,
  contents: 'Please summarize this transcript',
  config: {cachedContent: cache.name},
});
console.log('Response text:', response.text);

Go

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

modelName := "gemini-3.8-flash"
document, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "a11.txt"),
	&genai.UploadFileConfig{
		MIMEType: "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache created:")
fmt.Println(cache)

// Use the cache for generating content.
response, err := client.Models.GenerateContent(
	ctx,
	modelName,
	genai.Text("Please summarize this transcript"),
	&genai.GenerateContentConfig{
		CachedContent: cache.Name,
	},
)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

調整過的模型

Python

# With Gemini 2 we're launching a new SDK. See the following doc for details.
# https://ai.google.dev/gemini-api/docs/migrate

JSON 模式

Python

from google import genai
from google.genai import types
from typing_extensions import TypedDict

class Recipe(TypedDict):
  recipe_name: str
  ingredients: list[str]

client = genai.Client()
result = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="List a few popular cookie recipes.",
    config=types.GenerateContentConfig(
        response_mime_type="application/json", response_schema=list[Recipe]
    ),
)
print(result)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});
const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: 'List a few popular cookie recipes.',
  config: {
    responseMimeType: 'application/json',
    responseSchema: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          recipeName: {type: 'string'},
          ingredients: {type: 'array', items: {type: 'string'}},
        },
        required: ['recipeName', 'ingredients'],
      },
    },
  },
});
console.log(response.text);

Go

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

schema := &genai.Schema{
	Type: genai.TypeArray,
	Items: &genai.Schema{
		Type: genai.TypeObject,
		Properties: map[string]*genai.Schema{
			"recipe_name": {Type: genai.TypeString},
			"ingredients": {
				Type:  genai.TypeArray,
				Items: &genai.Schema{Type: genai.TypeString},
			},
		},
		Required: []string{"recipe_name"},
	},
}

config := &genai.GenerateContentConfig{
	ResponseMIMEType: "application/json",
	ResponseSchema:   schema,
}

response, err := client.Models.GenerateContent(
	ctx,
	"gemini-3.8-flash",
	genai.Text("List a few popular cookie recipes."),
	config,
)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

貝殼

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "contents": [{
      "parts":[
        {"text": "List 5 popular cookie recipes"}
        ]
    }],
    "generationConfig": {
        "response_mime_type": "application/json",
        "response_schema": {
          "type": "ARRAY",
          "items": {
            "type": "OBJECT",
            "properties": {
              "recipe_name": {"type":"STRING"},
            }
          }
        }
    }
}' 2> /dev/null | head

Java

Client client = new Client();

Schema recipeSchema =
    Schema.builder()
        .type(Array.class.getSimpleName())
        .items(
            Schema.builder()
                .type(Object.class.getSimpleName())
                .properties(
                    Map.of(
                        "recipe_name",
                        Schema.builder().type(String.class.getSimpleName()).build(),
                        "ingredients",
                        Schema.builder()
                            .type(Array.class.getSimpleName())
                            .items(Schema.builder().type(String.class.getSimpleName()).build())
                            .build()))
                .required(List.of("recipe_name", "ingredients"))
                .build())
        .build();

GenerateContentConfig config =
    GenerateContentConfig.builder()
        .responseMimeType("application/json")
        .responseSchema(recipeSchema)
        .build();

GenerateContentResponse response =
    client.models.generateContent(
        "gemini-3.8-flash", "List a few popular cookie recipes.", config);

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

執行程式碼

Python

from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=(
        "Write and execute code that calculates the sum of the first 50"
        " prime numbers. Ensure that only the executable code and its"
        " resulting output are generated."
    ),
)
# Each part may contain text, executable code, or an execution result.
for part in response.candidates[0].content.parts:
  print(part, "\n")

print("-" * 80)
# The .text accessor concatenates the parts into a markdown-formatted text.
print("\n", response.text)

Go

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

response, err := client.Models.GenerateContent(
	ctx,
	"gemini-3.8-flash",
	genai.Text(
		`Write and execute code that calculates the sum of the first 50 prime numbers.
		 Ensure that only the executable code and its resulting output are generated.`,
	),
	&genai.GenerateContentConfig{},
)
if err != nil {
	log.Fatal(err)
}

// Print the response.
printResponse(response)

fmt.Println("--------------------------------------------------------------------------------")
fmt.Println(response.Text())

Java

Client client = new Client();

String prompt =
    """
    Write and execute code that calculates the sum of the first 50 prime numbers.
    Ensure that only the executable code and its resulting output are generated.
    """;

GenerateContentResponse response =
    client.models.generateContent("gemini-3.8-flash", prompt, null);

for (Part part : response.candidates().get().getFirst().content().get().parts().get()) {
  System.out.println(part + "\n");
}

System.out.println("-".repeat(80));
System.out.println(response.text());

呼叫函式

Python

from google import genai
from google.genai import types

client = genai.Client()

def add(a: float, b: float) -> float:
  """returns a + b."""
  return a + b

def subtract(a: float, b: float) -> float:
  """returns a - b."""
  return a - b

def multiply(a: float, b: float) -> float:
  """returns a * b."""
  return a * b

def divide(a: float, b: float) -> float:
  """returns a / b."""
  return a / b

# Create a chat session; function calling (via tools) is enabled in the config.
chat = client.chats.create(
    model="gemini-3.8-flash",
    config=types.GenerateContentConfig(
        tools=[add, subtract, multiply, divide]
    ),
)
response = chat.send_message(
    message=(
        "I have 57 cats, each owns 44 mittens, how many mittens is that in"
        " total?"
    )
)
print(response.text)

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
modelName := "gemini-3.8-flash"

// Create the function declarations for arithmetic operations.
addDeclaration := createArithmeticToolDeclaration("addNumbers", "Return the result of adding two numbers.")
subtractDeclaration := createArithmeticToolDeclaration("subtractNumbers", "Return the result of subtracting the second number from the first.")
multiplyDeclaration := createArithmeticToolDeclaration("multiplyNumbers", "Return the product of two numbers.")
divideDeclaration := createArithmeticToolDeclaration("divideNumbers", "Return the quotient of dividing the first number by the second.")

// Group the function declarations as a tool.
tools := []*genai.Tool{
	{
		FunctionDeclarations: []*genai.FunctionDeclaration{
			addDeclaration,
			subtractDeclaration,
			multiplyDeclaration,
			divideDeclaration,
		},
	},
}

// Create the content prompt.
contents := []*genai.Content{
	genai.NewContentFromText(
		"I have 57 cats, each owns 44 mittens, how many mittens is that in total?", genai.RoleUser,
	),
}

// Set up the generate content configuration with function calling enabled.
config := &genai.GenerateContentConfig{
	Tools: tools,
	ToolConfig: &genai.ToolConfig{
		FunctionCallingConfig: &genai.FunctionCallingConfig{
			// The mode equivalent to FunctionCallingConfigMode.ANY in JS.
			Mode: genai.FunctionCallingConfigModeAny,
		},
	},
}

genContentResp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
if err != nil {
	log.Fatal(err)
}

// Assume the response includes a list of function calls.
if len(genContentResp.FunctionCalls()) == 0 {
	log.Println("No function call returned from the AI.")
	return nil
}
functionCall := genContentResp.FunctionCalls()[0]
log.Printf("Function call: %+v\n", functionCall)

// Marshal the Args map into JSON bytes.
argsMap, err := json.Marshal(functionCall.Args)
if err != nil {
	log.Fatal(err)
}

// Unmarshal the JSON bytes into the ArithmeticArgs struct.
var args ArithmeticArgs
if err := json.Unmarshal(argsMap, &args); err != nil {
	log.Fatal(err)
}

// Map the function name to the actual arithmetic function.
var result float64
switch functionCall.Name {
case "addNumbers":
	result = add(args.FirstParam, args.SecondParam)
case "subtractNumbers":
	result = subtract(args.FirstParam, args.SecondParam)
case "multiplyNumbers":
	result = multiply(args.FirstParam, args.SecondParam)
case "divideNumbers":
	result = divide(args.FirstParam, args.SecondParam)
default:
	return fmt.Errorf("unimplemented function: %s", functionCall.Name)
}
log.Printf("Function result: %v\n", result)

// Prepare the final result message as content.
resultContents := []*genai.Content{
	genai.NewContentFromText("The final result is "+fmt.Sprintf("%v", result), genai.RoleUser),
}

// Use GenerateContent to send the final result.
finalResponse, err := client.Models.GenerateContent(ctx, modelName, resultContents, &genai.GenerateContentConfig{})
if err != nil {
	log.Fatal(err)
}

printResponse(finalResponse)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

/**
 * The add function returns the sum of two numbers.
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function add(a, b) {
  return a + b;
}

/**
 * The subtract function returns the difference (a - b).
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function subtract(a, b) {
  return a - b;
}

/**
 * The multiply function returns the product of two numbers.
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function multiply(a, b) {
  return a * b;
}

/**
 * The divide function returns the quotient of a divided by b.
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function divide(a, b) {
  return a / b;
}

const addDeclaration = {
  name: 'addNumbers',
  parameters: {
    type: 'object',
    description: 'Return the result of adding two numbers.',
    properties: {
      firstParam: {
        type: 'number',
        description:
            'The first parameter which can be an integer or a floating point number.',
      },
      secondParam: {
        type: 'number',
        description:
            'The second parameter which can be an integer or a floating point number.',
      },
    },
    required: ['firstParam', 'secondParam'],
  },
};

const subtractDeclaration = {
  name: 'subtractNumbers',
  parameters: {
    type: 'object',
    description:
        'Return the result of subtracting the second number from the first.',
    properties: {
      firstParam: {
        type: 'number',
        description: 'The first parameter.',
      },
      secondParam: {
        type: 'number',
        description: 'The second parameter.',
      },
    },
    required: ['firstParam', 'secondParam'],
  },
};

const multiplyDeclaration = {
  name: 'multiplyNumbers',
  parameters: {
    type: 'object',
    description: 'Return the product of two numbers.',
    properties: {
      firstParam: {
        type: 'number',
        description: 'The first parameter.',
      },
      secondParam: {
        type: 'number',
        description: 'The second parameter.',
      },
    },
    required: ['firstParam', 'secondParam'],
  },
};

const divideDeclaration = {
  name: 'divideNumbers',
  parameters: {
    type: 'object',
    description:
        'Return the quotient of dividing the first number by the second.',
    properties: {
      firstParam: {
        type: 'number',
        description: 'The first parameter.',
      },
      secondParam: {
        type: 'number',
        description: 'The second parameter.',
      },
    },
    required: ['firstParam', 'secondParam'],
  },
};

// Step 1: Call generateContent with function calling enabled.
const generateContentResponse = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents:
      'I have 57 cats, each owns 44 mittens, how many mittens is that in total?',
  config: {
    toolConfig: {
      functionCallingConfig: {
        mode: FunctionCallingConfigMode.ANY,
      },
    },
    tools: [
      {
        functionDeclarations: [
          addDeclaration,
          subtractDeclaration,
          multiplyDeclaration,
          divideDeclaration,
        ],
      },
    ],
  },
});

// Step 2: Extract the function call.(
// Assuming the response contains a 'functionCalls' array.
const functionCall = generateContentResponse.functionCalls &&
    generateContentResponse.functionCalls[0];
console.log(functionCall);

// Parse the arguments.
const args = functionCall.args;
// Expected args format: { firstParam: number, secondParam: number }

// Step 3: Invoke the actual function based on the function name.
const functionMapping = {
  addNumbers: add,
  subtractNumbers: subtract,
  multiplyNumbers: multiply,
  divideNumbers: divide,
};
const func = functionMapping[functionCall.name];
if (!func) {
  console.error('Unimplemented error:', functionCall.name);
  return generateContentResponse;
}
const resultValue = func(args.firstParam, args.secondParam);
console.log('Function result:', resultValue);

// Step 4: Use the chat API to send the result as the final answer.
const chat = ai.chats.create({model: 'gemini-3.8-flash'});
const chatResponse = await chat.sendMessage({
  message: 'The final result is ' + resultValue,
});
console.log(chatResponse.text);

貝殼


cat > tools.json << EOF
{
  "function_declarations": [
    {
      "name": "enable_lights",
      "description": "Turn on the lighting system."
    },
    {
      "name": "set_light_color",
      "description": "Set the light color. Lights must be enabled for this to work.",
      "parameters": {
        "type": "object",
        "properties": {
          "rgb_hex": {
            "type": "string",
            "description": "The light color as a 6-digit hex string, e.g. ff0000 for red."
          }
        },
        "required": [
          "rgb_hex"
        ]
      }
    },
    {
      "name": "stop_lights",
      "description": "Turn off the lighting system."
    }
  ]
} 
EOF

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d @<(echo '
  {
    "system_instruction": {
      "parts": {
        "text": "You are a helpful lighting system bot. You can turn lights on and off, and you can set the color. Do not perform any other tasks."
      }
    },
    "tools": ['$(cat tools.json)'],

    "tool_config": {
      "function_calling_config": {"mode": "auto"}
    },

    "contents": {
      "role": "user",
      "parts": {
        "text": "Turn on the lights please."
      }
    }
  }
') 2>/dev/null |sed -n '/"content"/,/"finishReason"/p'

Java

Client client = new Client();

FunctionDeclaration addFunction =
    FunctionDeclaration.builder()
        .name("addNumbers")
        .parameters(
            Schema.builder()
                .type("object")
                .properties(
                    Map.of(
                        "firstParam",
                            Schema.builder().type("number").description("First number").build(),
                        "secondParam",
                            Schema.builder()
                                .type("number")
                                .description("Second number")
                                .build()))
                .required(Arrays.asList("firstParam", "secondParam"))
                .build())
        .build();

FunctionDeclaration subtractFunction =
    FunctionDeclaration.builder()
        .name("subtractNumbers")
        .parameters(
            Schema.builder()
                .type("object")
                .properties(
                    Map.of(
                        "firstParam",
                            Schema.builder().type("number").description("First number").build(),
                        "secondParam",
                            Schema.builder()
                                .type("number")
                                .description("Second number")
                                .build()))
                .required(Arrays.asList("firstParam", "secondParam"))
                .build())
        .build();

FunctionDeclaration multiplyFunction =
    FunctionDeclaration.builder()
        .name("multiplyNumbers")
        .parameters(
            Schema.builder()
                .type("object")
                .properties(
                    Map.of(
                        "firstParam",
                            Schema.builder().type("number").description("First number").build(),
                        "secondParam",
                            Schema.builder()
                                .type("number")
                                .description("Second number")
                                .build()))
                .required(Arrays.asList("firstParam", "secondParam"))
                .build())
        .build();

FunctionDeclaration divideFunction =
    FunctionDeclaration.builder()
        .name("divideNumbers")
        .parameters(
            Schema.builder()
                .type("object")
                .properties(
                    Map.of(
                        "firstParam",
                            Schema.builder().type("number").description("First number").build(),
                        "secondParam",
                            Schema.builder()
                                .type("number")
                                .description("Second number")
                                .build()))
                .required(Arrays.asList("firstParam", "secondParam"))
                .build())
        .build();

GenerateContentConfig config =
    GenerateContentConfig.builder()
        .toolConfig(
            ToolConfig.builder()
                .functionCallingConfig(FunctionCallingConfig.builder().mode("ANY").build())
                .build())
        .tools(
            Collections.singletonList(
                Tool.builder()
                    .functionDeclarations(
                        Arrays.asList(
                            addFunction, subtractFunction, divideFunction, multiplyFunction))
                    .build()))
        .build();

GenerateContentResponse response =
    client.models.generateContent(
        "gemini-3.8-flash",
        "I have 57 cats, each owns 44 mittens, how many mittens is that in total?",
        config);

if (response.functionCalls() == null || response.functionCalls().isEmpty()) {
  System.err.println("No function call received");
  return null;
}

var functionCall = response.functionCalls().getFirst();
String functionName = functionCall.name().get();
var arguments = functionCall.args();

Map<String, BiFunction<Double, Double, Double>> functionMapping = new HashMap<>();
functionMapping.put("addNumbers", (a, b) -> a + b);
functionMapping.put("subtractNumbers", (a, b) -> a - b);
functionMapping.put("multiplyNumbers", (a, b) -> a * b);
functionMapping.put("divideNumbers", (a, b) -> b != 0 ? a / b : Double.NaN);

BiFunction<Double, Double, Double> function = functionMapping.get(functionName);

Number firstParam = (Number) arguments.get().get("firstParam");
Number secondParam = (Number) arguments.get().get("secondParam");
Double result = function.apply(firstParam.doubleValue(), secondParam.doubleValue());

System.out.println(result);

生成設定

Python

from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Tell me a story about a magic backpack.",
    config=types.GenerateContentConfig(
        candidate_count=1,
        stop_sequences=["x"],
        max_output_tokens=20,
        temperature=1.0,
    ),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: 'Tell me a story about a magic backpack.',
  config: {
    candidateCount: 1,
    stopSequences: ['x'],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

console.log(response.text);

Go

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

// Create local variables for parameters.
candidateCount := int32(1)
maxOutputTokens := int32(20)
temperature := float32(1.0)

response, err := client.Models.GenerateContent(
	ctx,
	"gemini-3.8-flash",
	genai.Text("Tell me a story about a magic backpack."),
	&genai.GenerateContentConfig{
		CandidateCount:  candidateCount,
		StopSequences:   []string{"x"},
		MaxOutputTokens: maxOutputTokens,
		Temperature:     &temperature,
	},
)
if err != nil {
	log.Fatal(err)
}

printResponse(response)

貝殼

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
        "contents": [{
            "parts":[
                {"text": "Explain how AI works"}
            ]
        }],
        "generationConfig": {
            "stopSequences": [
                "Title"
            ],
            "temperature": 1.0,
            "maxOutputTokens": 800,
            "topP": 0.8,
            "topK": 10
        }
    }'  2> /dev/null | grep "text"

Java

Client client = new Client();

GenerateContentConfig config =
    GenerateContentConfig.builder()
        .candidateCount(1)
        .stopSequences(List.of("x"))
        .maxOutputTokens(20)
        .temperature(1.0F)
        .build();

GenerateContentResponse response =
    client.models.generateContent(
        "gemini-3.8-flash", "Tell me a story about a magic backpack.", config);

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

安全性設定

Python

from google import genai
from google.genai import types

client = genai.Client()
unsafe_prompt = (
    "I support Martians Soccer Club and I think Jupiterians Football Club"
    " sucks! Write a ironic phrase about them including expletives."
)
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=unsafe_prompt,
    config=types.GenerateContentConfig(
        safety_settings=[
            types.SafetySetting(
                category="HARM_CATEGORY_HATE_SPEECH",
                threshold="BLOCK_MEDIUM_AND_ABOVE",
            ),
            types.SafetySetting(
                category="HARM_CATEGORY_HARASSMENT",
                threshold="BLOCK_ONLY_HIGH",
            ),
        ]
    ),
)
try:
  print(response.text)
except Exception:
  print("No information generated by the model.")

print(response.candidates[0].safety_ratings)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});
const unsafePrompt =
    'I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them including expletives.';

const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: unsafePrompt,
  config: {
    safetySettings: [
      {
        category: 'HARM_CATEGORY_HATE_SPEECH',
        threshold: 'BLOCK_MEDIUM_AND_ABOVE',
      },
      {
        category: 'HARM_CATEGORY_HARASSMENT',
        threshold: 'BLOCK_ONLY_HIGH',
      },
    ],
  },
});

try {
  console.log('Generated text:', response.text);
} catch (error) {
  console.log('No information generated by the model.');
}
console.log('Safety ratings:', response.candidates[0].safetyRatings);

Go

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

unsafePrompt := "I support Martians Soccer Club and I think Jupiterians Football Club sucks! " +
	"Write a ironic phrase about them including expletives."

config := &genai.GenerateContentConfig{
	SafetySettings: []*genai.SafetySetting{
		{
			Category:  "HARM_CATEGORY_HATE_SPEECH",
			Threshold: "BLOCK_MEDIUM_AND_ABOVE",
		},
		{
			Category:  "HARM_CATEGORY_HARASSMENT",
			Threshold: "BLOCK_ONLY_HIGH",
		},
	},
}
contents := []*genai.Content{
	genai.NewContentFromText(unsafePrompt, genai.RoleUser),
}
response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, config)
if err != nil {
	log.Fatal(err)
}

// Print the generated text.
text := response.Text()
fmt.Println("Generated text:", text)

// Print the and safety ratings from the first candidate.
if len(response.Candidates) > 0 {
	fmt.Println("Finish reason:", response.Candidates[0].FinishReason)
	safetyRatings, err := json.MarshalIndent(response.Candidates[0].SafetyRatings, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println("Safety ratings:", string(safetyRatings))
} else {
	fmt.Println("No candidate returned.")
}

貝殼

echo '{
    "safetySettings": [
        {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"},
        {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}
    ],
    "contents": [{
        "parts":[{
            "text": "'I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them.'"}]}]}' > request.json

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d @request.json 2> /dev/null

Java

Client client = new Client();

String unsafePrompt =
    """
     I support Martians Soccer Club and I think Jupiterians Football Club sucks!
     Write a ironic phrase about them including expletives.
    """;

GenerateContentConfig config =
    GenerateContentConfig.builder()
        .safetySettings(
            Arrays.asList(
                SafetySetting.builder()
                    .category("HARM_CATEGORY_HATE_SPEECH")
                    .threshold("BLOCK_MEDIUM_AND_ABOVE")
                    .build(),
                SafetySetting.builder()
                    .category("HARM_CATEGORY_HARASSMENT")
                    .threshold("BLOCK_ONLY_HIGH")
                    .build()))
        .build();

GenerateContentResponse response =
    client.models.generateContent("gemini-3.8-flash", unsafePrompt, config);

try {
  System.out.println(response.text());
} catch (Exception e) {
  System.out.println("No information generated by the model");
}

System.out.println(response.candidates().get().getFirst().safetyRatings());

系統指令

Python

from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Good morning! How are you?",
    config=types.GenerateContentConfig(
        system_instruction="You are a cat. Your name is Neko."
    ),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});
const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: 'Good morning! How are you?',
  config: {
    systemInstruction: 'You are a cat. Your name is Neko.',
  },
});
console.log(response.text);

Go

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

// Construct the user message contents.
contents := []*genai.Content{
	genai.NewContentFromText("Good morning! How are you?", genai.RoleUser),
}

// Set the system instruction as a *genai.Content.
config := &genai.GenerateContentConfig{
	SystemInstruction: genai.NewContentFromText("You are a cat. Your name is Neko.", genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, config)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

貝殼

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "system_instruction": {
    "parts":
      { "text": "You are a cat. Your name is Neko."}},
    "contents": {
      "parts": {
        "text": "Hello there"}}}'

Java

Client client = new Client();

Part textPart = Part.builder().text("You are a cat. Your name is Neko.").build();

Content content = Content.builder().role("system").parts(ImmutableList.of(textPart)).build();

GenerateContentConfig config =
    GenerateContentConfig.builder().systemInstruction(content).build();

GenerateContentResponse response =
    client.models.generateContent("gemini-3.8-flash", "Good morning! How are you?", config);

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

回應主體

如果成功,回應主體會包含 GenerateContentResponse 的執行個體。

方法:models.streamGenerateContent

根據輸入的 GenerateContentRequest,從模型生成串流回覆。

端點

貼文 https://generativelanguage.googleapis.com/v1beta/{model=models/*}:streamGenerateContent

路徑參數

model string

必填。要用來生成補全內容的Model名稱。

格式:models/{model}。格式為 models/{model}。

要求主體

要求主體會包含結構如下的資料:

欄位
contents[] object (Content)

必填。與模型目前對話的內容。

如果是單輪查詢,這會是單一執行個體。如果是 chat 等多輪查詢,這個重複欄位會包含對話記錄和最新要求。

tools[] object (Tool)

(選用步驟) Model 可能會用來生成下一個回覆的Tools清單。

Tool是一段程式碼,可讓系統與外部系統互動,執行 Model 知識和範圍以外的一或多項動作。支援的 Tool 為 Function 和 codeExecution。詳情請參閱呼叫函式和執行程式碼指南。

toolConfig object (ToolConfig)

(選用步驟) 要求中指定的任何 Tool 工具設定。如需使用範例,請參閱函式呼叫指南。

safetySettings[] object (SafetySetting)

(選用步驟) 用於封鎖不安全內容的不重複 SafetySetting 執行個體清單。

這項規定將於 GenerateContentRequest.contents和GenerateContentResponse.candidates強制執行。每個 SafetyCategory 類型不應有多個設定。API 會封鎖不符合這些設定門檻的內容和回覆。這份清單會覆寫 safetySettings 中指定的每個 SafetyCategory 預設設定。如果清單中未提供特定 SafetyCategory 的 SafetySetting,API 會使用該類別的預設安全設定。支援的危害類別包括 HARM_CATEGORY_HATE_SPEECH、HARM_CATEGORY_SEXUALLY_EXPLICIT、HARM_CATEGORY_DANGEROUS_CONTENT、HARM_CATEGORY_HARASSMENT、HARM_CATEGORY_CIVIC_INTEGRITY、HARM_CATEGORY_JAILBREAK。如要進一步瞭解可用的安全設定,請參閱指南。另請參閱安全指南,瞭解如何在 AI 應用程式中納入安全考量。

continuationToken string (bytes format)

(選用步驟) 不透明的接續權杖,用於從先前的 models.generateContent 或 models.streamGenerateContent 回應繼續生成,該回應在 finishReason 設為 CONTINUATION 時停止。請注意,contents 為必填欄位,且在要求中提供接續權杖時,必須與初始要求中的提示和對話記錄完全相同。

Base64 編碼字串。

labels map (key: string, value: string)

(選用步驟) 要求的使用者定義中繼資料標籤。

(選用步驟) 標籤必須符合標準統一 Cloud 標籤規定:- 標籤鍵開頭須為英文字母。- 標籤鍵和值的長度不得超過 63 個字元 (Unicode 碼點),且只能包含小寫英文字母、數字、底線和破折號。- 可以使用國際字元。

用法:- 來自集結網站的安全 ID:使用 safety_identifier 鍵 (例如 {"safety_identifier": "user_session_123"})

這個物件中包含 "key": value 組合的清單,範例:{ "name": "wrench", "mass": "1.3kg", "count": "3" }。

systemInstruction object (Content)

(選用步驟) 開發人員設定的系統指令。目前僅支援文字。

generationConfig object (GenerationConfig)

(選用步驟) 模型生成和輸出的設定選項。

cachedContent string

(選用步驟) 快取內容的名稱,用於提供預測結果。格式:cachedContents/{cachedContent}

serviceTier enum (ServiceTier)

(選用步驟) 要求的服務層級。

store boolean

(選用步驟) 設定特定要求的記錄行為。如果設定,則優先順序高於專案層級的記錄設定。

要求範例

文字

Python

from google import genai

client = genai.Client()
response = client.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents="Write a story about a magic backpack.",
)
for chunk in response:
  print(chunk.text)
  print("_" * 80)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

const response = await ai.models.generateContentStream({
  model: 'gemini-3.8-flash',
  contents: 'Write a story about a magic backpack.',
});
let text = '';
for await (const chunk of response) {
  console.log(chunk.text);
  text += chunk.text;
}

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
contents := []*genai.Content{
	genai.NewContentFromText("Write a story about a magic backpack.", genai.RoleUser),
}
for response, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-3.8-flash",
	contents,
	nil,
) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(response.Candidates[0].Content.Parts[0].Text)
}

貝殼

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \
        -H 'Content-Type: application/json' \
        --no-buffer \
        -d '{ "contents":[{"parts":[{"text": "Write a story about a magic backpack."}]}]}'

Java

Client client = new Client();

ResponseStream<GenerateContentResponse> responseStream =
    client.models.generateContentStream(
        "gemini-3.8-flash", "Write a story about a magic backpack.", null);

StringBuilder response = new StringBuilder();
for (GenerateContentResponse res : responseStream) {
  System.out.print(res.text());
  response.append(res.text());
}

responseStream.close();

圖片

Python

from google import genai
import PIL.Image

client = genai.Client()
organ = PIL.Image.open(media / "organ.jpg")
response = client.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents=["Tell me about this instrument", organ],
)
for chunk in response:
  print(chunk.text)
  print("_" * 80)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

const organ = await ai.files.upload({
  file: path.join(media, 'organ.jpg'),
});

const response = await ai.models.generateContentStream({
  model: 'gemini-3.8-flash',
  contents: [
    createUserContent([
      'Tell me about this instrument',
      createPartFromUri(organ.uri, organ.mimeType)
    ]),
  ],
});
let text = '';
for await (const chunk of response) {
  console.log(chunk.text);
  text += chunk.text;
}

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
file, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "organ.jpg"),
	&genai.UploadFileConfig{
		MIMEType: "image/jpeg",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromText("Tell me about this instrument"),
	genai.NewPartFromURI(file.URI, file.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}
for response, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-3.8-flash",
	contents,
	nil,
) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(response.Candidates[0].Content.Parts[0].Text)
}

貝殼

cat > "$TEMP_JSON" << EOF
{
  "contents": [{
    "parts":[
      {"text": "Tell me about this instrument"},
      {
        "inline_data": {
          "mime_type":"image/jpeg",
          "data": "$(cat "$TEMP_B64")"
        }
      }
    ]
  }]
}
EOF

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d "@$TEMP_JSON" 2> /dev/null

Java

Client client = new Client();

String path = media_path + "organ.jpg";
byte[] imageData = Files.readAllBytes(Paths.get(path));

Content content =
    Content.fromParts(
        Part.fromText("Tell me about this instrument."),
        Part.fromBytes(imageData, "image/jpeg"));

ResponseStream<GenerateContentResponse> responseStream =
    client.models.generateContentStream("gemini-3.8-flash", content, null);

StringBuilder response = new StringBuilder();
for (GenerateContentResponse res : responseStream) {
  System.out.print(res.text());
  response.append(res.text());
}

responseStream.close();

音訊

Python

from google import genai

client = genai.Client()
sample_audio = client.files.upload(file=media / "sample.mp3")
response = client.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
for chunk in response:
  print(chunk.text)
  print("_" * 80)

Go

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

file, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "sample.mp3"),
	&genai.UploadFileConfig{
		MIMEType: "audio/mpeg",
	},
)
if err != nil {
	log.Fatal(err)
}

parts := []*genai.Part{
	genai.NewPartFromText("Give me a summary of this audio file."),
	genai.NewPartFromURI(file.URI, file.MIMEType),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

for result, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-3.8-flash",
	contents,
	nil,
) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(result.Candidates[0].Content.Parts[0].Text)
}

貝殼

# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

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 "${BASE_URL}/upload/v1beta/files?key=${GEMINI_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 "@${AUDIO_PATH}" 2> /dev/null > file_info.json

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Please describe this file."},
          {"file_data":{"mime_type": "audio/mpeg", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

影片

Python

from google import genai
import time

client = genai.Client()
# Video clip (CC BY 3.0) from https://peach.blender.org/download/
myfile = client.files.upload(file=media / "Big_Buck_Bunny.mp4")
print(f"{myfile=}")

# Poll until the video file is completely processed (state becomes ACTIVE).
while not myfile.state or myfile.state.name != "ACTIVE":
  print("Processing video...")
  print("File state:", myfile.state)
  time.sleep(5)
  myfile = client.files.get(name=myfile.name)

response = client.models.generate_content_stream(
    model="gemini-3.8-flash", contents=[myfile, "Describe this video clip"]
)
for chunk in response:
  print(chunk.text)
  print("_" * 80)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

let video = await ai.files.upload({
  file: path.join(media, 'Big_Buck_Bunny.mp4'),
});

// Poll until the video file is completely processed (state becomes ACTIVE).
while (!video.state || video.state.toString() !== 'ACTIVE') {
  console.log('Processing video...');
  console.log('File state: ', video.state);
  await sleep(5000);
  video = await ai.files.get({name: video.name});
}

const response = await ai.models.generateContentStream({
  model: 'gemini-3.8-flash',
  contents: [
    createUserContent([
      'Describe this video clip',
      createPartFromUri(video.uri, video.mimeType),
    ]),
  ],
});
let text = '';
for await (const chunk of response) {
  console.log(chunk.text);
  text += chunk.text;
}

Go

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

file, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "Big_Buck_Bunny.mp4"),
	&genai.UploadFileConfig{
		MIMEType: "video/mp4",
	},
)
if err != nil {
	log.Fatal(err)
}

// Poll until the video file is completely processed (state becomes ACTIVE).
for file.State == genai.FileStateUnspecified || file.State != genai.FileStateActive {
	fmt.Println("Processing video...")
	fmt.Println("File state:", file.State)
	time.Sleep(5 * time.Second)

	file, err = client.Files.Get(ctx, file.Name, nil)
	if err != nil {
		log.Fatal(err)
	}
}

parts := []*genai.Part{
	genai.NewPartFromText("Describe this video clip"),
	genai.NewPartFromURI(file.URI, file.MIMEType),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

for result, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-3.8-flash",
	contents,
	nil,
) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(result.Candidates[0].Content.Parts[0].Text)
}

貝殼

# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${VIDEO_PATH}")
NUM_BYTES=$(wc -c < "${VIDEO_PATH}")
DISPLAY_NAME=VIDEO_PATH

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GEMINI_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 "@${VIDEO_PATH}" 2> /dev/null > file_info.json

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

state=$(jq ".file.state" file_info.json)
echo state=$state

while [[ "($state)" = *"PROCESSING"* ]];
do
  echo "Processing video..."
  sleep 5
  # Get the file of interest to check state
  curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
  state=$(jq ".file.state" file_info.json)
done

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Please describe this file."},
          {"file_data":{"mime_type": "video/mp4", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

PDF

Python

from google import genai

client = genai.Client()
sample_pdf = client.files.upload(file=media / "test.pdf")
response = client.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents=["Give me a summary of this document:", sample_pdf],
)

for chunk in response:
  print(chunk.text)
  print("_" * 80)

Go

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

file, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "test.pdf"),
	&genai.UploadFileConfig{
		MIMEType: "application/pdf",
	},
)
if err != nil {
	log.Fatal(err)
}

parts := []*genai.Part{
	genai.NewPartFromText("Give me a summary of this document:"),
	genai.NewPartFromURI(file.URI, file.MIMEType),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

for result, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-3.8-flash",
	contents,
	nil,
) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(result.Candidates[0].Content.Parts[0].Text)
}

貝殼

MIME_TYPE=$(file -b --mime-type "${PDF_PATH}")
NUM_BYTES=$(wc -c < "${PDF_PATH}")
DISPLAY_NAME=TEXT


echo $MIME_TYPE
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 "${BASE_URL}/upload/v1beta/files?key=${GEMINI_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 "@${PDF_PATH}" 2> /dev/null > file_info.json

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

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Can you add a few more lines to this poem?"},
          {"file_data":{"mime_type": "application/pdf", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

即時通訊

Python

from google import genai
from google.genai import types

client = genai.Client()
chat = client.chats.create(
    model="gemini-3.8-flash",
    history=[
        types.Content(role="user", parts=[types.Part(text="Hello")]),
        types.Content(
            role="model",
            parts=[
                types.Part(
                    text="Great to meet you. What would you like to know?"
                )
            ],
        ),
    ],
)
response = chat.send_message_stream(message="I have 2 dogs in my house.")
for chunk in response:
  print(chunk.text)
  print("_" * 80)
response = chat.send_message_stream(
    message="How many paws are in my house?"
)
for chunk in response:
  print(chunk.text)
  print("_" * 80)

print(chat.get_history())

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});
const chat = ai.chats.create({
  model: 'gemini-3.8-flash',
  history: [
    {
      role: 'user',
      parts: [{text: 'Hello'}],
    },
    {
      role: 'model',
      parts: [{text: 'Great to meet you. What would you like to know?'}],
    },
  ],
});

console.log('Streaming response for first message:');
const stream1 = await chat.sendMessageStream({
  message: 'I have 2 dogs in my house.',
});
for await (const chunk of stream1) {
  console.log(chunk.text);
  console.log('_'.repeat(80));
}

console.log('Streaming response for second message:');
const stream2 = await chat.sendMessageStream({
  message: 'How many paws are in my house?',
});
for await (const chunk of stream2) {
  console.log(chunk.text);
  console.log('_'.repeat(80));
}

console.log(chat.getHistory());

Go

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

history := []*genai.Content{
	genai.NewContentFromText("Hello", genai.RoleUser),
	genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),
}
chat, err := client.Chats.Create(ctx, "gemini-3.8-flash", nil, history)
if err != nil {
	log.Fatal(err)
}

for chunk, err := range chat.SendMessageStream(ctx, genai.Part{Text: "I have 2 dogs in my house."}) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(chunk.Text())
	fmt.Println(strings.Repeat("_", 64))
}

for chunk, err := range chat.SendMessageStream(ctx, genai.Part{Text: "How many paws are in my house?"}) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(chunk.Text())
	fmt.Println(strings.Repeat("_", 64))
}

fmt.Println(chat.History(false))

貝殼

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role":"user",
         "parts":[{
           "text": "Hello"}]},
        {"role": "model",
         "parts":[{
           "text": "Great to meet you. What would you like to know?"}]},
        {"role":"user",
         "parts":[{
           "text": "I have two dogs in my house. How many paws are in my house?"}]},
      ]
    }' 2> /dev/null | grep "text"

回應主體

如果成功,回應主體會包含 GenerateContentResponse 執行個體串流。

GenerateContentResponse

模型的回覆,支援多個候選回覆。

系統會針對 GenerateContentResponse.prompt_feedback 中的提示,以及 finishReason 和 safetyRatings 中的每個候選項目,回報安全評分和內容篩選結果。API:- 傳回所有要求的候選項目或不傳回任何候選項目 - 只有在提示有問題時,才不會傳回任何候選項目 (請查看 promptFeedback) - 針對 finishReason 和 safetyRatings 中的每個候選項目回報意見回饋。

欄位
candidates[] object (Candidate)

模型提供的候選回覆。

promptFeedback object (PromptFeedback)

傳回與內容篩選器相關的提示意見回饋。

usageMetadata object (UsageMetadata)

僅供輸出。生成要求詞元用量的中繼資料。

modelVersion string

僅供輸出。用於生成回覆的模型版本。

responseId string

僅供輸出。responseId 用於識別各個回應。

modelStatus object (ModelStatus)

僅供輸出。這個模型的目前狀態。

JSON 表示法
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string,
  "responseId": string,
  "modelStatus": {
    object (ModelStatus)
  }
}

PromptFeedback

GenerateContentRequest.content 中指定的提示詞意見回饋中繼資料。

欄位
blockReason enum (BlockReason)

(選用步驟) 如果設定,提示會遭到封鎖,且不會傳回任何候選項目。改寫提示。

safetyRatings[] object (SafetyRating)

提示詞的安全評分。每個類別最多只能有一個評分。

JSON 表示法
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

BlockReason

說明提示遭封鎖的原因。

列舉
BLOCK_REASON_UNSPECIFIED 預設值。這個值不會用到。
SAFETY 基於安全考量,系統已封鎖提示詞。檢查 safetyRatings,瞭解遭到封鎖的原因。
OTHER 提示詞因不明原因遭到封鎖。
BLOCKLIST 提示詞含有術語封鎖清單中的字詞,因此遭到封鎖。
PROHIBITED_CONTENT 提示詞含有禁止宣傳的內容,因此遭到封鎖。
IMAGE_SAFETY 候選項目因含有不安全的圖像生成內容而遭封鎖。

UsageMetadata

生成要求權杖用量的中繼資料。

欄位
promptTokenCount integer

提示中的詞元數量。設定 cachedContent 時,這仍是有效提示總大小,也就是包含快取內容中的詞元數量。

cachedContentTokenCount integer

提示快取部分 (快取內容) 的詞元數量

candidatesTokenCount integer

所有生成的回覆候選項目中的詞元總數。

toolUsePromptTokenCount integer

僅供輸出。工具使用提示中的詞元數量。

thoughtsTokenCount integer

僅供輸出。思考模型的思考詞元數量。

totalTokenCount integer

生成要求的詞元總數 (提示 + 工具使用提示 + 思考 + 候選回覆)。

promptTokensDetails[] object (ModalityTokenCount)

僅供輸出。要求輸入內容中處理的模態清單。

cacheTokensDetails[] object (ModalityTokenCount)

僅供輸出。要求輸入內容中快取內容的模態清單。

candidatesTokensDetails[] object (ModalityTokenCount)

僅供輸出。回應中傳回的模態清單。

toolUsePromptTokensDetails[] object (ModalityTokenCount)

僅供輸出。處理工具使用要求輸入內容時,所採用的模態清單。

serviceTier enum (ServiceTier)

僅供輸出。要求的服務級別。

JSON 表示法
{
  "promptTokenCount": integer,
  "cachedContentTokenCount": integer,
  "candidatesTokenCount": integer,
  "toolUsePromptTokenCount": integer,
  "thoughtsTokenCount": integer,
  "totalTokenCount": integer,
  "promptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "cacheTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "candidatesTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "toolUsePromptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "serviceTier": enum (ServiceTier)
}

ModelStatus

底層模型的狀態。這項資訊用於指出基礎模型的階段,以及淘汰時間 (如適用)。

欄位
modelStage enum (ModelStage)

基礎模型的階段。

retirementTime string (Timestamp format)

模型停用時間。

使用 RFC 3339,產生的輸出內容一律會經過 Z 正規化,並使用 0、3、6 或 9 個小數位數,也接受「Z」以外的偏移量。範例:"2014-10-02T15:01:23Z"、"2014-10-02T15:01:23.045123456Z" 或 "2014-10-02T15:01:23+05:30"。

message string

說明模型狀態的訊息。

JSON 表示法
{
  "modelStage": enum (ModelStage),
  "retirementTime": string,
  "message": string
}

ModelStage

定義基礎模型的階段。

列舉
MODEL_STAGE_UNSPECIFIED 未指定模型階段。
UNSTABLE_EXPERIMENTAL

基礎模型會經過多次調整。

EXPERIMENTAL 這個階段的模型僅供實驗。
PREVIEW 這個階段的模型比實驗模型更成熟。
STABLE 這個階段的模型已穩定,可投入正式環境。
LEGACY 如果模型處於這個階段,表示模型即將淘汰。只有現有客戶可以使用這個模型。
DEPRECATED

這個階段的模型已淘汰。無法使用這些模型。

RETIRED 這個階段的模型已停用。無法使用這些模型。

候選人

模型生成的回覆候選。

欄位
content object (Content)

僅供輸出。模型傳回的生成內容。

finishReason enum (FinishReason)

(選用步驟) 僅供輸出。模型停止生成詞元的原因。

如果空白,表示模型尚未停止生成權杖。

safetyRatings[] object (SafetyRating)

候選回覆的安全評分清單。

每個類別最多只能有一個評分。

citationMetadata object (CitationMetadata)

僅供輸出。模型生成候選項目的引用資訊。

這個欄位可能會填入 content 中任何文字的背誦資訊。這些段落是從基礎 LLM 訓練資料中的著作權內容「背誦」而來。

tokenCount integer

僅供輸出。這個候選項目的詞元數量。

groundingAttributions[] object (GroundingAttribution)

僅供輸出。提供基準答案的來源歸因資訊。

系統會為 GenerateAnswer 呼叫填入這個欄位。

groundingMetadata object (GroundingMetadata)

僅供輸出。候選項目的基準中繼資料。

GenerateContent 呼叫會填入這個欄位。

avgLogprobs number

僅供輸出。候選回覆的平均對數機率分數。

logprobsResult object (LogprobsResult)

僅供輸出。回覆詞元和熱門詞元的對數可能性分數

urlContextMetadata object (UrlContextMetadata)

僅供輸出。網址背景資訊檢索工具相關中繼資料。

continuationToken string (bytes format)

當 finishReason 為 CONTINUATION 時,系統會傳回選用的不透明接續權杖。用戶端可以在後續的 GenerateContentRequest 中傳遞這個權杖,繼續生成內容。

Base64 編碼字串。

index integer

僅供輸出。回覆候選項目清單中的候選項目索引。

finishMessage string

(選用步驟) 僅供輸出。詳細說明模型停止生成權杖的原因。只有在設定 finishReason 時,系統才會填入這個值。

JSON 表示法
{
  "content": {
    object (Content)
  },
  "finishReason": enum (FinishReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ],
  "citationMetadata": {
    object (CitationMetadata)
  },
  "tokenCount": integer,
  "groundingAttributions": [
    {
      object (GroundingAttribution)
    }
  ],
  "groundingMetadata": {
    object (GroundingMetadata)
  },
  "avgLogprobs": number,
  "logprobsResult": {
    object (LogprobsResult)
  },
  "urlContextMetadata": {
    object (UrlContextMetadata)
  },
  "continuationToken": string,
  "index": integer,
  "finishMessage": string
}

FinishReason

定義模型停止生成權杖的原因。

列舉
FINISH_REASON_UNSPECIFIED 預設值。這個值不會用到。
STOP 模型的自然停止點或提供的停止序列。
MAX_TOKENS 已達要求中指定的權杖數量上限。
SAFETY 基於安全考量,系統已標記候選回覆內容。
RECITATION 候選回覆內容因背誦原因而遭到標記。
LANGUAGE 回覆候選內容因使用不支援的語言而遭標記。
OTHER 原因不明。
BLOCKLIST 內容含有禁止使用的字詞,因此系統已停止生成權杖。
PROHIBITED_CONTENT 系統可能生成了禁止宣傳的內容,因此已停止生成詞元。
SPII 內容可能含有具敏感性的個人識別資訊 (SPII),因此已停止生成權杖。
MALFORMED_FUNCTION_CALL 模型生成的函式呼叫無效。
IMAGE_SAFETY 生成的圖像違反安全規定,因此停止生成權杖。
IMAGE_PROHIBITED_CONTENT 生成的圖像含有其他禁止內容,因此停止生成圖像。
IMAGE_OTHER 因其他問題而停止生成圖像。
NO_IMAGE 模型應生成圖片卻未生成。
IMAGE_RECITATION 圖像生成作業因背誦而停止。
UNEXPECTED_TOOL_CALL 模型產生了工具呼叫,但要求中未啟用任何工具。
TOO_MANY_TOOL_CALLS 模型連續呼叫太多工具,因此系統已退出執行作業。
MISSING_THOUGHT_SIGNATURE 要求至少缺少一個思考簽章。
MALFORMED_RESPONSE 因回應格式有誤而結束。
ESCALATION 要求已由提報規則篩除。
PUP_LIMITED_DISABLED 表示使用者帳戶因違反《使用限制政策》(PUP) 而受限或停用,因此系統停止產生權杖。
CONTINUATION 回覆內容已達單次要求的分詞數量上限,但尚未生成完畢,因此系統已停止生成分詞。您可以使用傳回的 continuationToken 傳送後續要求,繼續生成模型回覆。請注意,maxOutputTokens 會在接續躍點中累計,且必須單調遞增或省略。

GroundingAttribution

提供答案的來源出處。

欄位
sourceId object (AttributionSourceId)

僅供輸出。促成這項歸因的來源 ID。

content object (Content)

構成這項歸因的基準來源內容。

JSON 表示法
{
  "sourceId": {
    object (AttributionSourceId)
  },
  "content": {
    object (Content)
  }
}

AttributionSourceId

促成這項歸因的來源 ID。

欄位
source Union type
以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
groundingPassage object (GroundingPassageId)

內嵌段落的 ID。

semanticRetrieverChunk object (SemanticRetrieverChunk)

透過語意檢索器擷取的 Chunk ID。

互斥欄位結束。
JSON 表示法
{

  // source
  "groundingPassage": {
    object (GroundingPassageId)
  },
  "semanticRetrieverChunk": {
    object (SemanticRetrieverChunk)
  }
  // Union type
}

GroundingPassageId

GroundingPassage 內某個部分的 ID。

欄位
passageId string

僅供輸出。與 GenerateAnswerRequest 的 GroundingPassage.id 相符的段落 ID。

partIndex integer

僅供輸出。GenerateAnswerRequest 的 GroundingPassage.content 中部分的索引。

JSON 表示法
{
  "passageId": string,
  "partIndex": integer
}

SemanticRetrieverChunk

透過 GenerateAnswerRequest 中指定的語意檢索器,使用 SemanticRetrieverConfig 擷取的 Chunk ID。

欄位
source string

僅供輸出。與要求 SemanticRetrieverConfig.source 相符的來源名稱。例如:corpora/123 或 corpora/123/documents/abc

chunk string

僅供輸出。包含作者資訊文字的 Chunk 名稱。範例:corpora/123/documents/abc/chunks/xyz

JSON 表示法
{
  "source": string,
  "chunk": string
}

GroundingMetadata

啟用基準建立功能時,傳回用戶端的中繼資料。

欄位
groundingChunks[] object (GroundingChunk)

從指定基準來源擷取的佐證參考資料清單。串流時,這項資訊只會包含先前回應的基準中繼資料未納入的基準資訊塊。

groundingSupports[] object (GroundingSupport)

基準建立支援清單。

webSearchQueries[] string

後續網頁搜尋的網頁搜尋查詢。

imageSearchQueries[] string

用於建立基準的圖片搜尋查詢。

searchEntryPoint object (SearchEntryPoint)

(選用步驟) Google 搜尋項目,用於後續網頁搜尋。

retrievalMetadata object (RetrievalMetadata)

與建立基準流程中檢索作業相關的中繼資料。

googleMapsWidgetContextToken string

(選用步驟) Google 地圖小工具上下文詞元的資源名稱,可與 PlacesContextElement 小工具搭配使用,算繪比對內容資料。只有在啟用「利用 Google 地圖建立基準」時,才會填入這個欄位。

JSON 表示法
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "imageSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  },
  "googleMapsWidgetContextToken": string
}

SearchEntryPoint

Google 搜尋進入點。

欄位
renderedContent string

(選用步驟) 可嵌入網頁或應用程式 WebView 的網路內容程式碼片段。

sdkBlob string (bytes format)

(選用步驟) Base64 編碼的 JSON,代表 <搜尋字詞, 搜尋網址> 元組陣列。

Base64 編碼字串。

JSON 表示法
{
  "renderedContent": string,
  "sdkBlob": string
}

GroundingChunk

GroundingChunk 代表佐證模型回覆的證據片段。例如網路上的文字片段、從檔案擷取的內容,或 Google 地圖中的資訊。

欄位
chunk_type Union type
區塊類型。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
web object (Web)

網路上的基準資訊塊。

image object (Image)

(選用步驟) 圖片搜尋的基準資訊區塊。

retrievedContext object (RetrievedContext)

(選用步驟) 檔案搜尋工具擷取的內容中,用於建立基準的文字片段。

maps object (Maps)

(選用步驟) Google 地圖的基準資訊區塊。

互斥欄位結束。
JSON 表示法
{

  // chunk_type
  "web": {
    object (Web)
  },
  "image": {
    object (Image)
  },
  "retrievedContext": {
    object (RetrievedContext)
  },
  "maps": {
    object (Maps)
  }
  // Union type
}

網頁

網路上的文字片段。

欄位
uri string

僅供輸出。區塊的 URI 參照。

title string

僅供輸出。區塊標題。

JSON 表示法
{
  "uri": string,
  "title": string
}

圖片

圖片搜尋結果中的片段。

欄位
sourceUri string

歸因的網頁 URI。

imageUri string

圖片素材資源網址。

title string

圖片來源網頁的標題。

domain string

圖片來源網頁的根網域,例如「example.com」。

JSON 表示法
{
  "sourceUri": string,
  "imageUri": string,
  "title": string,
  "domain": string
}

RetrievedContext

檔案搜尋工具擷取的背景資訊片段。

欄位
customMetadata[] object (CustomMetadata)

(選用步驟) 使用者提供的檢索內容中繼資料。

uri string

(選用步驟) 語意檢索文件的 URI 參照。

title string

(選用步驟) 文件標題。

text string

(選用步驟) 區塊的文字。

fileSearchStore string

(選用步驟) 包含文件的 FileSearchStore 名稱。範例:fileSearchStores/123

pageNumber integer

(選用步驟) 所擷取內容的頁碼 (如適用)。

mediaId string

(選用步驟) 多模態檔案搜尋結果的媒體 blob 資源名稱。格式:fileSearchStores/{file_search_store_id}/media/{blobId}

JSON 表示法
{
  "customMetadata": [
    {
      object (CustomMetadata)
    }
  ],
  "uri": string,
  "title": string,
  "text": string,
  "fileSearchStore": string,
  "pageNumber": integer,
  "mediaId": string
}

CustomMetadata

使用者提供的 GroundingFact 中繼資料。

欄位
key string

中繼資料的鍵。

value Union type
中繼資料的值。可以是字串、字串清單或數字。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
stringValue string

(選用步驟) 中繼資料的字串值。

stringListValue object (StringList)

(選用步驟) 中繼資料的字串值清單。

numericValue number

(選用步驟) 中繼資料的數值。這個值的預期範圍取決於使用的特定 key。

互斥欄位結束。
JSON 表示法
{
  "key": string,

  // value
  "stringValue": string,
  "stringListValue": {
    object (StringList)
  },
  "numericValue": number
  // Union type
}

StringList

字串值清單。

欄位
values[] string

清單的字串值。

JSON 表示法
{
  "values": [
    string
  ]
}

地圖

Google 地圖的基準資訊塊。一個地圖區塊對應一個地點。

欄位
uri string

地點的 URI 參照。

title string

地點名稱。

text string

地點答案的文字說明。

placeId string

地點 ID,格式為 places/{placeId}。使用者可以透過這個 ID 查詢該地點。

placeAnswerSources object (PlaceAnswerSources)

在 Google 地圖中,提供特定地點相關資訊的來源。

JSON 表示法
{
  "uri": string,
  "title": string,
  "text": string,
  "placeId": string,
  "placeAnswerSources": {
    object (PlaceAnswerSources)
  }
}

PlaceAnswerSources

這組來源提供 Google 地圖中特定地點的特色資訊。每則 PlaceAnswerSources 訊息都對應 Google 地圖中的特定地點。Google 地圖工具會使用這些來源,回答有關地點特色的問題 (例如「Foo 酒吧有 Wi-Fi 嗎?」或「Foo Bar 有無障礙設施嗎?」)。目前我們僅支援評論摘錄做為來源。

欄位
reviewSnippets[] object (ReviewSnippet)

Google 地圖會使用評論摘要,生成特定地點特色的相關答案。

JSON 表示法
{
  "reviewSnippets": [
    {
      object (ReviewSnippet)
    }
  ]
}

ReviewSnippet

封裝使用者評論摘要,回答 Google 地圖中特定地點功能的問題。

欄位
reviewId string

評論摘錄的 ID。

googleMapsUri string

Google 地圖上使用者評論的對應連結。

title string

評論標題。

JSON 表示法
{
  "reviewId": string,
  "googleMapsUri": string,
  "title": string
}

GroundingSupport

基準建立支援。

欄位
groundingChunkIndices[] integer

(選用步驟) 索引清單 (response.candidate.grounding_metadata 中的「grounding_chunk」),指定與聲明相關聯的引用來源。舉例來說,[1,3,4] 表示 grounding_chunk[1]、grounding_chunk[3]、grounding_chunk[4] 是歸因於聲明的檢索內容。如果回應是串流,groundingChunkIndices 會參照所有回應的索引。用戶端有責任從所有回覆中累積基準資訊塊 (同時維持相同順序)。

confidenceScores[] number

(選用步驟) 佐證參考資料的可信度分數。範圍介於 0 到 1。1 代表信心最高。這份清單的大小必須與 groundingChunkIndices 相同。

renderedParts[] integer

僅供輸出。候選內容 parts 欄位的索引。這些索引會指定哪些算繪部分與這個支援來源相關聯。

segment object (Segment)

這項支援所屬的內容區隔。

JSON 表示法
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "renderedParts": [
    integer
  ],
  "segment": {
    object (Segment)
  }
}

區隔

內容區隔。

欄位
partIndex integer

Part 物件在父項 Content 物件中的索引。

startIndex integer

指定 Part 的起始索引,以位元組為單位。從 Part 開頭算起的偏移量 (含),從零開始。

endIndex integer

指定 Part 的結束索引,以位元組為單位。從 Part 開頭算起的偏移量 (不含),從零開始。

text string

回應中與該片段對應的文字。

JSON 表示法
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

RetrievalMetadata

與建立基準流程中檢索作業相關的中繼資料。

欄位
googleSearchDynamicRetrievalScore number

(選用步驟) 這個分數代表 Google 搜尋資訊有助於回答提示的可能性。分數介於 [0, 1] 之間,0 表示可能性最低,1 表示可能性最高。只有在啟用 Google 搜尋基準建立和動態檢索功能時,系統才會填入這項分數。系統會將這個分數與門檻值比較,決定是否要觸發 Google 搜尋。

JSON 表示法
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

Logprobs 結果

欄位
topCandidates[] object (TopCandidates)

長度 = 解碼步驟總數。

chosenCandidates[] object (Candidate)

長度 = 解碼步驟總數。選定的候選項目不一定會出現在 topCandidates 中。

logProbabilitySum number

所有符記的對數機率總和。

JSON 表示法
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ],
  "logProbabilitySum": number
}

TopCandidates

在每個解碼步驟中,對數機率最高的候選項目。

欄位
candidates[] object (Candidate)

依記錄機率遞減排序。

JSON 表示法
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

候選人

logprobs 詞元和分數的候選項目。

欄位
token string

候選項目的詞元字串值。

tokenId integer

候選項目的詞元 ID 值。

logProbability number

候選詞的對數機率。

JSON 表示法
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

UrlContextMetadata

網址背景資訊擷取工具的相關中繼資料。

欄位
urlMetadata[] object (UrlMetadata)

網址背景資訊清單。

JSON 表示法
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}

UrlMetadata

單一網址擷取的背景資訊。

欄位
retrievedUrl string

工具擷取的網址。

urlRetrievalStatus enum (UrlRetrievalStatus)

網址擷取狀態。

JSON 表示法
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}

UrlRetrievalStatus

網址擷取狀態。

列舉
URL_RETRIEVAL_STATUS_UNSPECIFIED 預設值。這個值不會用到。
URL_RETRIEVAL_STATUS_SUCCESS 成功擷取網址。
URL_RETRIEVAL_STATUS_ERROR 發生錯誤,無法擷取網址。
URL_RETRIEVAL_STATUS_PAYWALL 內容位於付費牆後方,因此無法擷取網址。
URL_RETRIEVAL_STATUS_UNSAFE 內容不安全,因此無法擷取網址。

CitationMetadata

內容的來源出處集合。

欄位
citationSources[] object (CitationSource)

特定回覆的來源引用。

JSON 表示法
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}

CitationSource

特定回覆部分內容的來源引用。

欄位
startIndex integer

(選用步驟) 回覆中歸因於這項來源的區段開頭。

索引代表區隔的開頭,以位元組為單位。

endIndex integer

(選用步驟) 歸因片段的結束時間 (不含)。

uri string

(選用步驟) 歸因於部分文字來源的 URI。

license string

(選用步驟) GitHub 專案的授權,該專案是片段的來源。

必須提供授權資訊,才能引用程式碼。

JSON 表示法
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}

HarmCategory

分級類別。

這些類別涵蓋開發人員可能想調整的各種有害內容。

列舉
HARM_CATEGORY_UNSPECIFIED 未指定類別。
HARM_CATEGORY_DEROGATORY

PaLM:針對特定身分和/或受保護特質發表負面或有害言論。DEPRECATED: PaLM-only category, not supported by Gemini models.

HARM_CATEGORY_TOXICITY

PaLM:粗魯、不尊重或不雅的內容。已淘汰:僅限 PaLM 類別,Gemini 模型不支援。

HARM_CATEGORY_VIOLENCE

PaLM:描述對個人或群體施暴的情境,或一般血腥內容。DEPRECATED: PaLM-only category, not supported by Gemini models.

HARM_CATEGORY_SEXUAL

PaLM:提及性行為或其他猥褻情事的內容。已淘汰:僅限 PaLM 類別,Gemini 模型不支援。

HARM_CATEGORY_MEDICAL

PaLM:宣傳未經查證的醫療建議。已淘汰:僅限 PaLM 類別,Gemini 模型不支援。

HARM_CATEGORY_DANGEROUS

PaLM:宣傳、鼓吹或助長有害舉動的危險內容。DEPRECATED: PaLM-only category, not supported by Gemini models.

HARM_CATEGORY_HARASSMENT Gemini - 騷擾內容。
HARM_CATEGORY_HATE_SPEECH Gemini - 仇恨言論和內容。
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini - 情色露骨內容。
HARM_CATEGORY_DANGEROUS_CONTENT Gemini - 危險內容。
HARM_CATEGORY_CIVIC_INTEGRITY

Gemini:可能用於危害公民誠信的內容。已淘汰:請改用 enableEnhancedCivicAnswers。

HARM_CATEGORY_JAILBREAK Gemini:提示詞試圖規避或破壞模型的安全指南 (越獄嘗試)。

ModalityTokenCount

代表單一模態的詞元計數資訊。

欄位
modality enum (Modality)

與這個詞元數量相關聯的模態。

tokenCount integer

權杖數量。

JSON 表示法
{
  "modality": enum (Modality),
  "tokenCount": integer
}

模態

內容部分模態

列舉
MODALITY_UNSPECIFIED 未指定模態。
TEXT 純文字。
IMAGE 圖片。
VIDEO 影片。
AUDIO 音訊。
DOCUMENT 文件,例如 PDF。

SafetyRating

內容的安全評分。

安全評分包含內容的危害類別,以及該類別的危害機率等級。系統會根據多種危害類別,對內容進行安全性分類,並在此列出危害分類的機率。

欄位
category enum (HarmCategory)

必填。這項評分的類別。

probability enum (HarmProbability)

必填。這項內容有害的機率。

blocked boolean

這項內容是否因這個分級而遭到封鎖?

JSON 表示法
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}

HarmProbability

內容有害的機率。

分類系統會提供內容不安全的機率。這不代表內容的危害嚴重程度。

列舉
HARM_PROBABILITY_UNSPECIFIED 未指定機率。
NEGLIGIBLE 內容不安全的機率極低。
LOW 內容不太可能不安全。
MEDIUM 內容有中等機率不安全。
HIGH 內容很有可能不安全。

SafetySetting

安全性設定,會影響安全性封鎖行為。

傳遞類別的安全設定,會變更內容遭封鎖的允許機率。

欄位
category enum (HarmCategory)

必填。這項設定的類別。

threshold enum (HarmBlockThreshold)

必填。控制封鎖有害內容的機率門檻。

JSON 表示法
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

HarmBlockThreshold

封鎖有害機率達到或超過指定值的內容。

列舉
HARM_BLOCK_THRESHOLD_UNSPECIFIED 未指定門檻。
BLOCK_LOW_AND_ABOVE 系統會允許「可忽略」的內容。
BLOCK_MEDIUM_AND_ABOVE 系統會允許「NEGLIGIBLE」和「LOW」的內容。
BLOCK_ONLY_HIGH 系統會允許 NEGLIGIBLE、LOW 和 MEDIUM 的內容。
BLOCK_NONE 系統會允許所有內容。
OFF 關閉安全篩選器。

ServiceTier

要求的服務級別。

列舉
unspecified 預設服務級別,即標準級。
standard 標準服務級別。
flex Flex 服務級別。
priority 優先服務級別。

內容

基本結構化資料類型,包含訊息的多部分內容。

Content 包含 role 欄位 (指定 Content 的產生者) 和 parts 欄位 (包含多部分資料,其中包含訊息輪替的內容)。

欄位
parts[] object (Part)

構成單一訊息的已排序 Parts。各部分可能會有不同的 MIME 類型。

role string

(選用步驟) 內容的製作者。必須是「user」或「model」。

適合用於多輪對話,否則可以留空或不設定。

JSON 表示法
{
  "parts": [
    {
      object (Part)
    }
  ],
  "role": string
}

配件

包含媒體的資料類型,屬於多部分 Content 訊息的一部分。

Part 包含具有相關聯資料類型的資料。Part 只能包含 Part.data 中接受的其中一種類型。

如果 inlineData 欄位填入原始位元組,Part 必須有固定的 IANA MIME 類型,用於識別媒體的類型和子類型。

欄位
thought boolean

(選用步驟) 指出該部分是否為模型的思考過程。

thoughtSignature string (bytes format)

(選用步驟) 思考的不透明簽章,可在後續要求中重複使用。

Base64 編碼字串。

partMetadata object (Struct format)

與 Part 相關聯的自訂中繼資料。如果代理使用 genai.Part 做為內容表示法,可能需要追蹤額外資訊。例如,這可以是 Part 來源檔案/來源的名稱,或是多工處理多個 Part 串流的方式。

mediaResolution object (MediaResolution)

(選用步驟) 輸入媒體的媒體解析度。

mediaProcessing enum (MediaProcessing)

(選用步驟) 模型如何處理這個部分的媒體,以便理解內容。僅適用於影片部分 (inlineData 或 fileData 搭配影片 MIME)。非影片部分會忽略這個欄位。

audioTranscription object (AudioTranscription)

(選用步驟) 音訊 (輸入或輸出) 轉錄。只有在這個 Part 包含音訊資料時,才會設定這個屬性。

speechMetadata object (SpeechMetadata)

(選用步驟) 套用至文字部分的中繼資料,用於自訂朗讀或合成方式,例如指定說話者身分或說話風格。

data Union type
以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
text string

內嵌文字。

inlineData object (Blob)

內嵌媒體位元組。

functionCall object (FunctionCall)

模型傳回的預測 FunctionCall,其中包含代表 FunctionDeclaration.name 的字串,以及引數和其值。

functionResponse object (FunctionResponse)

FunctionCall 的結果輸出內容包含代表 FunctionDeclaration.name 的字串,以及包含函式任何輸出內容的結構化 JSON 物件,會做為模型的背景資訊。

fileData object (FileData)

URI 資料。

executableCode object (ExecutableCode)

模型生成的程式碼,用於執行。

codeExecutionResult object (CodeExecutionResult)

執行 ExecutableCode 的結果。

toolCall object (ToolCall)

伺服器端工具呼叫。如果模型預測應在伺服器上執行工具叫用,就會填入這個欄位。用戶端應將這則訊息回傳至 API。

toolResponse object (ToolResponse)

伺服器端 ToolCall 執行的輸出內容。用戶端會根據執行對應 ToolCall 的結果,填入這個欄位。

互斥欄位結束。
metadata Union type
控制資料的額外預先處理。如果 inline_data 或 file_data 存在,請設定這個屬性,為每個部分設定靜態媒體預先處理。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
videoMetadata object (VideoMetadata)

(選用步驟) 影片中繼資料。只有在 inlineData 或 fileData 中提供影片資料時,才應指定中繼資料。

互斥欄位結束。
JSON 表示法
{
  "thought": boolean,
  "thoughtSignature": string,
  "partMetadata": {
    object
  },
  "mediaResolution": {
    object (MediaResolution)
  },
  "mediaProcessing": enum (MediaProcessing),
  "audioTranscription": {
    object (AudioTranscription)
  },
  "speechMetadata": {
    object (SpeechMetadata)
  },

  // data
  "text": string,
  "inlineData": {
    object (Blob)
  },
  "functionCall": {
    object (FunctionCall)
  },
  "functionResponse": {
    object (FunctionResponse)
  },
  "fileData": {
    object (FileData)
  },
  "executableCode": {
    object (ExecutableCode)
  },
  "codeExecutionResult": {
    object (CodeExecutionResult)
  },
  "toolCall": {
    object (ToolCall)
  },
  "toolResponse": {
    object (ToolResponse)
  }
  // Union type

  // metadata
  "videoMetadata": {
    object (VideoMetadata)
  }
  // Union type
}

Blob

原始媒體位元組。

文字不應以原始位元組的形式傳送,請使用「text」欄位。

欄位
mimeType string

來源資料的 IANA 標準 MIME 類型。支援的類型範例:- 圖片:image/png、image/jpeg、image/jpg、image/webp、image/heic、image/heif、image/gif、image/avif - 音訊:audio/*、video/audio/s16le、video/audio/wav - 影片:video/* - 文字:text/plain、text/html、text/css、text/javascript、text/x-typescript、text/csv、text/markdown、text/x-python、text/xml、text/rtf、video/text/timestamp - 應用程式:application/x-javascript、application/x-typescript、application/x-python-code、application/json、application/x-ipynb+json、application/rtf、application/pdf。如需更多背景資訊,請參閱「支援的檔案格式」。//

data string (bytes format)

媒體格式的原始位元組。

Base64 編碼字串。

displayName string

(選用步驟) 指定向模型參照這個 blob 時使用的名稱 (例如「my_blob.png」)。當 verbalizationMode 設為 REFERENCE_ONLY 時,做為 Blob 參考 ID。

JSON 表示法
{
  "mimeType": string,
  "data": string,
  "displayName": string
}

FunctionCall

模型傳回的預測 FunctionCall,其中包含代表 FunctionDeclaration.name 的字串,以及引數和其值。

欄位
id string

(選用步驟) 函式呼叫的專屬 ID。如果已填入,用戶端會執行 functionCall,並傳回具有相符 id 的回應。

name string

必填。要呼叫的函式名稱。必須是 a-z、A-Z、0-9,或包含底線和破折號,長度上限為 128。

args object (Struct format)

(選用步驟) JSON 物件格式的函式參數和值。

JSON 表示法
{
  "id": string,
  "name": string,
  "args": {
    object
  }
}

FunctionResponse

FunctionCall 的輸出結果包含代表 FunctionDeclaration.name 的字串,以及包含函式輸出的結構化 JSON 物件,會做為模型的背景資訊。其中應包含根據模型預測結果做出的FunctionCall。

欄位
id string

(選用步驟) 這項回覆所屬函式呼叫的 ID。由用戶端填入,與對應的函式呼叫 id 相符。

name string

必填。要呼叫的函式名稱。必須是 a-z、A-Z、0-9,或包含底線和破折號,長度上限為 128。

response object (Struct format)

必填。JSON 物件格式的函式回應。呼叫端可以使用任何符合函式語法的鍵來傳回函式輸出內容,例如「output」、「result」等。特別是,如果函式呼叫無法執行,回應可以包含「error」鍵,將錯誤詳細資料傳回模型。

如要加入多媒體,請使用包含單一「$ref」鍵的子物件,其值為包含多媒體的 FunctionResponsePart 的 inlineData.display_name。請參閱 https://ai.google.dev/gemini-api/docs/function-calling#multimodal。

parts[] object (FunctionResponsePart)

(選用步驟) 構成函式回應的已排序 Parts。各部分可能會有不同的 IANA MIME 類型。

willContinue boolean

(選用步驟) 表示函式呼叫會繼續執行,並傳回更多回應,將函式呼叫轉換為生成器。僅適用於 NON_BLOCKING 函式呼叫,否則會遭到忽略。如果設為 False,系統就不會考量後續回覆。可以傳回空白的 response 和 willContinue=False,表示函式呼叫已完成。這仍可能觸發模型生成。如要避免觸發生成作業並完成函式呼叫,請一併將 scheduling 設為 SILENT。

scheduling enum (Scheduling)

(選用步驟) 指定應如何在對話中排定回覆。僅適用於 NON_BLOCKING 函式呼叫,否則會遭到忽略。預設為 WHEN_IDLE。

JSON 表示法
{
  "id": string,
  "name": string,
  "response": {
    object
  },
  "parts": [
    {
      object (FunctionResponsePart)
    }
  ],
  "willContinue": boolean,
  "scheduling": enum (Scheduling)
}

FunctionResponsePart

包含媒體的資料類型,屬於 FunctionResponse 訊息的一部分。

FunctionResponsePart 包含具有相關聯資料類型的資料。FunctionResponsePart 只能包含 FunctionResponsePart.data 中接受的其中一種類型。

如果 inlineData 欄位填入原始位元組,FunctionResponsePart 必須有固定的 IANA MIME 類型,用於識別媒體的類型和子類型。

欄位
data Union type
函式回應部分的資料。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
inlineData object (FunctionResponseBlob)

內嵌媒體位元組。

互斥欄位結束。
JSON 表示法
{

  // data
  "inlineData": {
    object (FunctionResponseBlob)
  }
  // Union type
}

FunctionResponseBlob

函式回應的原始媒體位元組。

文字不應以原始位元組的形式傳送,請使用「FunctionResponse.response」欄位。

欄位
mimeType string

來源資料的 IANA 標準 MIME 類型。範例:- image/png - image/jpeg 如果提供不支援的 MIME 類型,系統會傳回錯誤。如需支援類型的完整清單,請參閱「支援的檔案格式」。

data string (bytes format)

媒體格式的原始位元組。

Base64 編碼字串。

JSON 表示法
{
  "mimeType": string,
  "data": string
}

排程

指定應如何在對話中排定回覆。

列舉
SCHEDULING_UNSPECIFIED 這個值不會用到。
SILENT Only add the result to the conversation context, do not interrupt or trigger generation.
WHEN_IDLE 將結果新增至對話內容,並提示生成輸出內容,不中斷正在進行的生成作業。
INTERRUPT 將結果新增至對話內容、中斷進行中的生成作業,並提示生成輸出內容。

FileData

URI 資料。

欄位
mimeType string

(選用步驟) 來源資料的 IANA 標準 MIME 類型。

fileUri string

必填。URI。

displayName string

(選用步驟) 指定向模型參照這個檔案時使用的名稱 (例如「my_file.pdf」)。當 verbalizationMode 設為 REFERENCE_ONLY 時,做為檔案參考 ID。

JSON 表示法
{
  "mimeType": string,
  "fileUri": string,
  "displayName": string
}

ExecutableCode

模型生成的程式碼,用於執行並將結果傳回模型。

只有在使用 CodeExecution 工具時才會產生,系統會自動執行程式碼,並產生對應的 CodeExecutionResult。

欄位
id string

(選用步驟) ExecutableCode 部分的專屬 ID。伺服器會傳回與 id 相符的 CodeExecutionResult。

language enum (Language)

必填。code 的程式設計語言。

code string

必填。要執行的程式碼。

JSON 表示法
{
  "id": string,
  "language": enum (Language),
  "code": string
}

語言

生成程式碼支援的程式設計語言。

列舉
LANGUAGE_UNSPECIFIED 未指定語言。請勿使用這個值。
PYTHON Python >= 3.10,且可使用 numpy 和 simpy。預設語言為 Python。

CodeExecutionResult

執行 ExecutableCode 的結果。

只有在使用 CodeExecution 工具時才會產生。

欄位
id string

(選用步驟) 這項結果所屬 ExecutableCode 部分的 ID。只有在對應的 ExecutableCode 有 ID 時,才會填入這個欄位。

outcome enum (Outcome)

必填。執行程式碼的結果。

output string

(選用步驟) 如果執行程式碼成功,則包含 stdout,否則包含 stderr 或其他說明。

JSON 表示法
{
  "id": string,
  "outcome": enum (Outcome),
  "output": string
}

結果

列舉執行程式碼的可能結果。

列舉
OUTCOME_UNSPECIFIED 未指定狀態。請勿使用這個值。
OUTCOME_OK 已成功執行程式碼。output 包含 stdout (如有)。
OUTCOME_FAILED 無法執行程式碼。output 包含 stderr 和 stdout (如有)。
OUTCOME_DEADLINE_EXCEEDED 執行程式碼時間過長,因此已取消。可能會有部分 output。

ToolCall

模型傳回的預測伺服器端ToolCall。這則訊息包含模型要叫用的工具相關資訊。用戶端不應執行這個 ToolCall。用戶端應在後續對話中,透過 Content 訊息將這個 ToolCall 傳回 API,並附上對應的 ToolResponse。

欄位
id string

(選用步驟) 工具呼叫的專屬 ID。伺服器會傳回工具回應,並附上相符的 id。

toolName string

(選用步驟) 呼叫的工具名稱。

toolType enum (ToolType)

必填。呼叫的工具類型。

args object (Struct format)

(選用步驟) 工具呼叫引數。範例:{"arg1" : "value1", "arg2" : "value2" , ...}

JSON 表示法
{
  "id": string,
  "toolName": string,
  "toolType": enum (ToolType),
  "args": {
    object
  }
}

ToolType

函式呼叫中的工具類型。

列舉
TOOL_TYPE_UNSPECIFIED 未指定工具類型。
GOOGLE_SEARCH_WEB Google 搜尋工具,對應至 Tool.google_search.search_types.web_search。
GOOGLE_SEARCH_IMAGE 圖片搜尋工具,對應至 Tool.google_search.search_types.image_search。
URL_CONTEXT 網址背景資訊工具,對應至 Tool.url_context。
GOOGLE_MAPS Google 地圖工具,對應至 Tool.google_maps。

ToolResponse

伺服器端 ToolCall 執行的輸出內容。這則訊息包含模型 ToolCall 啟動的工具叫用結果。用戶端應在後續對話中,透過 Content 訊息將這個 ToolResponse 傳回 API,並附上對應的 ToolCall。

欄位
id string

(選用步驟) 這項回覆對應的工具呼叫 ID。

toolType enum (ToolType)

必填。呼叫的工具類型,與對應 ToolCall 中的 toolType 相符。

response object (Struct format)

(選用步驟) 工具回覆。

JSON 表示法
{
  "id": string,
  "toolType": enum (ToolType),
  "response": {
    object
  }
}

VideoMetadata

中繼資料會說明輸入的影片內容。當 inlineData 或 fileData 包含影片時,請在 Part.video_metadata 或 FunctionResponsePart.video_metadata 中設定這項屬性,以設定靜態影片預先處理 (例如時間剪輯、影格率、影格數量上限或擷取的內容層)。

欄位
startOffset string (Duration format)

(選用步驟) 影片的開始偏移量。

以秒為單位的時間長度,最多 9 個小數位數,結尾為「s」。例如:"3.5s"。

endOffset string (Duration format)

(選用步驟) 影片的結束偏移。

以秒為單位的時間長度,最多 9 個小數位數,結尾為「s」。例如:"3.5s"。

fps number

(選用步驟) 傳送至模型的影片影格率。如未指定,預設值為 1.0。每秒影格數範圍為 (0.0, 24.0]。

JSON 表示法
{
  "startOffset": string,
  "endOffset": string,
  "fps": number
}

MediaResolution

用於權杖化的媒體解析度。

欄位
value Union type
媒體解析度等級。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
level enum (Level)

用於指定媒體的權杖化品質。 ,瞭解 Gemini API 支援。

互斥欄位結束。
JSON 表示法
{

  // value
  "level": enum (Level)
  // Union type
}

等級

媒體解析度等級。

列舉
MEDIA_RESOLUTION_UNSPECIFIED 尚未設定媒體解析度。
MEDIA_RESOLUTION_LOW 媒體解析度已設為低。
MEDIA_RESOLUTION_MEDIUM 媒體解析度已設為中等。
MEDIA_RESOLUTION_HIGH 媒體解析度已設為高。
MEDIA_RESOLUTION_ULTRA_HIGH 媒體解析度已設為超高。

MediaProcessing

模型如何處理輸入媒體以理解內容。

列舉
MEDIA_PROCESSING_UNSPECIFIED 預設為模型專屬處理。
STATIC 固定速率影格擷取。所有影格都已放入情境中。
AGENTIC 模型驅動的動態導覽。適用於大部分用途。

AudioTranscription

音訊部分的轉錄稿。如果音訊有多位說話者,每個說話者片段都是獨立的 Part,並有自己的 AudioTranscription,其中包含 speakerLabel。

欄位
text string

必填。這段音訊的轉錄文字。

speakerLabel string

(選用步驟) 這個音訊片段的發言者標籤 (例如「spk_1」、「spk_2」)。設定說話者辨識時顯示。

words[] object (WordInfo)

(選用步驟) 詳細的字詞層級轉錄稿和時間詳細資料。設定 wordTimestamp 時會顯示。

JSON 表示法
{
  "text": string,
  "speakerLabel": string,
  "words": [
    {
      object (WordInfo)
    }
  ]
}

WordInfo

單一辨識字詞的相關資訊。

欄位
word string

必填。字詞的轉錄稿。

startOffset string (Duration format)

(選用步驟) 字詞相對於音訊開頭的起始偏移時間。

以秒為單位的時間長度,最多 9 個小數位數,結尾為「s」。例如:"3.5s"。

endOffset string (Duration format)

(選用步驟) 字詞相對於音訊開頭的結束時間偏移。

以秒為單位的時間長度,最多 9 個小數位數,結尾為「s」。例如:"3.5s"。

JSON 表示法
{
  "word": string,
  "startOffset": string,
  "endOffset": string
}

SpeechMetadata

text 個部分的語音中繼資料。

欄位
speaker string

(選用步驟) 多人語音合成的講者名稱 (選填)。

style string

(選用步驟) 語音合成的選用風格指令。

JSON 表示法
{
  "speaker": string,
  "style": string
}

環境

代理的執行環境。

欄位
id string

必填。僅供輸出。環境的 ID。

sources[] object (Source)

要掛接至環境的來源。

created string

僅供輸出。環境建立時間,採用 ISO 8601 格式 (YYYY-MM-DDThh:mm:ssZ)。

updated string

僅供輸出。環境上次更新的時間,採用 ISO 8601 格式 (YYYY-MM-DDThh:mm:ssZ)。

lastAccessed string

僅供輸出。上次存取環境的時間,採用 ISO 8601 格式 (YYYY-MM-DDThh:mm:ssZ)。

status enum (Status)

僅供輸出。環境容器的狀態。

fileCount string (int64 format)

僅供輸出。環境中的檔案數量 (僅限輸出)。

sizeBytes string (int64 format)

僅供輸出。環境檔案的總大小 (以位元組為單位),僅供輸出。

network Union type
環境的網路設定。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
networkAllowlist object (EnvironmentNetworkEgressAllowlist)

僅允許特定網域。

networkMode enum (NetworkMode)

網路輸出模式。

互斥欄位結束。
JSON 表示法
{
  "id": string,
  "sources": [
    {
      object (Source)
    }
  ],
  "created": string,
  "updated": string,
  "lastAccessed": string,
  "status": enum (Status),
  "fileCount": string,
  "sizeBytes": string,

  // network
  "networkAllowlist": {
    object (EnvironmentNetworkEgressAllowlist)
  },
  "networkMode": enum (NetworkMode)
  // Union type
}

狀態

環境狀態。

列舉
STATUS_UNSPECIFIED
ACTIVE
EXPIRED

NetworkMode

非許可清單設定的網路輸出模式。

列舉
NETWORK_MODE_UNSPECIFIED 預設值。未使用。
DISABLED 所有網路輸出都會遭到封鎖。

結構定義

Schema 物件可定義輸入和輸出資料類型。這些類型可以是物件,也可以是原始類型和陣列。代表 OpenAPI 3.0 結構定義物件的特定子集。

欄位
type enum (Type)

必填。資料類型。

format string

(選用步驟) 資料格式。可輸入任何值,但多數值不會觸發任何特殊功能。

title string

(選用步驟) 結構定義的標題。

description string

(選用步驟) 參數的簡短說明。這可能包含使用範例。參數說明可採用 Markdown 格式。

nullable boolean

(選用步驟) 指出值是否可為空值。

enum[] string

(選用步驟) Type.STRING 元素可能的值,格式為列舉。舉例來說,我們可以將 Enum Direction 定義為:{type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]}

maxItems string (int64 format)

(選用步驟) Type.ARRAY 的元素數量上限。

minItems string (int64 format)

(選用步驟) Type.ARRAY 的元素數量下限。

properties map (key: string, value: object (Schema))

(選用步驟) Type.OBJECT 的屬性。

這個物件中包含 "key": value 組合的清單,範例:{ "name": "wrench", "mass": "1.3kg", "count": "3" }。

required[] string

(選用步驟) Type.OBJECT 的必要屬性。

minProperties string (int64 format)

(選用步驟) Type.OBJECT 的屬性數量下限。

maxProperties string (int64 format)

(選用步驟) Type.OBJECT 的屬性數量上限。

minLength string (int64 format)

(選用步驟) 類型 STRING 的結構定義欄位:Type.STRING 的長度下限

maxLength string (int64 format)

(選用步驟) Type.STRING 的長度上限

pattern string

(選用步驟) Type.STRING 的模式,用於將字串限制為規則運算式。

example value (Value format)

(選用步驟) 物件範例。只有在物件為根時,才會填入。

anyOf[] object (Schema)

(選用步驟) 值應根據清單中的任何 (一或多個) 子結構定義進行驗證。

propertyOrdering[] string

(選用步驟) 屬性的順序。這不是 Open API 規格中的標準欄位,用於決定回應中屬性的順序。

default value (Value format)

(選用步驟) 欄位的預設值。根據 JSON 結構定義,這個欄位適用於文件產生器,不會影響驗證。因此,這裡會納入並忽略這個欄位,這樣一來,傳送含有 default 欄位結構定義的開發人員就不會收到未知欄位錯誤。

items object (Schema)

(選用步驟) Type.ARRAY 元素的結構定義。

minimum number

(選用步驟) INTEGER 和 NUMBER 類型的結構定義欄位:Type.INTEGER 和 Type.NUMBER 的最小值

maximum number

(選用步驟) Type.INTEGER 和 Type.NUMBER 的最大值

JSON 表示法
{
  "type": enum (Type),
  "format": string,
  "title": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "minProperties": string,
  "maxProperties": string,
  "minLength": string,
  "maxLength": string,
  "pattern": string,
  "example": value,
  "anyOf": [
    {
      object (Schema)
    }
  ],
  "propertyOrdering": [
    string
  ],
  "default": value,
  "items": {
    object (Schema)
  },
  "minimum": number,
  "maximum": number
}

類型

「Type」包含 https://spec.openapis.org/oas/v3.0.3#data-types 定義的 OpenAPI 資料類型清單

列舉
TYPE_UNSPECIFIED 未指定,不應使用。
STRING 字串類型。
NUMBER 數字類型。
INTEGER 整數類型。
BOOLEAN 布林值類型。
ARRAY 陣列類型。
OBJECT 物件類型。
NULL 空值類型。

工具

模型可能用來生成回覆的工具詳細資料。

Tool是一段程式碼,可讓系統與外部系統互動,執行模型知識和範圍以外的一或多項動作。

欄位
functionDeclarations[] object (FunctionDeclaration)

(選用步驟) 模型可用的 FunctionDeclarations 清單,可用於呼叫函式。

模型或系統不會執行函式,而是將定義的函式以 FunctionCall 形式傳回,並附帶引數,供用戶端執行。模型可能會在回覆中填入 FunctionCall,決定呼叫這些函式的子集。下一個對話回合可能包含 FunctionResponse,其中包含下一個模型回合的 Content.role「函式」生成情境。

googleSearchRetrieval object (GoogleSearchRetrieval)

(選用步驟) 採用 Google 搜尋技術的檢索工具。

codeExecution object (CodeExecution)

(選用步驟) 讓模型在生成內容時執行程式碼。

computerUse object (ComputerUse)

(選用步驟) 這項工具可讓模型直接與電腦互動。啟用後,系統會自動填入電腦使用專用的函式宣告。

urlContext object (UrlContext)

(選用步驟) 支援網址背景資訊擷取的工具。

mcpServers[] object (McpServer)

(選用步驟) 要連線的 MCP 伺服器。

googleMaps object (GoogleMaps)

(選用步驟) 這項工具可根據與使用者查詢相關的地理空間背景資訊,建立模型回覆。

JSON 表示法
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "googleSearchRetrieval": {
    object (GoogleSearchRetrieval)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "googleSearch": {
    object (GoogleSearch)
  },
  "computerUse": {
    object (ComputerUse)
  },
  "urlContext": {
    object (UrlContext)
  },
  "fileSearch": {
    object (FileSearch)
  },
  "mcpServers": [
    {
      object (McpServer)
    }
  ],
  "googleMaps": {
    object (GoogleMaps)
  }
}

FunctionDeclaration

函式宣告的結構化表示法,依 OpenAPI 3.03 規格定義。這項宣告包含函式名稱和參數。這個 FunctionDeclaration 代表一段程式碼,模型可將其做為 Tool,並由用戶端執行。

欄位
name string

必填。函式名稱。必須是 a-z、A-Z、0-9,或包含底線、冒號、句點和破折號,長度上限為 128。

description string

必填。函式的簡短說明。

behavior enum (Behavior)

(選用步驟) 指定函式行為。目前僅支援 BidiGenerateContent 方法。

parameters object (Schema)

(選用步驟) 說明這個函式的參數。反映 Open API 3.03 參數物件字串鍵:參數名稱。參數名稱區分大小寫。結構定義值:定義參數所用類型的結構定義。

parametersJsonSchema value (Value format)

(選用步驟) 以 JSON 結構定義格式說明函式的參數。結構定義必須描述一個物件,其屬性為函式的參數。例如:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" }
  },
  "additionalProperties": false,
  "required": ["name", "age"],
  "propertyOrdering": ["name", "age"]
}

這個欄位與 parameters 互斥。

response object (Schema)

(選用步驟) 以 JSON 結構定義格式說明這個函式的輸出內容。反映 Open API 3.03 回應物件。結構定義會定義函式回應值使用的類型。

responseJsonSchema value (Value format)

(選用步驟) 以 JSON 結構定義格式說明這個函式的輸出內容。結構定義指定的值是函式的回應值。

這個欄位與 response 互斥。

JSON 表示法
{
  "name": string,
  "description": string,
  "behavior": enum (Behavior),
  "parameters": {
    object (Schema)
  },
  "parametersJsonSchema": value,
  "response": {
    object (Schema)
  },
  "responseJsonSchema": value
}

行為

定義函式行為。預設值為 BLOCKING。

列舉
UNSPECIFIED 這個值不會用到。
BLOCKING 設定後,系統會等待函式回應,再繼續對話。
NON_BLOCKING 如果設定,系統就不會等待接收函式回應。而是會在函式回應可用時嘗試處理,同時維持使用者與模型之間的對話。

GoogleSearchRetrieval

這項工具由 Google 提供,可擷取公開網路資料做為基準。

欄位
dynamicRetrievalConfig object (DynamicRetrievalConfig)

指定指定來源的動態檢索設定。

JSON 表示法
{
  "dynamicRetrievalConfig": {
    object (DynamicRetrievalConfig)
  }
}

DynamicRetrievalConfig

說明自訂動態檢索的選項。

欄位
mode enum (Mode)

動態檢索中使用的預測器模式。

dynamicThreshold number

動態擷取使用的門檻。如未設定,系統會使用系統預設值。

JSON 表示法
{
  "mode": enum (Mode),
  "dynamicThreshold": number
}

模式

動態檢索時要使用的預測器模式。

列舉
MODE_UNSPECIFIED 一律觸發檢索。
MODE_DYNAMIC 只有在系統判定有必要時,才執行檢索。

CodeExecution

這個類型沒有任何欄位。

這項工具會執行模型生成的程式碼,並自動將結果傳回模型。

另請參閱 ExecutableCode 和 CodeExecutionResult,這兩項指標只有在使用這項工具時才會產生。

GoogleSearch

GoogleSearch 工具類型。在模型中支援 Google 搜尋的工具。體現 Google 的技術結晶

欄位
timeRangeFilter object (Interval)

(選用步驟) 篩選特定日期範圍的搜尋結果。如果顧客設定開始時間,就必須設定結束時間,反之亦然。

searchTypes object (SearchTypes)

(選用步驟) 要啟用的搜尋類型組合。如未設定,系統預設會啟用網頁搜尋。

JSON 表示法
{
  "timeRangeFilter": {
    object (Interval)
  },
  "searchTypes": {
    object (SearchTypes)
  }
}

間隔

代表時間間隔,編碼以一個時間戳記開始 (含),一個時間戳記結束 (不含)。

開始時間必須小於或等於結束時間。如果開始時間等於結束時間,間隔會是空白 (不符合任何時間)。如果開始和結束時間都未指定,則間隔會符合任何時間。

欄位
startTime string (Timestamp format)

(選用步驟) 間隔的開始時間 (含)。

如果指定了這個值,符合此間隔的時間戳記必須等於或晚於開始時間。

使用 RFC 3339,產生的輸出內容一律會經過 Z 正規化,並使用 0、3、6 或 9 個小數位數,也接受「Z」以外的偏移量。範例:"2014-10-02T15:01:23Z"、"2014-10-02T15:01:23.045123456Z" 或 "2014-10-02T15:01:23+05:30"。

endTime string (Timestamp format)

選填。間隔的結束時間 (不含)。

如果指定,符合這個間隔的時間戳記必須早於結束時間。

使用 RFC 3339,產生的輸出內容一律會經過 Z 正規化,並使用 0、3、6 或 9 個小數位數,也接受「Z」以外的偏移量。範例:"2014-10-02T15:01:23Z"、"2014-10-02T15:01:23.045123456Z" 或 "2014-10-02T15:01:23+05:30"。

JSON 表示法
{
  "startTime": string,
  "endTime": string
}

SearchTypes

可在 GoogleSearch 工具啟用的不同搜尋類型。

欄位
JSON 表示法
{
  "webSearch": {
    object (WebSearch)
  },
  "imageSearch": {
    object (ImageSearch)
  }
}

WebSearch

這個類型沒有任何欄位。

用於建立基準和相關設定的標準網頁搜尋。

ImageSearch

這個類型沒有任何欄位。

圖片搜尋基準和相關設定。

ComputerUse

Computer Use 工具類型。

欄位
environment enum (Environment)

必填。要操作的環境。

excludedPredefinedFunctions[] string

(選用步驟) 根據預設,最終模型呼叫會包含預先定義的函式。您可以明確排除某些項目,不讓系統自動納入。這有兩個用途:1. 使用限制較多 / 不同的動作空間。2. 改善預先定義函式的定義 / 操作說明。

enablePromptInjectionDetection boolean

(選用步驟) 是否要對電腦使用要求啟用提示詞注入偵測檢查。

disabledSafetyPolicies[] enum (SafetyPolicy)

(選用步驟) 停用電腦使用安全政策。

JSON 表示法
{
  "environment": enum (Environment),
  "excludedPredefinedFunctions": [
    string
  ],
  "enablePromptInjectionDetection": boolean,
  "disabledSafetyPolicies": [
    enum (SafetyPolicy)
  ]
}

環境

代表操作中的環境,例如網路瀏覽器。

列舉
ENVIRONMENT_UNSPECIFIED 預設為瀏覽器。
ENVIRONMENT_BROWSER 在網路瀏覽器中運作。
ENVIRONMENT_MOBILE 在行動環境中運作。
ENVIRONMENT_DESKTOP 在電腦環境中運作。

SafetyPolicy

預先定義的電腦使用安全政策。

列舉
SAFETY_POLICY_UNSPECIFIED 未指定安全政策。
FINANCIAL_TRANSACTIONS 金融交易安全政策。
SENSITIVE_DATA_MODIFICATION 敏感資料修改安全政策。
COMMUNICATION_TOOL 通訊工具 (例如 Gmail、Chat、Meet) 的安全政策。
ACCOUNT_CREATION 帳戶建立安全性政策。
DATA_MODIFICATION 資料修改安全政策。
LEGAL_TERMS_AND_AGREEMENTS 法律條款和協議的安全政策。

UrlContext

這個類型沒有任何欄位。

支援網址背景資訊擷取的工具。

FileSearch

FileSearch 工具,可從語意檢索語料庫中擷取知識。檔案會透過 ImportFile API 匯入語意檢索語料庫。

欄位
fileSearchStoreNames[] string

必填。要擷取的 fileSearchStores 名稱。範例:fileSearchStores/my-file-search-store-123

metadataFilter string

(選用步驟) 要套用至語意檢索文件和區塊的中繼資料篩選器。

topK integer

(選用步驟) 要擷取的語意檢索區塊數量。

JSON 表示法
{
  "fileSearchStoreNames": [
    string
  ],
  "metadataFilter": string,
  "topK": integer
}

McpServer

MCPServer 是可由模型呼叫來執行動作的伺服器。這類伺服器會實作 MCP 通訊協定。

欄位
name string

MCPServer 的名稱。

transport Union type
連線至 MCPServer 時要使用的傳輸方式。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
streamableHttpTransport object (StreamableHttpTransport)

可串流 HTTP 要求和回應的傳輸。

互斥欄位結束。
JSON 表示法
{
  "name": string,

  // transport
  "streamableHttpTransport": {
    object (StreamableHttpTransport)
  }
  // Union type
}

StreamableHttpTransport

可串流 HTTP 要求和回應的傳輸。

欄位
url string

MCPServer 端點的完整網址。例如:「https://api.example.com/mcp」

headers map (key: string, value: string)

選用:視需要填寫驗證標頭、逾時等欄位。

這個物件中包含 "key": value 組合的清單,範例:{ "name": "wrench", "mass": "1.3kg", "count": "3" }。

timeout string (Duration format)

一般作業的 HTTP 逾時時間。

以秒為單位的時間長度,最多 9 個小數位數,結尾為「s」。例如:"3.5s"。

sseReadTimeout string (Duration format)

SSE 讀取作業逾時。

以秒為單位的時間長度,最多 9 個小數位數,結尾為「s」。例如:"3.5s"。

terminateOnClose boolean

是否要在傳輸關閉時關閉用戶端工作階段。

JSON 表示法
{
  "url": string,
  "headers": {
    string: string,
    ...
  },
  "timeout": string,
  "sseReadTimeout": string,
  "terminateOnClose": boolean
}

GoogleMaps

GoogleMaps 工具,可為使用者查詢提供地理空間背景資訊。

欄位
enableWidget boolean

(選用步驟) 是否在回覆的 GroundingMetadata 中傳回小工具脈絡詞元。開發人員可以使用小工具脈絡詞元,算繪 Google 地圖小工具,並提供與模型在回覆中提及的地點相關的地理空間脈絡。

JSON 表示法
{
  "enableWidget": boolean
}

REST 資源:auth_tokens

資源:AuthToken

建立臨時驗證權杖的要求。

欄位
name string

僅供輸出。ID。權杖本身。

expireTime string (Timestamp format)

(選用步驟) 僅限輸入。不可變動。選用時間,超過這個時間後,使用產生的權杖時,BidiGenerateContent 工作階段中的訊息會遭到拒絕。(Gemini 可能會在這段時間後主動關閉工作階段)。

如未設定,則預設為 30 分鐘後。如果設定這個值,則必須小於 20 小時。

使用 RFC 3339,產生的輸出內容一律會經過 Z 正規化,並使用 0、3、6 或 9 個小數位數,也接受「Z」以外的偏移量。範例:"2014-10-02T15:01:23Z"、"2014-10-02T15:01:23.045123456Z" 或 "2014-10-02T15:01:23+05:30"。

newSessionExpireTime string (Timestamp format)

(選用步驟) 僅限輸入。不可變動。超過這個時間後,使用這項要求產生的權杖建立新的 Live API 工作階段,將會遭到拒絕。

如未設定,預設值為 60 秒後。如果設定這個值,則必須小於 20 小時。

使用 RFC 3339,產生的輸出內容一律會經過 Z 正規化,並使用 0、3、6 或 9 個小數位數,也接受「Z」以外的偏移量。範例:"2014-10-02T15:01:23Z"、"2014-10-02T15:01:23.045123456Z" 或 "2014-10-02T15:01:23+05:30"。

fieldMask string (FieldMask format)

(選用步驟) 僅限輸入。不可變動。如果 fieldMask 為空白,且沒有 bidiGenerateContentSetup,則有效的 BidiGenerateContentSetup 訊息會取自 Live API 連線。

如果 fieldMask 為空白,且bidiGenerateContentSetup 存在,則有效的BidiGenerateContentSetup訊息會完全取自這項要求中的bidiGenerateContentSetup。系統會忽略 Live API 連線的設定訊息。

如果 fieldMask 不是空白,bidiGenerateContentSetup 的對應欄位會覆寫 Live API 連線中設定訊息的欄位。

這是以半形逗號分隔的完整欄位名稱清單,範例:"user.displayName,photo"。

config Union type
產生權杖的方法專屬設定。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
bidiGenerateContentSetup object (BidiGenerateContentSetup)

(選用步驟) 僅限輸入。不可變動。BidiGenerateContent 專用設定。

互斥欄位結束。
uses integer

(選用步驟) 僅限輸入。不可變動。權杖可使用的次數。如果這個值為零,則不會套用任何限制。恢復 Live API 工作階段不計入使用次數。如未指定,預設值為 1。

JSON 表示法
{
  "name": string,
  "expireTime": string,
  "newSessionExpireTime": string,
  "fieldMask": string,

  // config
  "bidiGenerateContentSetup": {
    object (BidiGenerateContentSetup)
  }
  // Union type
  "uses": integer
}

BidiGenerateContentSetup

在第一個 (且僅限第一個) BidiGenerateContentClientMessage 中傳送的訊息。包含在串流 RPC 期間套用的設定。

用戶端應等待 BidiGenerateContentSetupComplete 訊息,再傳送其他訊息。

欄位
model string

必填。模型的資源名稱。這個 ID 會用於模型。

格式:models/{model}

generationConfig object (GenerationConfig)

(選用步驟) 生成設定。

不支援下列欄位:

  • responseLogprobs
  • responseMimeType
  • logprobs
  • responseSchema
  • responseJsonSchema
  • stop_sequence
  • skipResponseCache
  • routing_config
  • audio_timestamp
systemInstruction object (Content)

(選用步驟) 使用者為模型提供的系統指令。

注意:各部分只能使用文字,且各部分的內容會分段顯示。

tools[] object (Tool)

(選用步驟) 模型可能用來生成下一個回覆的Tools清單。

Tool是一段程式碼,可讓系統與外部系統互動,執行模型知識和範圍以外的一或多項動作。

realtimeInputConfig object (RealtimeInputConfig)

(選用步驟) 設定即時輸入內容的處理方式。

sessionResumption object (SessionResumptionConfig)

(選用步驟) 設定工作階段繼續機制。

如果包含,伺服器會傳送 SessionResumptionUpdate 訊息。

contextWindowCompression object (ContextWindowCompressionConfig)

(選用步驟) 設定脈絡視窗壓縮機制。

如果包含這項設定,當脈絡超過設定長度時,伺服器會自動縮減脈絡大小。

inputAudioTranscription object (AudioTranscriptionConfig)

(選用步驟) 如果設定,系統會啟用語音輸入轉錄功能。如果已設定,轉錄稿會與輸入音訊語言一致。

outputAudioTranscription object (AudioTranscriptionConfig)

(選用步驟) 設定後,系統會轉錄模型的音訊輸出內容。如果已設定輸出音訊的語言代碼,轉錄稿會與該代碼一致。

historyConfig object (HistoryConfig)

(選用步驟) 設定用戶端和伺服器之間的記錄交換。

labels map (key: string, value: string)

(選用步驟) 要求的使用者定義中繼資料標籤。

(選用步驟) 標籤必須符合標準統一 Cloud 標籤規定:- 標籤鍵開頭須為英文字母。- 標籤鍵和值的長度不得超過 63 個字元 (Unicode 碼點),且只能包含小寫英文字母、數字、底線和破折號。- 可以使用國際字元。

用法:- 來自集結網站的安全 ID:使用 safety_identifier 鍵 (例如 {"safety_identifier": "user_session_123"})

這個物件中包含 "key": value 組合的清單,範例:{ "name": "wrench", "mass": "1.3kg", "count": "3" }。

JSON 表示法
{
  "model": string,
  "generationConfig": {
    object (GenerationConfig)
  },
  "systemInstruction": {
    object (Content)
  },
  "tools": [
    {
      object (Tool)
    }
  ],
  "realtimeInputConfig": {
    object (RealtimeInputConfig)
  },
  "sessionResumption": {
    object (SessionResumptionConfig)
  },
  "contextWindowCompression": {
    object (ContextWindowCompressionConfig)
  },
  "inputAudioTranscription": {
    object (AudioTranscriptionConfig)
  },
  "outputAudioTranscription": {
    object (AudioTranscriptionConfig)
  },
  "historyConfig": {
    object (HistoryConfig)
  },
  "labels": {
    string: string,
    ...
  }
}

GenerationConfig

模型生成和輸出的設定選項。部分參數無法在某些模型中設定。

欄位
stopSequences[] string

(選用步驟) 停止生成輸出內容的字元序列組合 (最多 5 個)。如果指定,API 會在第一次出現 stop_sequence 時停止。停止序列不會包含在回覆中。

responseMimeType string

(選用步驟) 生成候選文字的 MIME 類型。支援的 MIME 類型如下:text/plain:(預設) 文字輸出。application/json:候選回覆中的 JSON 回覆。text/x.enum:候選回覆中的 ENUM 字串回覆。如需所有支援的文字 MIME 類型清單,請參閱說明文件。

responseSchema
(deprecated)
object (Schema)

(選用步驟) 生成候選文字的輸出結構定義。結構定義必須是 OpenAPI 結構定義的子集,可以是物件、基本類型或陣列。

如果設定這項屬性,也必須設定相容的 responseMimeType。相容的 MIME 類型:application/json:JSON 回應的結構定義。詳情請參閱 JSON 文字生成指南。

已淘汰,請改用 responseFormat。

_responseJsonSchema
(deprecated)
value (Value format)

(選用步驟) 生成回覆的輸出結構定義。這是 responseSchema 的替代方案,可接受 JSON 結構定義。

如果設定這項屬性,則必須省略 responseSchema,但必須提供 responseMimeType。

雖然可以傳送完整的 JSON 結構定義,但並非所有功能都支援。具體來說,系統僅支援下列屬性:

  • $id
  • $defs
  • $ref
  • $anchor
  • type
  • format
  • title
  • description
  • enum (適用於字串和數字)
  • items
  • prefixItems
  • minItems
  • maxItems
  • minimum
  • maximum
  • anyOf
  • oneOf (解讀方式與 anyOf 相同)
  • properties
  • additionalProperties
  • required

您也可以設定非標準 propertyOrdering 屬性。

循環參照會展開至有限程度,因此只能在非必要屬性中使用。(僅使用可為空值的屬性是不夠的)。如果在子結構定義上設定 $ref,則除了以 $ 開頭的屬性外,不得設定其他屬性。

已淘汰,請改用 responseFormat。

responseJsonSchema value (Value format)

(選用步驟) 內部詳細資料。請使用 responseJsonSchema,而非這個欄位。

responseModalities[] enum (Modality)

(選用步驟) 回覆要求的模態。代表模型可傳回的模態組合,且應在回覆中預期。這與回覆的模態完全相符。

模型可能支援多種模態組合。如果要求的模態不符合任何支援的組合,系統會傳回錯誤。

空白清單等同於只要求文字。

candidateCount integer

(選用步驟) 要傳回的生成回覆數量。如未設定,預設值為 1。請注意,這項功能不適用於前一代模型 (Gemini 1.0 系列)

maxOutputTokens integer

(選用步驟) 候選回覆中可包含的詞元數量上限。

注意:預設值因模型而異,請參閱 getModel 函式傳回的 Model Model.output_token_limit 屬性。

temperature number

(選用步驟) 控制輸出內容的隨機程度。

注意:預設值因模型而異,請參閱 getModel 函式傳回的 Model Model.temperature 屬性。

值範圍為 [0.0, 2.0]。

Gemini 3.6 Flash 和更新的模型不再支援這個欄位,並會自動忽略。

topP number

(選用步驟) 取樣時要考量的詞元累計機率上限。

模型會結合 Top-k 和 Top-p (核心) 取樣。

系統會根據指派的機率排序詞元,只考慮最有可能的詞元。Top-k 取樣會直接限制要考量的詞元數量上限,而 Nucleus 取樣則會根據累積機率限制詞元數量。

注意:預設值會因 Model 而異,並由 getModel 函式傳回的 Model.top_p 屬性指定。如果 topK 屬性空白,表示模型不會套用 Top-K 取樣,也不允許在要求中設定 topK。

Gemini 3.6 Flash 和更新的模型不再支援這個欄位,並會自動忽略。

topK integer

(選用步驟) 取樣時要考量的詞元數量上限。

Gemini 模型會使用 Top-p (核心) 取樣,或結合 Top-k 和核心取樣。Top-k 取樣會考量機率最高的 topK 個詞元。使用核心取樣執行的模型不允許 topK 設定。

注意:預設值會因 Model 而異,並由 getModel 函式傳回的 Model.top_p 屬性指定。如果 topK 屬性空白,表示模型不會套用 top-k 取樣,也不允許在要求中設定 topK。

Gemini 3.6 Flash 和更新的模型不再支援這個欄位,並會自動忽略。

seed integer

(選用步驟) 解碼時使用的種子。如未設定,要求會使用隨機產生的種子。

presencePenalty number

(選用步驟) 如果權杖已出現在回覆中,則會對下一個權杖的 logprobs 套用存在懲罰。

這項懲罰機制只有啟用/停用兩種狀態,與詞元使用次數無關 (首次使用後)。使用 frequencyPenalty,每次使用都會增加懲罰。

正值懲罰會降低回覆中使用重複詞元的機率,增加詞彙量。

如果設為負值,系統會傾向使用已在回覆中出現過的詞元,減少用詞變化。

frequencyPenalty number

(選用步驟) 套用至下一個詞元 logprobs 的頻率懲罰,乘以每個詞元在回覆中出現的次數。

正值懲罰會根據詞元的使用次數,按比例降低已使用詞元的使用頻率:詞元使用次數越多,模型就越難再次使用該詞元,進而增加回覆的詞彙量。

注意:如果設為負值,模型會根據詞元的使用次數,按比例重複使用詞元。如果設為較小的負值,回覆的詞彙量會減少。如果負值較大,模型會開始重複常見的詞元,直到達到 maxOutputTokens 限制。

responseLogprobs boolean

(選用步驟) 如果設為 true,則在回覆中匯出 logprobs 結果。

logprobs integer

(選用步驟) 必須設定 responseLogprobs=True 才會生效。這項設定會指定 Candidate.logprobs_result 中每個解碼步驟要傳回的最高 logprob 數量 (包含所選候選項目)。數字必須介於 0 到 20 之間。

enableEnhancedCivicAnswers boolean

(選用步驟) 啟用強化版公民資訊解答。部分模型可能不支援這項功能。

speechConfig object (SpeechConfig)

(選用步驟) 語音生成設定。

thinkingConfig object (ThinkingConfig)

(選用步驟) 思考功能的設定。如果為不支援思考的模型設定這個欄位,系統會傳回錯誤。

imageConfig object (ImageConfig)

(選用步驟) 圖像生成設定。如果為不支援這些設定選項的模型設定這個欄位,系統會傳回錯誤。

mediaResolution enum (MediaResolution)

(選用步驟) 如果指定,系統會使用指定的媒體解析度。

enableAffectiveDialog boolean

(選用步驟) 啟用後,模型會偵測情緒並據此調整回覆。

responseFormat object (ResponseFormatConfig)

(選用步驟) 回覆輸出格式的設定。可透過平面結構,指定各模態 (文字、音訊、圖片) 的輸出設定。

translationConfig object (TranslationConfig)

(選用步驟) 翻譯設定。

audioTranscriptionConfig object (AudioTranscriptionConfig)

(選用步驟) 音訊轉錄 (語音辨識) 設定。

JSON 表示法
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "_responseJsonSchema": value,
  "responseJsonSchema": value,
  "responseModalities": [
    enum (Modality)
  ],
  "candidateCount": integer,
  "maxOutputTokens": integer,
  "temperature": number,
  "topP": number,
  "topK": integer,
  "seed": integer,
  "presencePenalty": number,
  "frequencyPenalty": number,
  "responseLogprobs": boolean,
  "logprobs": integer,
  "enableEnhancedCivicAnswers": boolean,
  "speechConfig": {
    object (SpeechConfig)
  },
  "thinkingConfig": {
    object (ThinkingConfig)
  },
  "imageConfig": {
    object (ImageConfig)
  },
  "mediaResolution": enum (MediaResolution),
  "enableAffectiveDialog": boolean,
  "responseFormat": {
    object (ResponseFormatConfig)
  },
  "translationConfig": {
    object (TranslationConfig)
  },
  "audioTranscriptionConfig": {
    object (AudioTranscriptionConfig)
  }
}

模態

回覆支援的模態。

列舉
MODALITY_UNSPECIFIED 預設值。
TEXT 表示模型應傳回文字。
IMAGE 表示模型應傳回圖片。
AUDIO 表示模型應傳回音訊。

SpeechConfig

語音生成和轉錄的設定。

欄位
voiceConfig object (VoiceConfig)

單一語音輸出的設定。

multiSpeakerVoiceConfig object (MultiSpeakerVoiceConfig)

(選用步驟) 多喇叭設定。與 voiceConfig 欄位互斥。

languageCode string

(選用步驟) 使用者設定應用程式使用的 IETF BCP-47 語言代碼。用於語音辨識及合成。

有效值為:de-DE、en-AU、en-GB、en-IN、en-US、es-US、fr-FR、hi-IN、pt-BR、ar-XA、es-ES、fr-CA、id-ID、it-IT、ja-JP、tr-TR、vi-VN、bn-IN、gu-IN、kn-IN、ml-IN、mr-IN、ta-IN、te-IN、nl-NL、ko-KR、cmn-CN、pl-PL、ru-RU 和 th-TH。

JSON 表示法
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}

VoiceConfig

要使用的語音設定。

欄位
voice_config Union type
說話者要使用的設定。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
prebuiltVoiceConfig object (PrebuiltVoiceConfig)

要使用的預建語音設定。

voice string

(選用步驟) 合成用語音 ID。支援的格式:

  • 預建語音的說話者名稱 (例如 Orus 或 Kore)。
  • 儲存語音的語音 ID (例如 voice_xxx)。
  • 語音複製金鑰 (例如 voicekey_xxx)。
互斥欄位結束。
JSON 表示法
{

  // voice_config
  "prebuiltVoiceConfig": {
    object (PrebuiltVoiceConfig)
  },
  "voice": string
  // Union type
}

PrebuiltVoiceConfig

預建說話者要使用的設定。

欄位
voiceName string

(選用步驟) 要使用的預設語音名稱。

JSON 表示法
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

多喇叭設定。

欄位
speakerVoiceConfigs[] object (SpeakerVoiceConfig)

必填。所有已啟用的說話者聲音。

JSON 表示法
{
  "speakerVoiceConfigs": [
    {
      object (SpeakerVoiceConfig)
    }
  ]
}

SpeakerVoiceConfig

多位說話者設定中,單一說話者的設定。

欄位
speaker string

必填。要使用的說話者名稱。應與提示中的內容相同。

voiceConfig object (VoiceConfig)

必填。要使用的語音設定。

JSON 表示法
{
  "speaker": string,
  "voiceConfig": {
    object (VoiceConfig)
  }
}

ThinkingConfig

思考功能的設定。

欄位
includeThoughts boolean

指出是否要在回覆中加入思考過程。如果設為 true,則只會在有思考過程時傳回。

thinkingBudget integer

模型應生成的思考詞元數量。

thinkingLevel enum (ThinkingLevel)

(選用步驟) 控制模型內部推論過程的最大深度,超過這個深度就會產生回覆。預設值因模型而異。詳情請參閱思考層級指南。建議用於 Gemini 3 以上版本。如果與舊版模型搭配使用,會導致錯誤。

JSON 表示法
{
  "includeThoughts": boolean,
  "thinkingBudget": integer,
  "thinkingLevel": enum (ThinkingLevel)
}

ThinkingLevel

允許使用者使用列舉 (而非整數預算) 指定思考程度。

列舉
THINKING_LEVEL_UNSPECIFIED 預設值。
MINIMAL 幾乎不需思考。
LOW 思考程度低。
MEDIUM 中度思考。
HIGH 高思考程度。

ImageConfig

圖像生成功能的設定。

欄位
aspectRatio string

(選用步驟) 要生成的圖片顯示比例。支援的顯示比例:1:1、1:4、4:1、1:8、8:1、2:3、3:2、3:4、4:3、4:5、5:4、9:16、16:9 或 21:9。

如未指定,模型會根據提供的參考圖像,選擇預設顯示比例。

imageSize string

(選用步驟) 指定生成圖像的大小。支援的值為 512、1K、2K、4K。如未指定,模型會使用預設值 1K。

JSON 表示法
{
  "aspectRatio": string,
  "imageSize": string
}

MediaResolution

輸入媒體的媒體解析度。

列舉
MEDIA_RESOLUTION_UNSPECIFIED 尚未設定媒體解析度。
MEDIA_RESOLUTION_LOW 媒體解析度設為低 (64 個詞元)。
MEDIA_RESOLUTION_MEDIUM 媒體解析度設為中 (256 個詞元)。
MEDIA_RESOLUTION_HIGH 媒體解析度設為高 (放大重新構圖,使用 256 個詞元)。

ResponseFormatConfig

回覆輸出格式的設定。這是平面物件,每個選用子欄位都會設定特定輸出模態。

欄位
text object (TextResponseFormat)

(選用步驟) 文字輸出格式設定。

audio object (AudioResponseFormat)

(選用步驟) 音訊輸出格式設定。

image object (ImageResponseFormat)

(選用步驟) 圖片輸出格式設定。

JSON 表示法
{
  "text": {
    object (TextResponseFormat)
  },
  "audio": {
    object (AudioResponseFormat)
  },
  "image": {
    object (ImageResponseFormat)
  }
}

TextResponseFormat

文字輸出格式的設定。

欄位
mimeType enum (MimeType)

(選用步驟) 文字輸出的 MIME 類型。

schema value (Value format)

(選用步驟) 輸出內容應符合的 JSON 結構定義。只有在 mimeType 為 APPLICATION_JSON 時才適用。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "schema": value
}

MimeType

文字輸出支援的 MIME 類型。

列舉
MIME_TYPE_UNSPECIFIED 預設值。這個值不會用到。
APPLICATION_JSON JSON 輸出格式。
TEXT_PLAIN 純文字輸出格式。

AudioResponseFormat

音訊輸出格式設定。

欄位
mimeType enum (MimeType)

(選用步驟) 音訊輸出的 MIME 類型。

delivery enum (Delivery)

(選用步驟) 音訊輸出的傳送模式。

sampleRate integer

(選用步驟) 取樣率 (Hz)。

bitRate integer

(選用步驟) 位元率,以每秒位元數 (bps) 為單位。僅適用於壓縮格式 (MP3、Opus)。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "delivery": enum (Delivery),
  "sampleRate": integer,
  "bitRate": integer
}

MimeType

音訊輸出支援的 MIME 類型。

列舉
MIME_TYPE_UNSPECIFIED 預設值。這個值不會用到。
AUDIO_MP3 MP3 音訊格式。
AUDIO_OGG_OPUS OGG Opus 音訊格式。
AUDIO_L16 原始 PCM (L16) 音訊格式。
AUDIO_WAV WAV 音訊格式。
AUDIO_ALAW A-law 音訊格式。
AUDIO_MULAW Mu-law 音訊格式。

外送

音訊輸出的傳送模式。

列舉
DELIVERY_UNSPECIFIED 預設值。這個值不會用到。
INLINE 音訊資料會以內嵌方式在回應中傳回。
URI 音訊資料會以 URI 形式傳回。

ImageResponseFormat

圖片輸出格式的設定。

欄位
mimeType enum (MimeType)

(選用步驟) 輸出圖片的 MIME 類型。

delivery enum (Delivery)

(選用步驟) 圖片輸出的傳送模式。

aspectRatio enum (AspectRatio)

(選用步驟) 輸出圖像的顯示比例。

imageSize enum (ImageSize)

(選用步驟) 輸出圖片的大小。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "delivery": enum (Delivery),
  "aspectRatio": enum (AspectRatio),
  "imageSize": enum (ImageSize)
}

MimeType

圖片輸出支援的 MIME 類型。

列舉
MIME_TYPE_UNSPECIFIED 預設值。這個值不會用到。
IMAGE_JPEG JPEG 圖片格式。

外送

圖片輸出的提供模式。

列舉
DELIVERY_UNSPECIFIED 預設值。這個值不會用到。
INLINE 圖片資料會以內嵌方式在回應中傳回。
URI 圖片資料會以 URI 形式傳回。

AspectRatio

支援的圖像輸出顯示比例。

列舉
ASPECT_RATIO_UNSPECIFIED 預設值。這個值不會用到。
ASPECT_RATIO_ONE_BY_ONE 顯示比例 1:1。
ASPECT_RATIO_TWO_BY_THREE 顯示比例 2:3。
ASPECT_RATIO_THREE_BY_TWO 顯示比例 3:2。
ASPECT_RATIO_THREE_BY_FOUR 顯示比例 3:4。
ASPECT_RATIO_FOUR_BY_THREE 4:3 顯示比例。
ASPECT_RATIO_FOUR_BY_FIVE 顯示比例 4:5。
ASPECT_RATIO_FIVE_BY_FOUR 5:4 顯示比例。
ASPECT_RATIO_NINE_BY_SIXTEEN 顯示比例 9:16。
ASPECT_RATIO_SIXTEEN_BY_NINE 顯示比例 16:9。
ASPECT_RATIO_TWENTY_ONE_BY_NINE 顯示比例 21:9。
ASPECT_RATIO_ONE_BY_EIGHT 1:8 顯示比例。
ASPECT_RATIO_EIGHT_BY_ONE 顯示比例 8:1。
ASPECT_RATIO_ONE_BY_FOUR 顯示比例 1:4。
ASPECT_RATIO_FOUR_BY_ONE 顯示比例 4:1。

ImageSize

支援的輸出圖片大小。

列舉
IMAGE_SIZE_UNSPECIFIED 預設值。這個值不會用到。
IMAGE_SIZE_FIVE_TWELVE 圖片大小為 512 像素。
IMAGE_SIZE_ONE_K 1K 圖片大小。
IMAGE_SIZE_TWO_K 2K 圖片大小。
IMAGE_SIZE_FOUR_K 4K 圖片大小。

TranslationConfig

翻譯功能的設定。

欄位
targetLanguageCode string

必填。翻譯的譯文語言。支援的值為 BCP-47 語言代碼 (例如「en」、「es」、「fr」)。

echoTargetLanguage boolean

(選用步驟) 如果設為 true,模型會在說出目標語言時生成音訊,基本上會模仿輸入內容。如果設為 false,系統就不會生成譯文語言的音訊。

JSON 表示法
{
  "targetLanguageCode": string,
  "echoTargetLanguage": boolean
}

AudioTranscriptionConfig

音訊轉錄設定。

欄位
languageCodes[] string

(選用步驟) BCP-47 語言代碼,提供音訊中語言的提示。如省略或留空,預設會自動偵測語言。

adaptationPhrases[]
(deprecated)
string

(選用步驟) 用於語音調整的詞組清單,可讓 ASR 模型偏向這些特定字詞,提高辨識準確度。

customVocabulary[] string

(選用步驟) 自訂詞彙詞組清單,可引導語音辨識模型辨識特定字詞 (產品名稱、專有名詞、專業術語)。

wordTimestamp boolean

(選用步驟) 設定字詞層級時間戳記生成功能。

diarization boolean

(選用步驟) 設定說話者分段標記。

mode enum (Mode)

(選用步驟) 設定語音轉錄模式。支援的值:VERBATIM、SMART。如未指定,預設為 VERBATIM 語音轉錄。在 SMART 模式下,模型會執行贅字移除 (刪除填充詞、重複內容和錯誤開頭)、稍微修正文法、自動設定格式 (段落、項目符號、編號清單),以及進行使用者的小幅編輯 (內嵌自我修正)。時間戳記和分段標記與模式 SMART 不相容。

language_config Union type
已淘汰:請改用頂層 language_codes。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
languageAuto
(deprecated)
object (LanguageAuto)

(選用步驟) 模型會自動偵測語言。

languageHints
(deprecated)
object (LanguageHints)

(選用步驟) 指定音訊中的一或多種語言。

互斥欄位結束。
JSON 表示法
{
  "languageCodes": [
    string
  ],
  "adaptationPhrases": [
    string
  ],
  "customVocabulary": [
    string
  ],
  "wordTimestamp": boolean,
  "diarization": boolean,
  "mode": enum (Mode),

  // language_config
  "languageAuto": {
    object (LanguageAuto)
  },
  "languageHints": {
    object (LanguageHints)
  }
  // Union type
}

LanguageAuto

這個類型沒有任何欄位。

表示應自動偵測音訊語言。

LanguageHints

向模型提供提示,指出音訊中可能出現的語言。

欄位
languageCodes[]
(deprecated)
string

必填。BCP-47 語言代碼。

JSON 表示法
{
  "languageCodes": [
    string
  ]
}

模式

語音轉錄模式。

列舉
MODE_UNSPECIFIED 未指定語音轉錄模式。
VERBATIM 逐字稿轉錄模式。
SMART 智慧語音轉錄模式。

RealtimeInputConfig

設定 BidiGenerateContent 中的即時輸入行為。

欄位
automaticActivityDetection object (AutomaticActivityDetection)

(選用步驟) 如未設定,系統預設會啟用自動偵測活動功能。如果停用自動語音偵測功能,用戶端必須傳送活動信號。

activityHandling enum (ActivityHandling)

(選用步驟) 定義活動的效果。

turnCoverage enum (TurnCoverage)

(選用步驟) 定義使用者回合中包含的輸入內容。

interimTranscriptTimestampEnabled boolean

(選用步驟) 設定臨時轉錄稿時間戳記。

JSON 表示法
{
  "automaticActivityDetection": {
    object (AutomaticActivityDetection)
  },
  "activityHandling": enum (ActivityHandling),
  "turnCoverage": enum (TurnCoverage),
  "interimTranscriptTimestampEnabled": boolean
}

AutomaticActivityDetection

設定自動偵測活動。

欄位
disabled boolean

(選用步驟) 啟用此設定 (預設) 後,偵測到的語音和文字輸入會視為活動。如果停用,用戶端必須傳送活動信號。

startOfSpeechSensitivity enum (StartSensitivity)

(選用步驟) 決定偵測到語音的可能性。

prefixPaddingMs integer

(選用步驟) 偵測到語音後,必須持續多久才會判定為語音開始。這個值越低,語音開頭偵測功能就越敏感,可辨識的語音長度也越短。不過,這也會提高偽陽性的機率。

endOfSpeechSensitivity enum (EndSensitivity)

(選用步驟) 決定偵測到的語音結束的可能性。

silenceDurationMs integer

(選用步驟) 偵測到非語音 (例如靜音) 的必要時間長度,超過這個長度就會判定語音結束。這個值越大,語音間隔時間就越長,不會中斷使用者的活動,但會增加模型的延遲時間。

JSON 表示法
{
  "disabled": boolean,
  "startOfSpeechSensitivity": enum (StartSensitivity),
  "prefixPaddingMs": integer,
  "endOfSpeechSensitivity": enum (EndSensitivity),
  "silenceDurationMs": integer
}

StartSensitivity

決定如何偵測語音起始處。

列舉
START_SENSITIVITY_UNSPECIFIED 預設值為 START_SENSITIVITY_HIGH。
START_SENSITIVITY_HIGH 自動偵測功能會更常偵測到語音的開頭。
START_SENSITIVITY_LOW 自動偵測功能偵測到語音開始的頻率會降低。

EndSensitivity

決定如何偵測語音結束。

列舉
END_SENSITIVITY_UNSPECIFIED 預設值為 END_SENSITIVITY_HIGH。
END_SENSITIVITY_HIGH 自動偵測功能會更頻繁地結束語音。
END_SENSITIVITY_LOW 自動偵測功能會減少結束語音的頻率。

ActivityHandling

處理使用者活動的不同方式。

列舉
ACTIVITY_HANDLING_UNSPECIFIED 如未指定,預設行為是 START_OF_ACTIVITY_INTERRUPTS。
START_OF_ACTIVITY_INTERRUPTS 如果設為 true,活動開始時會中斷模型的回覆 (也稱為「插話」)。模型目前的回覆會在您中斷時停止。此為預設行為。
NO_INTERRUPTION 模型的回覆不會中斷。

TurnCoverage

使用者回合中包含哪些輸入內容的選項。

列舉
TURN_COVERAGE_UNSPECIFIED 如未指定,系統會根據模型選取預設行為。舉例來說,Gemini 2.5 的預設值為 TURN_INCLUDES_ONLY_ACTIVITY,Gemini 3.1 以上版本則為 TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO。
TURN_INCLUDES_ONLY_ACTIVITY 包含上次對話後的活動,但不含不活動狀態 (例如音訊串流靜音)。
TURN_INCLUDES_ALL_INPUT 包含自上次對話以來的所有即時輸入內容,包括無活動 (例如音訊串流中的靜音)。
TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO 包括音訊活動和上一個回合以來的所有影片。如果啟用自動活動偵測功能,音訊活動是指語音,不包括靜音。

SessionResumptionConfig

工作階段繼續設定。

這則訊息會以 BidiGenerateContentSetup.session_resumption 的形式納入工作階段設定。設定完成後,伺服器會傳送 SessionResumptionUpdate 則訊息。

欄位
handle string

先前工作階段的控制代碼。如果沒有,則會建立新的工作階段。

工作階段控制代碼來自先前連線中的 SessionResumptionUpdate.token 值。

JSON 表示法
{
  "handle": string
}

ContextWindowCompressionConfig

啟用脈絡窗口壓縮功能,這項機制可管理模型的脈絡窗口,確保不超過指定長度。

欄位
compression_mechanism Union type
使用的脈絡窗口壓縮機制。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
slidingWindow object (SlidingWindow)

滑動式時間區間機制。

互斥欄位結束。
triggerTokens string (int64 format)

觸發脈絡窗口壓縮所需的詞元數量 (在執行一輪對話前)。

這項設定可用來平衡品質與延遲時間,因為較短的脈絡窗口可能會加快模型回覆速度。不過,任何壓縮作業都會導致延遲時間暫時增加,因此不應頻繁觸發。

如未設定,預設值為模型脈絡窗口限制的 80%。剩下的 20% 則用於下一個使用者要求/模型回覆。

JSON 表示法
{

  // compression_mechanism
  "slidingWindow": {
    object (SlidingWindow)
  }
  // Union type
  "triggerTokens": string
}

SlidingWindow

SlidingWindow 方法會捨棄脈絡視窗開頭的內容。產生的情境一律會從 USER 角色對話的開頭開始。系統指令和任何 BidiGenerateContentSetup.prefix_turns 一律會保留在結果開頭。

欄位
targetTokens string (int64 format)

要保留的目標權杖數量。預設值為 triggerTokens/2。

捨棄部分內容視窗會導致延遲時間暫時增加,因此應調整這個值,避免頻繁執行壓縮作業。

JSON 表示法
{
  "targetTokens": string
}

HistoryConfig

記錄設定。

這則訊息會以 BidiGenerateContentSetup.history_config 的形式納入工作階段設定。設定歷史訊息的交換。

欄位
initialHistoryInClientContent boolean

(選用步驟) 如果設為 true,伺服器會在傳送 setupComplete 後等待,並先處理 clientContent 訊息,直到 turnComplete 為 true。這項初始記錄不會觸發模型呼叫,且可能以角色 MODEL 結尾。turnComplete true後,用戶端就能透過 realtimeInput 開始即時對話。

JSON 表示法
{
  "initialHistoryInClientContent": boolean
}

方法:auth_tokens.create

建立權杖,可用於限制 BidiGenerateContent 工作階段的行為。

端點

貼文 https://generativelanguage.googleapis.com/v1beta/auth_tokens

要求主體

要求主體包含 AuthToken 的例項。

欄位
expireTime string (Timestamp format)

(選用步驟) 僅限輸入。不可變動。選用時間,超過這個時間後,使用產生的權杖時,BidiGenerateContent 工作階段中的訊息會遭到拒絕。(Gemini 可能會在這段時間後主動關閉工作階段)。

如未設定,則預設為 30 分鐘後。如果設定這個值,則必須小於 20 小時。

使用 RFC 3339,產生的輸出內容一律會經過 Z 正規化,並使用 0、3、6 或 9 個小數位數,也接受「Z」以外的偏移量。範例:"2014-10-02T15:01:23Z"、"2014-10-02T15:01:23.045123456Z" 或 "2014-10-02T15:01:23+05:30"。

newSessionExpireTime string (Timestamp format)

(選用步驟) 僅限輸入。不可變動。超過這個時間後,使用這項要求產生的權杖建立新的 Live API 工作階段,將會遭到拒絕。

如未設定,預設值為 60 秒後。如果設定這個值,則必須小於 20 小時。

使用 RFC 3339,產生的輸出內容一律會經過 Z 正規化,並使用 0、3、6 或 9 個小數位數,也接受「Z」以外的偏移量。範例:"2014-10-02T15:01:23Z"、"2014-10-02T15:01:23.045123456Z" 或 "2014-10-02T15:01:23+05:30"。

fieldMask string (FieldMask format)

(選用步驟) 僅限輸入。不可變動。如果 fieldMask 為空白,且沒有 bidiGenerateContentSetup,則有效的 BidiGenerateContentSetup 訊息會取自 Live API 連線。

如果 fieldMask 為空白,且bidiGenerateContentSetup 存在,則有效的BidiGenerateContentSetup訊息會完全取自這項要求中的bidiGenerateContentSetup。系統會忽略 Live API 連線的設定訊息。

如果 fieldMask 不是空白,bidiGenerateContentSetup 的對應欄位會覆寫 Live API 連線中設定訊息的欄位。

這是以半形逗號分隔的完整欄位名稱清單,範例:"user.displayName,photo"。

config Union type
產生權杖的方法專屬設定。以下是互斥欄位清單。回應中最多會設定下列其中一個欄位:
bidiGenerateContentSetup object (BidiGenerateContentSetup)

(選用步驟) 僅限輸入。不可變動。BidiGenerateContent 專用設定。

互斥欄位結束。
uses integer

(選用步驟) 僅限輸入。不可變動。權杖可使用的次數。如果這個值為零,則不會套用任何限制。恢復 Live API 工作階段不計入使用次數。如未指定,預設值為 1。

回應主體

如果成功,回應主體會包含新建立的 AuthToken 執行個體。