Generating content

Gemini API 支援生成圖片、音訊、程式碼、工具等內容,如要瞭解這些功能的詳細資訊,請繼續閱讀並查看以工作為導向的範例程式碼,或參閱完整指南。

方法:models.generateContent

根據輸入內容 GenerateContentRequest 生成模型回覆。如需詳細使用資訊,請參閱文字生成指南。輸入功能會因模型而異,包括微調模型。詳情請參閱模型指南微調指南

端點

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

路徑參數

model string

必填。用於生成完成內容的 Model 名稱。

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

要求主體

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

欄位
contents[] object (Content)

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

如果是單輪查詢,這就是單一執行個體。如果是多輪查詢 (例如「聊天」),這個欄位會重複出現,內含對話記錄和最新要求。

tools[] object (Tool)

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

Tool是一段程式碼,可讓系統與外部系統互動,在Model的知識和範圍外執行動作或一連串動作。支援的 ToolFunctioncodeExecution。詳情請參閱「呼叫函式」和「執行程式碼」指南。

toolConfig object (ToolConfig)

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

safetySettings[] object (SafetySetting)

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

這項規定將於 GenerateContentRequest.contentsGenerateContentResponse.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 應用程式中納入安全考量。

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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-flash" });
  const chatResponse = await chat.sendMessage({
    message: "The final result is " + resultValue,
  });
  console.log(chatResponse.text);
  return chatResponse;
}

貝殼


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.7-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.7-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.7-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.7-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.7-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.7-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.7-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);
  return response;
}

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.7-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.7-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.7-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.7-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.7-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.7-flash",
                "Good morning! How are you?",
                config);

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

回應主體

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

方法:models.streamGenerateContent

根據輸入內容 GenerateContentRequest,從模型生成串流回覆

端點

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

路徑參數

model string

必填。用於生成完成內容的 Model 名稱。

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

要求主體

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

欄位
contents[] object (Content)

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

如果是單輪查詢,這就是單一執行個體。如果是多輪查詢 (例如「聊天」),這個欄位會重複出現,內含對話記錄和最新要求。

tools[] object (Tool)

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

Tool是一段程式碼,可讓系統與外部系統互動,在Model的知識和範圍外執行動作或一連串動作。支援的 ToolFunctioncodeExecution。詳情請參閱「呼叫函式」和「執行程式碼」指南。

toolConfig object (ToolConfig)

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

safetySettings[] object (SafetySetting)

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

這項規定將於 GenerateContentRequest.contentsGenerateContentResponse.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 應用程式中納入安全考量。

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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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.7-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 中的提示和 finishReasonsafetyRatings 中的每個候選項目,回報安全評分和內容篩選結果。API: - 會傳回所有要求候選項目,或完全不傳回任何項目 - 只有在提示有誤時,才會完全不傳回任何候選項目 (請檢查 promptFeedback) - 會在 finishReasonsafetyRatings 中回報每個候選項目的意見回饋。

Fields
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 中指定的一組意見回饋中繼資料。

Fields
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

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

Fields
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

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

Fields
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 這個階段的模型會淘汰。無法使用這些模型。

候選人

模型生成的候選回覆。

Fields
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)

僅供輸出。與網址背景資訊擷取工具有關的中繼資料。

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)
  },
  "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 要求已由提報規則篩除。

GroundingAttribution

對促成答案的來源進行出處標註。

Fields
sourceId object (AttributionSourceId)

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

content object (Content)

構成這項出處資訊的基礎來源內容。

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

AttributionSourceId

促成這項歸因的來源 ID。

欄位
source Union type
source 只能是下列其中一項:
groundingPassage object (GroundingPassageId)

內嵌段落的 ID。

semanticRetrieverChunk object (SemanticRetrieverChunk)

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

JSON 表示法
{

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

GroundingPassageId

GroundingPassage 中零件的 ID。

Fields
passageId string

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

partIndex integer

僅供輸出。GenerateAnswerRequestGroundingPassage.content 內零件索引。

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

SemanticRetrieverChunk

透過 SemanticRetrieverConfigGenerateAnswerRequest 中指定的語意擷取器擷取的 Chunk ID。

Fields
source string

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

chunk string

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

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

GroundingMetadata

啟用基礎模型時傳回給用戶端的中繼資料。

Fields
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 搜尋進入點。

Fields
renderedContent string

(選用步驟) 可內嵌在網頁或應用程式網頁檢視畫面中的網頁內容程式碼片段。

sdkBlob string (bytes format)

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

Base64 編碼字串。

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

GroundingChunk

GroundingChunk 代表模型回覆所依據的佐證片段。可以是網頁上的內容片段、從檔案擷取的內容,或是 Google 地圖上的資訊。

欄位
chunk_type Union type
區塊類型。chunk_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
}

網頁

網路上的區塊。

Fields
uri string

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

title string

僅供輸出。區塊的標題。

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

圖片

圖片搜尋結果中的區塊。

Fields
sourceUri string

歸因的網頁 URI。

imageUri string

圖片素材資源網址。

title string

圖片來源網頁的標題。

domain string

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

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

RetrievedContext

檔案搜尋工具擷取的脈絡區塊。

Fields
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 中繼資料。

Fields
key string

中繼資料的鍵。

value Union type
中繼資料的值。可以是字串、字串清單或數字。value 只能是下列其中一項:
stringValue string

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

stringListValue object (StringList)

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

numericValue number

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

JSON 表示法
{
  "key": string,

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

StringList

字串值清單。

Fields
values[] string

清單的字串值。

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

地圖

Google 地圖的建立基準區塊。地圖區塊對應到單一地點。

Fields
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 地圖工具會使用這些來源回答地點功能相關問題 (例如「Bar Foo 有 Wi-Fi 嗎?」或「Foo Bar 是否提供無障礙設施?」)。目前我們僅支援評論摘要做為來源。

Fields
reviewSnippets[] object (ReviewSnippet)

用於生成 Google 地圖中特定地點功能相關答案的評論片段。

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

ReviewSnippet

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

Fields
reviewId string

評論摘錄的 ID。

googleMapsUri string

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

title string

評論標題。

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

GroundingSupport

支援建立基準。

Fields
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)
  }
}

區隔

內容片段。

Fields
partIndex integer

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

startIndex integer

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

endIndex integer

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

text string

回應中與區段對應的文字。

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

RetrievalMetadata

與基礎流程中的擷取作業相關的中繼資料。

Fields
googleSearchDynamicRetrievalScore number

(選用步驟) 分數:表示 Google 搜尋資訊有多大可能協助回答提示。分數範圍為 [0, 1],其中 0 表示最不可能,1 表示最有可能。只有在啟用 Google 搜尋基礎和動態擷取功能時,系統才會填入這項分數。系統會將這項分數與門檻進行比較,判斷是否要觸發 Google 搜尋。

JSON 表示法
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

Logprobs 結果

Fields
topCandidates[] object (TopCandidates)

長度 = 解碼步驟總數。

chosenCandidates[] object (Candidate)

長度 = 解碼步驟總數。所選候選字可能位於 topCandidates 中,也可能不在其中。

logProbabilitySum number

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

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

TopCandidates

在每個解碼步驟中,記錄機率最高的候選字詞。

Fields
candidates[] object (Candidate)

依對數機率遞減排序。

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

候選人

記錄機率的候選權杖和分數。

Fields
token string

候選人的權杖字串值。

tokenId integer

候選人的權杖 ID 值。

logProbability number

候選者的記錄機率。

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

UrlContextMetadata

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

Fields
urlMetadata[] object (UrlMetadata)

網址背景資訊清單。

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

UrlMetadata

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

Fields
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

內容的來源出處集合。

Fields
citationSources[] object (CitationSource)

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

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

CitationSource

特定回覆部分內容的來源出處。

Fields
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 - 針對特定身分和/或受保護特質發表負面或有害言論。
HARM_CATEGORY_TOXICITY PaLM - 粗魯、不敬或不雅的內容。
HARM_CATEGORY_VIOLENCE PaLM - 描述對個人或群體施暴的場景,或一般血腥內容。
HARM_CATEGORY_SEXUAL PaLM - 提及性行為或其他猥褻情事的內容。
HARM_CATEGORY_MEDICAL PaLM - 宣傳未經查證的醫療建議。
HARM_CATEGORY_DANGEROUS PaLM - 宣傳、鼓吹或助長有害舉動的危險內容。
HARM_CATEGORY_HARASSMENT Gemini - 騷擾內容。
HARM_CATEGORY_HATE_SPEECH Gemini - 仇恨言論和內容。
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini - 情色露骨內容。
HARM_CATEGORY_DANGEROUS_CONTENT Gemini - Dangerous content.
HARM_CATEGORY_CIVIC_INTEGRITY

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

HARM_CATEGORY_JAILBREAK Gemini - 試圖規避或顛覆模型安全規範的提示 (越獄嘗試)。

ModalityTokenCount

代表單一模態的權杖計數資訊。

Fields
modality enum (Modality)

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

tokenCount integer

權杖數量。

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

模態

內容部分模式

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

SafetyRating

內容的安全評分。

安全評分包含內容的危害類別,以及該類別的危害機率等級。系統會根據多個危害類別對內容進行安全分類,並在此處顯示內容屬於特定危害類別的機率。

Fields
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

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

通過類別的安全設定後,系統允許封鎖內容的機率就會隨之變更。

Fields
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 內容的風險評估結果為「微乎其微」和「低」時,即允許上傳。
BLOCK_ONLY_HIGH 內容的風險等級為「微不足道」、「低」和「中」時,將可正常顯示。
BLOCK_NONE 允許所有內容。
OFF 關閉安全篩選器。

ServiceTier

要求服務層級。

列舉
unspecified 預設服務層級 (標準)。
standard 標準服務級別。
flex 彈性服務級別。
priority 優先服務等級。

內容

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

Content 包含指定 Content 生產端的 role 欄位,以及包含多部分資料的 parts 欄位,其中包含訊息輪流傳送的內容。

Fields
parts[] object (Part)

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

role string

(選用步驟) 內容製作人。必須為「user」或「model」。

建議為多輪對話設定,否則可以留空或不設定。

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

配件

包含媒體的資料型別,是多部分 Content 訊息的一部分。

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

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

Fields
thought boolean

(選用步驟) 指出該部分是否為模型所想。

thoughtSignature string (bytes format)

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

Base64 編碼字串。

partMetadata object (Struct format)

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

mediaResolution object (MediaResolution)

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

mediaProcessing enum (MediaProcessing)

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

data Union type
data 只能是下列其中一項:
text string

內嵌文字。

inlineData object (Blob)

內嵌媒體位元組。

functionCall object (FunctionCall)

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

functionResponse object (FunctionResponse)

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

fileData object (FileData)

以 URI 為基礎的資料。

executableCode object (ExecutableCode)

模型生成的程式碼,可供執行。

codeExecutionResult object (CodeExecutionResult)

執行 ExecutableCode 的結果。

toolCall object (ToolCall)

伺服器端工具呼叫。如果模型預測應在伺服器上執行的工具呼叫,系統會在此欄位中填入資料。用戶端應將這則訊息回送給 API。

toolResponse object (ToolResponse)

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

metadata Union type
控制資料的額外預先處理作業。metadata 只能是下列其中一項:
videoMetadata object (VideoMetadata)

(選用步驟) 影片中繼資料。只有在影片資料以 inlineData 或 fileData 形式呈現時,才應指定中繼資料。

JSON 表示法
{
  "thought": boolean,
  "thoughtSignature": string,
  "partMetadata": {
    object
  },
  "mediaResolution": {
    object (MediaResolution)
  },
  "mediaProcessing": enum (MediaProcessing),

  // 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」欄位。

Fields
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 編碼字串。

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

FunctionCall

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

Fields
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

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

Fields
id string

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

name string

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

response object (Struct format)

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

如要加入多媒體,請使用含有單一「$ref」鍵的子物件,該鍵的值是保存多媒體的 FunctionResponsePartinlineData.display_name。請參閱 https://ai.google.dev/gemini-api/docs/function-calling#multimodal

parts[] object (FunctionResponsePart)

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

willContinue boolean

(選用步驟) 表示函式呼叫會繼續,並傳回更多回應,將函式呼叫變成產生器。僅適用於 NON_BLOCKING 函式呼叫,否則會遭到忽略。如果設為 false,系統就不會將之後的回覆納入考量。允許傳回空白 responsewillContinue=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
函式回應部分的資料。data 只能是下列其中一項:
inlineData object (FunctionResponseBlob)

內嵌媒體位元組。

JSON 表示法
{

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

FunctionResponseBlob

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

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

Fields
mimeType string

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

data string (bytes format)

媒體格式的原始位元組。

Base64 編碼字串。

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

排程

指定在對話中安排回覆的方式。

列舉
SCHEDULING_UNSPECIFIED 這個值不會使用。
SILENT 只將結果加入對話內容,請勿中斷或觸發生成作業。
WHEN_IDLE 將結果新增至對話內容,並提示生成輸出內容,不必中斷正在進行的生成作業。
INTERRUPT 將結果新增至對話內容、中斷正在進行的生成作業,並提示生成輸出內容。

FileData

以 URI 為基礎的資料。

Fields
mimeType string

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

fileUri string

必填。URI。

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

ExecutableCode

模型生成的程式碼 (用於執行),以及傳回給模型的結果。

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

Fields
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 工具時才會產生。

Fields
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 連同對應的 ToolResponse 傳回 API。

Fields
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 連同對應的 ToolCall 傳回 API。

Fields
id string

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

toolType enum (ToolType)

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

response object (Struct format)

(選用步驟) 工具回應。

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

VideoMetadata

已淘汰:請改用 GenerateContentRequest.processing_options。中繼資料會說明輸入的影片內容。

Fields
startOffset string (Duration format)

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

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

endOffset string (Duration format)

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

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

fps number

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

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

MediaResolution

權杖化的媒體解析度。

欄位
value Union type
媒體解析度等級。value 只能是下列其中一項:
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 預設。使用特定型號的處理方式 (3.5 Pro+ -> AGENTIC,舊型號 -> STATIC)。
STATIC 固定費率影格擷取。所有影格都已放置在內容中。
AGENTIC 模型驅動的動態導覽。適用於大部分用途。

環境

代理的執行環境。

Fields
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
環境的網路設定。network 只能是下列其中一項:
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 結構定義物件的選取子集。

Fields
type enum (Type)

必填。資料類型。

format string

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

title string

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

description string

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

nullable boolean

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

enum[] string

(選用步驟) Type.STRING 元素可能的值,格式為列舉。舉例來說,我們可以將列舉「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 的結構定義欄位。類型為 STRING 的長度下限

maxLength string (int64 format)

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

pattern string

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

example value (Value format)

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

anyOf[] object (Schema)

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

propertyOrdering[] string

(選用步驟) 屬性的順序。這不是 OpenAPI 規格中的標準欄位,而是用於判斷回應中屬性的順序。

default value (Value format)

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

items object (Schema)

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

minimum number

(選用步驟) 類型為 INTEGER 和 NUMBER 的結構定義欄位。類型為 INTEGER 和 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 包含 OpenAPI 資料型別清單,如 https://spec.openapis.org/oas/v3.0.3#data-types 所定義

列舉
TYPE_UNSPECIFIED 未指定,請勿使用。
STRING 字串類型。
NUMBER 電話號碼類型。
INTEGER 整數類型。
BOOLEAN 布林類型。
ARRAY 陣列類型。
OBJECT 物件類型。
NULL 空值型別。

工具

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

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

下一個 ID:17

Fields
functionDeclarations[] object (FunctionDeclaration)

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

模型或系統未執行函式。而是將定義的函式做為 FunctionCall 傳回,並附上引數,供用戶端執行。模型可能會決定呼叫這些函式的一部分,方法是在回應中填入 FunctionCall。下一個對話回合可能包含 FunctionResponse,其中含有下一個模型回合的 Content.role「function」生成內容。

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,並由用戶端執行。

Fields
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 提供,可擷取公開網路資料做為基準。

Fields
dynamicRetrievalConfig object (DynamicRetrievalConfig)

指定指定來源的動態擷取設定。

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

DynamicRetrievalConfig

說明自訂動態擷取的選項。

Fields
mode enum (Mode)

要在動態擷取中使用的預測器模式。

dynamicThreshold number

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

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

模式

要在動態擷取中使用的預測器模式。

列舉
MODE_UNSPECIFIED 一律觸發擷取作業。
MODE_DYNAMIC 只有在系統判斷有必要時才執行擷取作業。

CodeExecution

這個類型沒有任何欄位。

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

另請參閱 ExecutableCodeCodeExecutionResult,這些內容只會在您使用這項工具時生成。

GoogleSearch

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

Fields
timeRangeFilter object (Interval)

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

searchTypes object (SearchTypes)

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

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

時間間隔

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

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

Fields
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 工具上啟用的不同搜尋類型。

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

WebSearch

這個類型沒有任何欄位。

標準網頁搜尋,用於強化事實基礎和相關設定。

ImageSearch

這個類型沒有任何欄位。

圖片搜尋功能,可做為基礎和相關設定。

ComputerUse

電腦使用工具類型。

Fields
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

這項工具會從語意檢索語料庫中檢索知識。使用 ImportFile API 將檔案匯入語意擷取語料庫。

Fields
fileSearchStoreNames[] string

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

metadataFilter string

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

topK integer

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

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

McpServer

MCPServer 是模型可呼叫的伺服器,可執行動作。這是實作 MCP 通訊協定的伺服器。下一個 ID:6

Fields
name string

MCPServer 的名稱。

transport Union type
用來連線至 MCPServer 的傳輸方式。transport 只能是下列其中一項:
streamableHttpTransport object (StreamableHttpTransport)

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

JSON 表示法
{
  "name": string,

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

StreamableHttpTransport

可串流傳輸 HTTP 要求和回應的傳輸方式。下一個 ID:6

Fields
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

Google 地圖工具,可為使用者的查詢提供地理空間脈絡。

Fields
enableWidget boolean

(選用步驟) 是否要在回應的 GroundingMetadata 中傳回小工具內容符記。開發人員可以使用小工具內容權杖,根據模型在回覆中提及的地點,顯示相關的地理空間背景資訊,並據此顯示 Google 地圖小工具。

JSON 表示法
{
  "enableWidget": boolean
}

REST 資源:auth_tokens

資源:AuthToken

要求建立臨時驗證權杖。

Fields
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,系統會從 Live API 連線取得有效的 BidiGenerateContentSetup 訊息。

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

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

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

config Union type
產生權杖的方法專屬設定。config 只能是下列其中一項:
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 訊息,再傳送任何其他訊息。

Fields
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)

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

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)
  }
}

GenerationConfig

模型生成和輸出內容的設定選項。並非所有模型都可設定所有參數。

Fields
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 文字生成指南

_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,則只能設定以 $ 開頭的屬性。

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]。

topP number

(選用步驟) 取樣時要考慮的符記累積分數上限。

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

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

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

topK integer

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

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

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

seed integer

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

presencePenalty number

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

這項處罰是二進位制,不會根據權杖的使用次數 (第一次之後) 而有所不同。使用 frequencyPenalty,每次使用都會增加處罰。

正向懲罰會阻止使用回應中已使用的符記,進而增加詞彙。

負向懲罰會鼓勵使用已在回覆中使用的符記,減少詞彙。

frequencyPenalty number

(選用步驟) 套用至下一個符記 logprobs 的頻率懲罰,乘以目前為止在回應中看到每個符記的次數。

正向懲罰會抑制模型使用已用過的權杖,且抑制程度與權杖的使用次數成正比:權杖使用次數越多,模型就越難再次使用該權杖,進而增加回覆的詞彙。

注意:懲罰會鼓勵模型重複使用詞元,比例與詞元的使用次數成正比。如果值為負數,回覆的詞彙就會減少。如果負值越大,模型就會開始重複常見的權杖,直到達到 maxOutputTokens 限制為止。

responseLogprobs boolean

(選用步驟) 設為 true 時,回應會匯出 logprobs 結果。

logprobs integer

(選用步驟) 必須設定 responseLogprobs=True 才會生效。這會設定在 Candidate.logprobs_result 的每個解碼步驟中,要傳回的最高 logprobs 數量,包括所選候選項目。數字必須介於 [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

語音生成和轉錄的設定。

Fields
voiceConfig object (VoiceConfig)

單一語音輸出時的設定。

multiSpeakerVoiceConfig object (MultiSpeakerVoiceConfig)

(選用步驟) 多音箱設定的設定。與 voiceConfig 欄位互斥。

languageCode string

(選用步驟) 使用者設定應用程式使用的 IETF BCP-47 語言代碼。用於語音辨識和合成。

有效值為:de-DEen-AUen-GBen-INen-USes-USfr-FRhi-INpt-BRar-XAes-ESfr-CAid-IDit-ITja-JPtr-TRvi-VNbn-INgu-INkn-INml-INmr-INta-INte-INnl-NLko-KRcmn-CNpl-PLru-RUth-TH

JSON 表示法
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}

VoiceConfig

要使用的語音設定。

欄位
voice_config Union type
音箱要使用的設定。voice_config 只能是下列其中一項:
prebuiltVoiceConfig object (PrebuiltVoiceConfig)

要使用的預建語音設定。

JSON 表示法
{

  // voice_config
  "prebuiltVoiceConfig": {
    object (PrebuiltVoiceConfig)
  }
  // Union type
}

PrebuiltVoiceConfig

預先建構的音箱要使用的設定。

Fields
voiceName string

要使用的預設語音名稱。

JSON 表示法
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

多音箱設定的設定。

Fields
speakerVoiceConfigs[] object (SpeakerVoiceConfig)

必填。所有已啟用的音箱語音。

JSON 表示法
{
  "speakerVoiceConfigs": [
    {
      object (SpeakerVoiceConfig)
    }
  ]
}

SpeakerVoiceConfig

多揚聲器設定中單一揚聲器的設定。

Fields
speaker string

必填。要使用的音箱名稱。應與提示中的內容相同。

voiceConfig object (VoiceConfig)

必填。要使用的語音設定。

JSON 表示法
{
  "speaker": string,
  "voiceConfig": {
    object (VoiceConfig)
  }
}

ThinkingConfig

思考功能的設定。

Fields
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

圖片生成功能的設定。

Fields
aspectRatio string

(選用步驟) 要生成的圖片顯示比例。支援的顯示比例:1:11:44:11:88:12:33:23:44:34:55:49:1616:921:9

如未指定,模型會根據提供的任何參考圖片選擇預設顯示比例。

imageSize string

(選用步驟) 指定生成的圖片大小。支援的值為 5121K2K4K。如未指定,模型會使用預設值 1K

JSON 表示法
{
  "aspectRatio": string,
  "imageSize": string
}

MediaResolution

輸入媒體的媒體解析度。

列舉
MEDIA_RESOLUTION_UNSPECIFIED 尚未設定媒體解析度。
MEDIA_RESOLUTION_LOW 媒體解析度設為低 (64 個權杖)。
MEDIA_RESOLUTION_MEDIUM 媒體解析度設為中等 (256 個權杖)。
MEDIA_RESOLUTION_HIGH 媒體解析度設為高 (縮放重構,含 256 個權杖)。

ResponseFormatConfig

回覆輸出格式的設定。這是平面物件,每個選用子欄位都會設定特定輸出模式。

Fields
text object (TextResponseFormat)

(選用步驟) 文字輸出格式設定。

audio object (AudioResponseFormat)

(選用步驟) 音訊輸出格式設定。

image object (ImageResponseFormat)

(選用步驟) 圖片輸出格式設定。

JSON 表示法
{
  "text": {
    object (TextResponseFormat)
  },
  "audio": {
    object (AudioResponseFormat)
  },
  "image": {
    object (ImageResponseFormat)
  }
}

TextResponseFormat

文字輸出格式的設定。

Fields
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

音訊輸出格式設定。

Fields
mimeType enum (MimeType)

(選用步驟) 音訊輸出的 MIME 類型。

delivery enum (Delivery)

(選用步驟) 音訊輸出的放送模式。

sampleRate integer

(選用步驟) 取樣率 (赫茲)。

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

圖片輸出格式的設定。

Fields
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

翻譯功能設定。

Fields
targetLanguageCode string

必填。譯文語言。支援的值為 BCP-47 語言代碼 (例如「en」、「es」、「fr」)。

echoTargetLanguage boolean

(選用步驟) 如果為 true,模型會在說出目標語言時生成音訊,基本上就是模仿輸入內容。如果設為 false,系統就不會生成目標語言的音訊。

JSON 表示法
{
  "targetLanguageCode": string,
  "echoTargetLanguage": boolean
}

AudioTranscriptionConfig

音訊轉錄設定。

Fields
languageCodes[] string

(選用步驟) BCP-47 語言代碼,提供音訊中語言的提示。如果省略或留空,系統會預設為自動偵測語言。

adaptationPhrases[]
(deprecated)
string

(選用步驟) 用於語音調整的詞組清單,可讓 ASR 模型偏向辨識這些特定字詞,進而提升辨識準確度。

customVocabulary[] string

(選用步驟) 自訂詞彙片語清單,引導語音辨識模型辨識特定字詞 (產品名稱、專有名詞、專業術語)。

wordTimestamp boolean

(選用步驟) 設定字詞層級時間戳記的產生方式。

diarization boolean

(選用步驟) 設定說話者分段標記。

language_config Union type
已淘汰:請改用頂層的 language_codeslanguage_config 只能是下列其中一項:
languageAuto
(deprecated)
object (LanguageAuto)

(選用步驟) 模型會自動偵測語言。

languageHints
(deprecated)
object (LanguageHints)

(選用步驟) 指定音訊中的一或多種語言。

JSON 表示法
{
  "languageCodes": [
    string
  ],
  "adaptationPhrases": [
    string
  ],
  "customVocabulary": [
    string
  ],
  "wordTimestamp": boolean,
  "diarization": boolean,

  // language_config
  "languageAuto": {
    object (LanguageAuto)
  },
  "languageHints": {
    object (LanguageHints)
  }
  // Union type
}

LanguageAuto

這個類型沒有任何欄位。

指出系統應自動偵測音訊語言。

LanguageHints

為模型提供音訊中可能出現的語言提示。

Fields
languageCodes[]
(deprecated)
string

必填。BCP-47 語言代碼。

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

RealtimeInputConfig

設定 BidiGenerateContent 中的即時輸入行為。

Fields
automaticActivityDetection object (AutomaticActivityDetection)

(選用步驟) 如果未設定,系統預設會啟用自動活動偵測功能。如果停用自動語音偵測功能,用戶端必須傳送活動信號。

activityHandling enum (ActivityHandling)

(選用步驟) 定義活動的影響。

turnCoverage enum (TurnCoverage)

(選用步驟) 定義使用者回合中包含的輸入內容。

JSON 表示法
{
  "automaticActivityDetection": {
    object (AutomaticActivityDetection)
  },
  "activityHandling": enum (ActivityHandling),
  "turnCoverage": enum (TurnCoverage)
}

AutomaticActivityDetection

設定自動偵測活動。

Fields
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 訊息。

Fields
handle string

先前工作階段的控制代碼。如果沒有,系統就會建立新工作階段。

工作階段控制代碼來自先前連線中的 SessionResumptionUpdate.token 值。

JSON 表示法
{
  "handle": string
}

ContextWindowCompressionConfig

啟用脈絡窗口壓縮功能,這項機制可管理模型的脈絡窗口,確保不會超過指定長度。

欄位
compression_mechanism Union type
使用的脈絡窗口壓縮機制。compression_mechanism 只能是下列其中一項:
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 一律會顯示在結果開頭。

Fields
targetTokens string (int64 format)

要保留的目標權杖數量。預設值為 triggerTokens/2。

捨棄部分內容視窗會導致暫時延遲增加,因此應校準這個值,避免頻繁的壓縮作業。

JSON 表示法
{
  "targetTokens": string
}

HistoryConfig

記錄設定。

這則訊息已納入工作階段設定,顯示為 BidiGenerateContentSetup.history_config。設定交換記錄訊息。

Fields
initialHistoryInClientContent boolean

(選用步驟) 如果為 true,伺服器會在傳送 setupComplete 後等待,並先處理 clientContent 訊息,直到 turnCompletetrue 為止。這項初始記錄不會觸發模型呼叫,且可能以角色 MODEL 結尾。turnComplete true 之後,用戶端即可透過 realtimeInput 開始即時對話。

JSON 表示法
{
  "initialHistoryInClientContent": boolean
}

方法:auth_tokens.create

建立權杖,可用於限制 BidiGenerateContent 工作階段的行為。

端點

post 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,系統會從 Live API 連線取得有效的 BidiGenerateContentSetup 訊息。

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

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

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

config Union type
產生權杖的方法專屬設定。config 只能是下列其中一項:
bidiGenerateContentSetup object (BidiGenerateContentSetup)

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

uses integer

(選用步驟) 僅供輸入。不可變動。代幣可使用的次數。如果這個值為零,系統就不會套用限制。繼續使用 Live API 工作階段不會計入用量。如未指定,則預設值為 1。

回應主體

如果成功,回應主體會包含新建立的 AuthToken 執行個體。