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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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 中回報每位候選人的意見回饋。

欄位
candidates[] object (Candidate)

模型提供的候選回覆。

promptFeedback object (PromptFeedback)

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

usageMetadata object (UsageMetadata)

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

modelVersion string

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

responseId string

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

modelStatus object (ModelStatus)

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

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

PromptFeedback

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

欄位
blockReason enum (BlockReason)

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

safetyRatings[] object (SafetyRating)

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

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

BlockReason

說明提示遭到封鎖的原因。

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

UsageMetadata

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

欄位
promptTokenCount integer

提示中的權杖數量。設定 cachedContent 時,這仍是有效提示的總大小,也就是說,這包括快取內容中的權杖數量。

cachedContentTokenCount integer

提示快取部分 (快取內容) 中的權杖數量

candidatesTokenCount integer

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

toolUsePromptTokenCount integer

僅供輸出。工具使用提示中的權杖數量。

thoughtsTokenCount integer

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

totalTokenCount integer

生成要求 (提示 + 想法 + 回覆候選項目) 的詞元數總計。

promptTokensDetails[] object (ModalityTokenCount)

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

cacheTokensDetails[] object (ModalityTokenCount)

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

candidatesTokensDetails[] object (ModalityTokenCount)

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

toolUsePromptTokensDetails[] object (ModalityTokenCount)

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

serviceTier enum (ServiceTier)

僅供輸出。要求服務層級。

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

ModelStatus

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

欄位
modelStage enum (ModelStage)

基礎模型的階段。

retirementTime string (Timestamp format)

模型淘汰時間。

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

message string

說明模型狀態的訊息。

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

ModelStage

定義基礎模型的階段。

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

基礎模型會經過大量調整。

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

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

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

候選人

模型生成的候選回覆。

欄位
content object (Content)

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

finishReason enum (FinishReason)

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

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

safetyRatings[] object (SafetyRating)

回覆候選內容安全評分清單。

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

citationMetadata object (CitationMetadata)

僅供輸出。模型生成的候選答案的引文資訊。

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

tokenCount integer

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

groundingAttributions[] object (GroundingAttribution)

僅供輸出。有助於生成基礎答案的來源出處資訊。

這個欄位會填入 GenerateAnswer 呼叫。

groundingMetadata object (GroundingMetadata)

僅供輸出。候選人的基礎中繼資料。

這個欄位會填入 GenerateContent 呼叫。

avgLogprobs number

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

logprobsResult object (LogprobsResult)

僅供輸出。回覆權杖和熱門權杖的對數似然分數

urlContextMetadata object (UrlContextMetadata)

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

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

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

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

欄位
passageId string

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

partIndex integer

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

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

SemanticRetrieverChunk

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

欄位
source string

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

chunk string

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

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

GroundingMetadata

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

欄位
groundingChunks[] object (GroundingChunk)

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

groundingSupports[] object (GroundingSupport)

基準建立支援清單。

webSearchQueries[] string

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

imageSearchQueries[] string

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

searchEntryPoint object (SearchEntryPoint)

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

retrievalMetadata object (RetrievalMetadata)

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

googleMapsWidgetContextToken string

(選用步驟) Google 地圖小工具內容權杖的資源名稱,可與 PlacesContextElement 小工具搭配使用,以便算繪內容比對資料。只有在啟用以 Google 地圖為基礎的服務時,才會填入這個欄位。

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

SearchEntryPoint

Google 搜尋進入點。

欄位
renderedContent string

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

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
}

網頁

網路上的區塊。

欄位
uri string

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

title string

僅供輸出。區塊的標題。

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

圖片

圖片搜尋結果中的區塊。

欄位
sourceUri string

歸因的網頁 URI。

imageUri string

圖片素材資源網址。

title string

圖片來源網頁的標題。

domain string

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

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

RetrievedContext

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

欄位
customMetadata[] object (CustomMetadata)

(選用步驟) 使用者提供的中繼資料,用於說明擷取的脈絡。

uri string

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

title string

(選用步驟) 文件標題。

text string

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

fileSearchStore string

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

pageNumber integer

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

mediaId string

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

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

CustomMetadata

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

欄位
key string

中繼資料的鍵。

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

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

stringListValue object (StringList)

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

numericValue number

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

JSON 表示法
{
  "key": string,

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

StringList

字串值清單。

欄位
values[] string

清單的字串值。

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

地圖

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

欄位
uri string

地點的 URI 參照。

title string

地點名稱。

text string

地點答案的文字說明。

placeId string

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

placeAnswerSources object (PlaceAnswerSources)

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

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

PlaceAnswerSources

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

欄位
reviewSnippets[] object (ReviewSnippet)

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

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

ReviewSnippet

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

欄位
reviewId string

評論摘錄的 ID。

googleMapsUri string

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

title string

評論標題。

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

GroundingSupport

支援基礎。

欄位
groundingChunkIndices[] integer

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

confidenceScores[] number

(選用步驟) 支援參考資料的可信度分數。範圍為 0 到 1。1 代表最有信心,這個清單的大小必須與 groundingChunkIndices 相同。

renderedParts[] integer

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

segment object (Segment)

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

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

區隔

內容片段。

欄位
partIndex integer

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

startIndex integer

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

endIndex integer

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

text string

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

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

RetrievalMetadata

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

欄位
googleSearchDynamicRetrievalScore number

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

JSON 表示法
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

Logprobs 結果

欄位
topCandidates[] object (TopCandidates)

長度 = 解碼步驟總數。

chosenCandidates[] object (Candidate)

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

logProbabilitySum number

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

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

TopCandidates

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

欄位
candidates[] object (Candidate)

依對數機率遞減排序。

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

候選人

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

欄位
token string

候選人的權杖字串值。

tokenId integer

候選人的權杖 ID 值。

logProbability number

候選者的記錄機率。

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

UrlContextMetadata

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

欄位
urlMetadata[] object (UrlMetadata)

網址背景資訊清單。

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

UrlMetadata

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

欄位
retrievedUrl string

工具擷取的網址。

urlRetrievalStatus enum (UrlRetrievalStatus)

網址擷取狀態。

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

UrlRetrievalStatus

網址擷取狀態。

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

CitationMetadata

內容的來源出處集合。

欄位
citationSources[] object (CitationSource)

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

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

CitationSource

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

欄位
startIndex integer

(選用步驟) 歸因於這個來源的回覆片段開頭。

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

endIndex integer

(選用步驟) 歸因區隔的結束時間 (不包含在內)。

uri string

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

license string

(選用步驟) GitHub 專案的授權,該專案會歸因於區隔的來源。

引用程式碼時必須提供授權資訊。

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

HarmCategory

可偵測使用者輸入內容和模型回覆中的有害類別。

列舉
HARM_CATEGORY_UNSPECIFIED 預設值。這個值不會使用。
HARM_CATEGORY_HATE_SPEECH 鼓吹暴力攻擊或煽動仇視具有某些特質的個人或群體。
HARM_CATEGORY_DANGEROUS_CONTENT 宣傳、鼓吹或助長危險活動的內容。
HARM_CATEGORY_HARASSMENT 不當、威脅或意圖霸凌、折磨或嘲笑他人的內容。
HARM_CATEGORY_SEXUALLY_EXPLICIT 含有煽情露骨內容。
HARM_CATEGORY_CIVIC_INTEGRITY

已淘汰:系統不再支援選舉篩選器。危害類別為公民誠信。

HARM_CATEGORY_IMAGE_HATE 含有仇恨言論的圖片。
HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT 含有危險內容的圖片。
HARM_CATEGORY_IMAGE_HARASSMENT 含有騷擾內容的圖片。
HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT 含有情色露骨內容的圖片。
HARM_CATEGORY_JAILBREAK 設計用來規避安全篩選機制的提示。

ModalityTokenCount

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

欄位
modality enum (Modality)

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

tokenCount integer

權杖數量。

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

模態

內容部分模式

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

SafetyRating

內容的安全評分。

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

欄位
category enum (HarmCategory)

必填。這項評分的類別。

probability enum (HarmProbability)

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

blocked boolean

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

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

HarmProbability

內容有害的機率。

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

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

SafetySetting

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

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

欄位
category enum (HarmCategory)

必填。這項設定的類別。

threshold enum (HarmBlockThreshold)

必填。控管系統封鎖有害內容的機率門檻。

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

HarmBlockThreshold

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

列舉
HARM_BLOCK_THRESHOLD_UNSPECIFIED 未指定門檻。
BLOCK_LOW_AND_ABOVE 內容的「可忽略」程度必須達到「可忽略」才能獲准。
BLOCK_MEDIUM_AND_ABOVE 內容的風險評估結果為「微乎其微」和「低」時,即允許上傳。
BLOCK_ONLY_HIGH 內容的風險等級為「微不足道」、「低」和「中」時,將可正常顯示。
BLOCK_NONE 允許所有內容。
OFF 關閉安全篩選器。

ServiceTier

互動的服務層級。

列舉
SERVICE_TIER_UNSPECIFIED 預設服務層級 (標準)。
SERVICE_TIER_FLEX 彈性服務級別。
SERVICE_TIER_STANDARD 標準服務級別。
SERVICE_TIER_PRIORITY 優先服務等級。

AllowedTools

允許使用的工具設定。

欄位
mode enum (ToolChoiceType)

工具選擇模式。

tools[] string

允許使用的工具名稱。

JSON 表示法
{
  "mode": enum (ToolChoiceType),
  "tools": [
    string
  ]
}

備註

模型生成內容的引用資訊。

欄位
startIndex integer

歸因於這個來源的回覆片段開頭。

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

endIndex integer

歸因區隔的結束時間 (不包含在內)。

type Union type
註解類型。type 只能是下列其中一項:
urlCitation object (UrlCitation)

網址引用註解。

fileCitation object (FileCitation)

檔案引用註解。

placeCitation object (PlaceCitation)

地點引用註解。

JSON 表示法
{
  "startIndex": integer,
  "endIndex": integer,

  // type
  "urlCitation": {
    object (UrlCitation)
  },
  "fileCitation": {
    object (FileCitation)
  },
  "placeCitation": {
    object (PlaceCitation)
  }
  // Union type
}

UrlCitation

網址引用註解。

欄位
url string

網址。

title string

網址的標題。

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

FileCitation

檔案引用註解。

欄位
documentUri string

檔案的 URI。

fileName string

檔案名稱。

source string

歸因於部分文字的來源。

customMetadata object (Struct)

使用者提供的中繼資料,與擷取的脈絡相關。

pageNumber integer

引用文件的頁碼 (如適用)。

mediaId string

圖片引用時的媒體 ID (如適用)。

JSON 表示法
{
  "documentUri": string,
  "fileName": string,
  "source": string,
  "customMetadata": {
    object (Struct)
  },
  "pageNumber": integer,
  "mediaId": string
}

PlaceCitation

地點引用註解。

欄位
placeId string

地點 ID,格式為 places/{placeId}

name string

地點名稱。

url string

地點的 URI 參照。

reviewSnippets[] object (ReviewSnippet)

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

JSON 表示法
{
  "placeId": string,
  "name": string,
  "url": string,
  "reviewSnippets": [
    {
      object (ReviewSnippet)
    }
  ]
}

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。

AudioResponseFormat

音訊輸出格式設定。

欄位
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
}

CodeExecution

這個類型沒有任何欄位。

模型可用來執行程式碼的工具。

CodeExecutionCallStep

執行程式碼呼叫步驟。

欄位
arguments object (CodeExecutionCallStepArguments)

必填。要傳遞至執行程式碼的引數。

JSON 表示法
{
  "arguments": {
    object (CodeExecutionCallStepArguments)
  }
}

CodeExecutionCallStepArguments

要傳遞至執行程式碼的引數。

欄位
language enum (Language)

code 的程式設計語言。

code string

要執行的程式碼。

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

CodeExecutionResultStep

執行程式碼結果步驟。

欄位
result string

必填。執行程式碼的輸出內容。

isError boolean

執行程式碼作業是否發生錯誤。

JSON 表示法
{
  "result": string,
  "isError": boolean
}

ComputerUse

模型可用來與電腦互動的工具。

欄位
environment enum (Environment)

正在運作的環境。

excludedPredefinedFunctions[] string

從模型呼叫中排除的預先定義函式清單。

enablePromptInjectionDetection boolean

是否要在電腦使用要求中啟用提示詞注入偵測檢查。

disabledSafetyPolicies[] enum (SafetyPolicy)

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

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

內容

回覆內容。

欄位
type Union type
type 只能是下列其中一項:
text object (TextContent)
image object (ImageContent)
audio object (AudioContent)
document object (DocumentContent)
video object (VideoContent)
thought
(deprecated)
object (ThoughtContent)
toolCall
(deprecated)
object (ToolCallContent)
toolResult
(deprecated)
object (ToolResultContent)
JSON 表示法
{

  // type
  "text": {
    object (TextContent)
  },
  "image": {
    object (ImageContent)
  },
  "audio": {
    object (AudioContent)
  },
  "document": {
    object (DocumentContent)
  },
  "video": {
    object (VideoContent)
  },
  "thought": {
    object (ThoughtContent)
  },
  "toolCall": {
    object (ToolCallContent)
  },
  "toolResult": {
    object (ToolResultContent)
  }
  // Union type
}

TextContent

文字內容區塊。

欄位
text string

必填。文字內容。

annotations[] object (Annotation)

模型生成內容的引用資訊。

JSON 表示法
{
  "text": string,
  "annotations": [
    {
      object (Annotation)
    }
  ]
}

ImageContent

圖片內容區塊。

欄位
mimeType enum (MimeType)

圖片的 MIME 類型。

resolution enum (MediaResolution)

媒體的解析度。

data_or_uri Union type
圖片內容。data_or_uri 只能是下列其中一項:
data string (bytes format)

圖片內容。

Base64 編碼字串。

uri string

圖片的 URI。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "resolution": enum (MediaResolution),

  // data_or_uri
  "data": string,
  "uri": string
  // Union type
}

AudioContent

音訊內容區塊。

欄位
mimeType enum (MimeType)

音訊的 MIME 類型。

channels integer

音訊聲道數。

sampleRate integer

音訊的取樣率。

data_or_uri Union type
音訊內容。data_or_uri 只能是下列其中一項:
data string (bytes format)

音訊內容。

Base64 編碼字串。

uri string

音訊的 URI。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "channels": integer,
  "sampleRate": integer,

  // data_or_uri
  "data": string,
  "uri": string
  // Union type
}

DocumentContent

文件內容區塊。

欄位
mimeType enum (MimeType)

文件的 MIME 類型。

data_or_uri Union type
文件內容。data_or_uri 只能是下列其中一項:
data string (bytes format)

文件內容。

Base64 編碼字串。

uri string

文件的 URI。

JSON 表示法
{
  "mimeType": enum (MimeType),

  // data_or_uri
  "data": string,
  "uri": string
  // Union type
}

VideoContentId:

影片內容區塊。

欄位
mimeType enum (MimeType)

影片的 MIME 類型。

resolution enum (MediaResolution)

媒體的解析度。

data_or_uri Union type
影片內容。data_or_uri 只能是下列其中一項:
data string (bytes format)

影片內容。

Base64 編碼字串。

uri string

影片的 URI。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "resolution": enum (MediaResolution),

  // data_or_uri
  "data": string,
  "uri": string
  // Union type
}

ThoughtContent

想法內容區塊。

欄位
signature string (bytes format)

與要納入生成作業的後端來源相符的簽章。

Base64 編碼字串。

summary[] object (ThoughtSummaryContent)

想法摘要。

JSON 表示法
{
  "signature": string,
  "summary": [
    {
      object (ThoughtSummaryContent)
    }
  ]
}

ThoughtSummaryContent

欄位
type Union type
type 只能是下列其中一項:
text object (TextContent)
image object (ImageContent)
JSON 表示法
{

  // type
  "text": {
    object (TextContent)
  },
  "image": {
    object (ImageContent)
  }
  // Union type
}

ToolCallContent

工具呼叫內容。

欄位
id string

必填。這個特定工具呼叫的專屬 ID。

signature string (bytes format)

用於後端驗證的簽章雜湊。

Base64 編碼字串。

type Union type
type 只能是下列其中一項:
functionCall object (FunctionCallContent)
codeExecutionCall object (CodeExecutionCallContent)
urlContextCall object (UrlContextCallContent)
mcpServerToolCall object (McpServerToolCallContent)
googleSearchCall object (GoogleSearchCallContent)
fileSearchCall object (FileSearchCallContent)
googleMapsCall object (GoogleMapsCallContent)
JSON 表示法
{
  "id": string,
  "signature": string,

  // type
  "functionCall": {
    object (FunctionCallContent)
  },
  "codeExecutionCall": {
    object (CodeExecutionCallContent)
  },
  "urlContextCall": {
    object (UrlContextCallContent)
  },
  "mcpServerToolCall": {
    object (McpServerToolCallContent)
  },
  "googleSearchCall": {
    object (GoogleSearchCallContent)
  },
  "fileSearchCall": {
    object (FileSearchCallContent)
  },
  "googleMapsCall": {
    object (GoogleMapsCallContent)
  }
  // Union type
}

FunctionCallContent

函式工具呼叫內容區塊。

欄位
name string

必填。要呼叫的工具名稱。

arguments object (Struct)

必填。要傳遞至函式的引數。

JSON 表示法
{
  "name": string,
  "arguments": {
    object (Struct)
  }
}

CodeExecutionCallContent

執行程式碼的內容。

欄位
arguments object (CodeExecutionCallArguments)

必填。要傳遞至執行程式碼的引數。

JSON 表示法
{
  "arguments": {
    object (CodeExecutionCallArguments)
  }
}

CodeExecutionCallArguments

要傳遞至執行程式碼的引數。

欄位
language enum (Language)

code 的程式設計語言。

code string

要執行的程式碼。

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

UrlContextCallContent

網址背景資訊內容。

欄位
arguments object (UrlContextCallArguments)

必填。要傳遞至網址環境的引數。

JSON 表示法
{
  "arguments": {
    object (UrlContextCallArguments)
  }
}

UrlContextCallArguments

要傳遞至網址環境的引數。

欄位
urls[] string

要擷取的網址。

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

McpServerToolCallContent

MCPServer 工具呼叫內容。

欄位
name string

必填。所呼叫工具的名稱。

serverName string

必填。所用 MCP 伺服器的名稱。

arguments object (Struct)

必填。函式引數的 JSON 物件。

JSON 表示法
{
  "name": string,
  "serverName": string,
  "arguments": {
    object (Struct)
  }
}

GoogleSearchCallContent

Google 搜尋內容。

欄位
arguments object (GoogleSearchCallArguments)

必填。要傳遞給 Google 搜尋的引數。

searchType enum (SearchType)

已啟用的搜尋基準建立功能類型。

JSON 表示法
{
  "arguments": {
    object (GoogleSearchCallArguments)
  },
  "searchType": enum (SearchType)
}

GoogleSearchCallArguments

要傳遞給 Google 搜尋的引數。

欄位
queries[] string

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

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

FileSearchCallContent

這個類型沒有任何欄位。

檔案搜尋內容。

GoogleMapsCallContent

Google 地圖內容。

欄位
arguments object (GoogleMapsCallArguments)

要傳遞至 Google 地圖工具的引數。

JSON 表示法
{
  "arguments": {
    object (GoogleMapsCallArguments)
  }
}

GoogleMapsCallArguments

要傳遞至 Google 地圖工具的引數。

欄位
queries[] string

要執行的查詢。

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

ToolResultContent

工具結果內容。

欄位
callId string

必填。與函式呼叫區塊中的 ID 相符的 ID。

signature string (bytes format)

用於後端驗證的簽章雜湊。

Base64 編碼字串。

type Union type
type 只能是下列其中一項:
functionResult object (FunctionResultContent)
codeExecutionResult object (CodeExecutionResultContent)
urlContextResult object (UrlContextResultContent)
googleSearchResult object (GoogleSearchResultContent)
mcpServerToolResult object (McpServerToolResultContent)
fileSearchResult object (FileSearchResultContent)
googleMapsResult object (GoogleMapsResultContent)
JSON 表示法
{
  "callId": string,
  "signature": string,

  // type
  "functionResult": {
    object (FunctionResultContent)
  },
  "codeExecutionResult": {
    object (CodeExecutionResultContent)
  },
  "urlContextResult": {
    object (UrlContextResultContent)
  },
  "googleSearchResult": {
    object (GoogleSearchResultContent)
  },
  "mcpServerToolResult": {
    object (McpServerToolResultContent)
  },
  "fileSearchResult": {
    object (FileSearchResultContent)
  },
  "googleMapsResult": {
    object (GoogleMapsResultContent)
  }
  // Union type
}

FunctionResultContent

函式工具結果內容區塊。

欄位
name string

所呼叫工具的名稱。

isError boolean

工具呼叫是否導致錯誤。

result Union type
工具呼叫的結果。result 只能是下列其中一項:
structResult object (Struct)
contentList object (FunctionResultSubcontentList)
stringResult string
JSON 表示法
{
  "name": string,
  "isError": boolean,

  // result
  "structResult": {
    object (Struct)
  },
  "contentList": {
    object (FunctionResultSubcontentList)
  },
  "stringResult": string
  // Union type
}

FunctionResultSubcontentList

欄位
contents[] object (FunctionResultSubcontent)
JSON 表示法
{
  "contents": [
    {
      object (FunctionResultSubcontent)
    }
  ]
}

FunctionResultSubcontent

欄位
type Union type
type 只能是下列其中一項:
text object (TextContent)
image object (ImageContent)
JSON 表示法
{

  // type
  "text": {
    object (TextContent)
  },
  "image": {
    object (ImageContent)
  }
  // Union type
}

CodeExecutionResultContent

執行程式碼結果內容。

欄位
result string

必填。執行程式碼的輸出內容。

isError boolean

執行程式碼作業是否發生錯誤。

JSON 表示法
{
  "result": string,
  "isError": boolean
}

UrlContextResultContent

網址背景資訊結果內容。

欄位
result[] object (UrlContextResult)

必填。網址環境的結果。

isError boolean

網址脈絡是否發生錯誤。

JSON 表示法
{
  "result": [
    {
      object (UrlContextResult)
    }
  ],
  "isError": boolean
}

UrlContextResult

網址環境的結果。

欄位
url string

擷取的網址。

status enum (Status)

網址擷取狀態。

JSON 表示法
{
  "url": string,
  "status": enum (Status)
}

GoogleSearchResultContent

Google 搜尋結果內容。

欄位
result[] object (GoogleSearchResult)

必填。Google 搜尋結果。

isError boolean

Google 搜尋是否發生錯誤。

JSON 表示法
{
  "result": [
    {
      object (GoogleSearchResult)
    }
  ],
  "isError": boolean
}

GoogleSearchResult

Google 搜尋結果。

欄位
searchSuggestions string

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

JSON 表示法
{
  "searchSuggestions": string
}

McpServerToolResultContent

MCPServer 工具結果內容。

欄位
name string

針對這項特定工具呼叫所呼叫的工具名稱。

serverName string

所用 MCP 伺服器的名稱。

result Union type
MCP 伺服器呼叫的輸出內容。可以是簡單文字或多媒體內容。result 只能是下列其中一項:
structResult object (Struct)
contentList object (FunctionResultSubcontentList)
stringResult string
JSON 表示法
{
  "name": string,
  "serverName": string,

  // result
  "structResult": {
    object (Struct)
  },
  "contentList": {
    object (FunctionResultSubcontentList)
  },
  "stringResult": string
  // Union type
}

FileSearchResultContent

檔案搜尋結果內容。

欄位
result[] object (FileSearchResult)

(選用步驟) 檔案搜尋結果。

JSON 表示法
{
  "result": [
    {
      object (FileSearchResult)
    }
  ]
}

FileSearchResult

這個類型沒有任何欄位。

檔案搜尋結果。

GoogleMapsResultContent

Google 地圖結果內容。

欄位
result[] object (GoogleMapsResult)

必填。Google 地圖的搜尋結果。

JSON 表示法
{
  "result": [
    {
      object (GoogleMapsResult)
    }
  ]
}

GoogleMapsResult

Google 地圖的搜尋結果。

欄位
places[] object (Places)

找到的地點。

widgetContextToken string

Google 地圖小工具情境權杖的資源名稱。

JSON 表示法
{
  "places": [
    {
      object (Places)
    }
  ],
  "widgetContextToken": string
}

地點

欄位
placeId string

地點 ID,格式為 places/{placeId}

name string

地點名稱。

url string

地點的 URI 參照。

reviewSnippets[] object (ReviewSnippet)

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

JSON 表示法
{
  "placeId": string,
  "name": string,
  "url": string,
  "reviewSnippets": [
    {
      object (ReviewSnippet)
    }
  ]
}

ContentList

內容清單。

欄位
contents[] object (Content)

清單內容。

JSON 表示法
{
  "contents": [
    {
      object (Content)
    }
  ]
}

CreateInteractionRequest

用於建立互動的設定參數。

欄位
stream boolean

僅供輸入。互動是否會串流。

store boolean

僅供輸入。是否要儲存回覆和要求,以供日後擷取。

interaction object (Interaction)

要建立的互動。

background boolean

僅供輸入。是否要在背景執行模型互動。

JSON 表示法
{
  "stream": boolean,
  "store": boolean,
  "interaction": {
    object (Interaction)
  },
  "background": boolean
}

互動

InteractionService.CreateInteraction 的回應。

欄位
id string

必填。僅供輸出。互動完成的專屬 ID。

status enum (Status)

必填。僅供輸出。互動狀態。

created string

必填。僅供輸出。回覆的建立時間,採用 ISO 8601 格式 (YYYY-MM-DDThh:mm:ssZ)。

updated string

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

role
(deprecated)
string

僅供輸出。互動的角色。

outputs[]
(deprecated)
object (Content)

僅供輸出。模型回覆。

systemInstruction string

互動的系統指令。

tools[] object (Tool)

模型在互動期間可能會呼叫的工具宣告清單。

usage object (Usage)

僅供輸出。互動要求的權杖用量統計資料。

responseModalities[]
(deprecated)
enum (ResponseModality)

要求的回覆模態 (TEXT、IMAGE、AUDIO)。

responseMimeType
(deprecated)
string

回應的 MIME 類型。如果已設定 responseFormat,就必須提供這個屬性。

previousInteractionId string

先前的互動 ID (如有)。

environmentId string

僅供輸出。互動的環境 ID。只有在要求中設定環境設定時,才會填入這個欄位。

serviceTier enum (ServiceTier)

互動的服務層級。

webhookConfig object (WebhookConfig)

(選用步驟) Webhook 設定,用於在互動完成時接收通知。

steps[] object (Step)

必填。僅供輸出。構成互動的步驟。

input Union type
互動的輸入內容。input 只能是下列其中一項:
contentList
(deprecated)
object (ContentList)

互動的輸入內容。

stringContent string

互動的字串輸入內容,系統會將其視為單一文字輸入內容處理。

turnList
(deprecated)
object (TurnList)

互動的輪流對話。

stepList object (StepList)

僅供輸入。互動步驟。

content object (Content)

互動內容。

response_format_config Union type
response_format_config 只能是下列其中一項:
responseFormat
(deprecated)
object (Value)

強制生成的 JSON 物件回覆必須符合這個欄位中指定的 JSON 結構定義。

responseFormatList object (ResponseFormatList)
responseFormatSingleton object (ResponseFormat)
request_type Union type
互動的要求類型。request_type 只能是下列其中一項:
modelInteraction object (ModelInteraction)

使用模型生成完成內容的互動。

agentInteraction object (AgentInteraction)

使用代理生成完成內容的互動。

environment Union type
互動的環境設定。environment 只能是下列其中一項:
envId string

互動的環境 ID。預設環境可為「remote」。

remoteEnvironment object (EnvironmentConfig)
localEnvironment object (LocalEnvironmentConfig)

代理程式的環境位於用戶端連線:內建環境作業 (檔案系統作業和執行指令) 會產生給用戶端執行,而不是在伺服器管理的沙箱中執行。與 remoteEnvironment 互斥。(與任何用戶端宣告的函式工具無關,無論這個欄位為何,函式工具一律會在用戶端執行)。

JSON 表示法
{
  "id": string,
  "status": enum (Status),
  "created": string,
  "updated": string,
  "role": string,
  "outputs": [
    {
      object (Content)
    }
  ],
  "systemInstruction": string,
  "tools": [
    {
      object (Tool)
    }
  ],
  "usage": {
    object (Usage)
  },
  "responseModalities": [
    enum (ResponseModality)
  ],
  "responseMimeType": string,
  "previousInteractionId": string,
  "environmentId": string,
  "serviceTier": enum (ServiceTier),
  "webhookConfig": {
    object (WebhookConfig)
  },
  "steps": [
    {
      object (Step)
    }
  ],

  // input
  "contentList": {
    object (ContentList)
  },
  "stringContent": string,
  "turnList": {
    object (TurnList)
  },
  "stepList": {
    object (StepList)
  },
  "content": {
    object (Content)
  }
  // Union type

  // response_format_config
  "responseFormat": {
    object (Value)
  },
  "responseFormatList": {
    object (ResponseFormatList)
  },
  "responseFormatSingleton": {
    object (ResponseFormat)
  }
  // Union type

  // request_type
  "modelInteraction": {
    object (ModelInteraction)
  },
  "agentInteraction": {
    object (AgentInteraction)
  }
  // Union type

  // environment
  "envId": string,
  "remoteEnvironment": {
    object (EnvironmentConfig)
  },
  "localEnvironment": {
    object (LocalEnvironmentConfig)
  }
  // Union type
}

TurnList

回合清單。

欄位
turns[] object (Turn)
JSON 表示法
{
  "turns": [
    {
      object (Turn)
    }
  ]
}

啟用或停用

Fields
role string

這個回合的發起者。必須是輸入的使用者或模型輸出內容的模型。

content Union type
content 只能是下列其中一項:
contentList object (ContentList)

輪流對話的內容。Content 物件陣列。

contentString string

輪流對話的內容。單一字串。

JSON 表示法
{
  "role": string,

  // content
  "contentList": {
    object (ContentList)
  },
  "contentString": string
  // Union type
}

StepList

步驟清單。

欄位
steps[] object (Step)

清單中的步驟。

JSON 表示法
{
  "steps": [
    {
      object (Step)
    }
  ]
}

步驟

互動中的步驟。

欄位
type Union type
type 只能是下列其中一項:
thought object (ThoughtStep)
toolCall object (ToolCallStep)
toolResult object (ToolResultStep)
userInput object (UserInputStep)

請勿使用 -- 這些僅適用於第三方 JSON

modelOutput object (ModelOutputStep)
text
(deprecated)
object (LegacyTextContent)
image
(deprecated)
object (LegacyImageContent)
audio
(deprecated)
object (LegacyAudioContent)
document
(deprecated)
object (LegacyDocumentContent)
video
(deprecated)
object (LegacyVideoContent)
JSON 表示法
{

  // type
  "thought": {
    object (ThoughtStep)
  },
  "toolCall": {
    object (ToolCallStep)
  },
  "toolResult": {
    object (ToolResultStep)
  },
  "userInput": {
    object (UserInputStep)
  },
  "modelOutput": {
    object (ModelOutputStep)
  },
  "text": {
    object (LegacyTextContent)
  },
  "image": {
    object (LegacyImageContent)
  },
  "audio": {
    object (LegacyAudioContent)
  },
  "document": {
    object (LegacyDocumentContent)
  },
  "video": {
    object (LegacyVideoContent)
  }
  // Union type
}

ThoughtStep

思考步驟。

欄位
signature string (bytes format)

用於後端驗證的簽章雜湊。

Base64 編碼字串。

summary[] object (Content)

想法摘要。

JSON 表示法
{
  "signature": string,
  "summary": [
    {
      object (Content)
    }
  ]
}

ToolCallStep

工具呼叫步驟。

欄位
id string

必填。這個特定工具呼叫的專屬 ID。

signature string (bytes format)

用於後端驗證的簽章雜湊。

Base64 編碼字串。

type Union type
type 只能是下列其中一項:
functionCall object (FunctionCallStep)
codeExecutionCall object (CodeExecutionCallStep)
urlContextCall object (UrlContextCallStep)
mcpServerToolCall object (McpServerToolCallStep)
googleSearchCall object (GoogleSearchCallStep)
fileSearchCall object (FileSearchCallStep)
googleMapsCall object (GoogleMapsCallStep)
retrievalCall object (RetrievalCallStep)
JSON 表示法
{
  "id": string,
  "signature": string,

  // type
  "functionCall": {
    object (FunctionCallStep)
  },
  "codeExecutionCall": {
    object (CodeExecutionCallStep)
  },
  "urlContextCall": {
    object (UrlContextCallStep)
  },
  "mcpServerToolCall": {
    object (McpServerToolCallStep)
  },
  "googleSearchCall": {
    object (GoogleSearchCallStep)
  },
  "fileSearchCall": {
    object (FileSearchCallStep)
  },
  "googleMapsCall": {
    object (GoogleMapsCallStep)
  },
  "retrievalCall": {
    object (RetrievalCallStep)
  }
  // Union type
}

FunctionCallStep

函式工具呼叫步驟。

欄位
name string

必填。要呼叫的工具名稱。

arguments object (Struct)

必填。要傳遞至函式的引數。

JSON 表示法
{
  "name": string,
  "arguments": {
    object (Struct)
  }
}

UrlContextCallStep

網址背景資訊呼叫步驟。

欄位
arguments object (UrlContextCallStepArguments)

必填。要傳遞至網址環境的引數。

JSON 表示法
{
  "arguments": {
    object (UrlContextCallStepArguments)
  }
}

UrlContextCallStepArguments

要傳遞至網址環境的引數。

欄位
urls[] string

要擷取的網址。

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

McpServerToolCallStep

MCPServer 工具呼叫步驟。

欄位
name string

必填。所呼叫工具的名稱。

serverName string

必填。所用 MCP 伺服器的名稱。

arguments object (Struct)

必填。函式引數的 JSON 物件。

JSON 表示法
{
  "name": string,
  "serverName": string,
  "arguments": {
    object (Struct)
  }
}

GoogleSearchCallStep

Google 搜尋通話步驟。

欄位
arguments object (GoogleSearchCallStepArguments)

必填。要傳遞給 Google 搜尋的引數。

searchType enum (SearchType)

已啟用的搜尋基準建立功能類型。

JSON 表示法
{
  "arguments": {
    object (GoogleSearchCallStepArguments)
  },
  "searchType": enum (SearchType)
}

GoogleSearchCallStepArguments

要傳遞給 Google 搜尋的引數。

欄位
queries[] string

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

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

FileSearchCallStep

這個類型沒有任何欄位。

「檔案搜尋」通話步驟。

GoogleMapsCallStep

Google 地圖通話步驟。

欄位
arguments object (GoogleMapsCallStepArguments)

要傳遞至 Google 地圖工具的引數。

JSON 表示法
{
  "arguments": {
    object (GoogleMapsCallStepArguments)
  }
}

GoogleMapsCallStepArguments

要傳遞至 Google 地圖工具的引數。

欄位
queries[] string

要執行的查詢。

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

ToolResultStep

工具結果步驟。

欄位
callId string

必填。與函式呼叫區塊中的 ID 相符的 ID。

signature string (bytes format)

用於後端驗證的簽章雜湊。

Base64 編碼字串。

type Union type
type 只能是下列其中一項:
functionResult object (FunctionResultStep)
codeExecutionResult object (CodeExecutionResultStep)
urlContextResult object (UrlContextResultStep)
googleSearchResult object (GoogleSearchResultStep)
mcpServerToolResult object (McpServerToolResultStep)
fileSearchResult object (FileSearchResultStep)
googleMapsResult object (GoogleMapsResultStep)
retrievalResult object (RetrievalResultStep)
JSON 表示法
{
  "callId": string,
  "signature": string,

  // type
  "functionResult": {
    object (FunctionResultStep)
  },
  "codeExecutionResult": {
    object (CodeExecutionResultStep)
  },
  "urlContextResult": {
    object (UrlContextResultStep)
  },
  "googleSearchResult": {
    object (GoogleSearchResultStep)
  },
  "mcpServerToolResult": {
    object (McpServerToolResultStep)
  },
  "fileSearchResult": {
    object (FileSearchResultStep)
  },
  "googleMapsResult": {
    object (GoogleMapsResultStep)
  },
  "retrievalResult": {
    object (RetrievalResultStep)
  }
  // Union type
}

FunctionResultStep

函式工具呼叫的結果。

欄位
name string

所呼叫工具的名稱。

isError boolean

工具呼叫是否導致錯誤。

result object (Value)

必填。工具呼叫的結果。

JSON 表示法
{
  "name": string,
  "isError": boolean,
  "result": {
    object (Value)
  }
}

UrlContextResultStep

網址背景資訊結果步驟。

欄位
result[] object (UrlContextResultItem)

必填。網址環境的結果。

isError boolean

網址脈絡是否發生錯誤。

JSON 表示法
{
  "result": [
    {
      object (UrlContextResultItem)
    }
  ],
  "isError": boolean
}

UrlContextResultItem

網址環境的結果。

欄位
url string

擷取的網址。

status enum (Status)

網址擷取狀態。

JSON 表示法
{
  "url": string,
  "status": enum (Status)
}

GoogleSearchResultStep

Google 搜尋結果步驟。

欄位
result[] object (GoogleSearchResultItem)

必填。Google 搜尋結果。

isError boolean

Google 搜尋是否發生錯誤。

JSON 表示法
{
  "result": [
    {
      object (GoogleSearchResultItem)
    }
  ],
  "isError": boolean
}

GoogleSearchResultItem

Google 搜尋結果。

欄位
searchSuggestions string

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

JSON 表示法
{
  "searchSuggestions": string
}

McpServerToolResultStep

MCPServer 工具結果步驟。

欄位
name string

針對這項特定工具呼叫所呼叫的工具名稱。

serverName string

所用 MCP 伺服器的名稱。

result object (Value)

必填。MCP 伺服器呼叫的輸出內容。可以是簡單文字或多媒體內容。

JSON 表示法
{
  "name": string,
  "serverName": string,
  "result": {
    object (Value)
  }
}

FileSearchResultStep

這個類型沒有任何欄位。

檔案搜尋結果步驟。

GoogleMapsResultStep

Google 地圖結果步驟。

欄位
result[] object (GoogleMapsResultItem)
JSON 表示法
{
  "result": [
    {
      object (GoogleMapsResultItem)
    }
  ]
}

GoogleMapsResultItem

Google 地圖的搜尋結果。

欄位
places[] object (GoogleMapsResultPlaces)
widgetContextToken string
JSON 表示法
{
  "places": [
    {
      object (GoogleMapsResultPlaces)
    }
  ],
  "widgetContextToken": string
}

GoogleMapsResultPlaces

欄位
placeId string
name string
url string
reviewSnippets[] object (ReviewSnippet)
JSON 表示法
{
  "placeId": string,
  "name": string,
  "url": string,
  "reviewSnippets": [
    {
      object (ReviewSnippet)
    }
  ]
}

UserInputStep

使用者提供的輸入內容。

欄位
content Union type
content 只能是下列其中一項:
contentList object (ContentList)

步驟內容。Content 物件陣列。

contentString string

步驟內容。單一字串。

JSON 表示法
{

  // content
  "contentList": {
    object (ContentList)
  },
  "contentString": string
  // Union type
}

ModelOutputStep

模型生成的輸出內容。

欄位
content[] object (Content)
JSON 表示法
{
  "content": [
    {
      object (Content)
    }
  ]
}

ResponseFormatList

欄位
responseFormats[] object (ResponseFormat)
JSON 表示法
{
  "responseFormats": [
    {
      object (ResponseFormat)
    }
  ]
}

ResponseFormat

欄位
type Union type
type 只能是下列其中一項:
audio object (AudioResponseFormat)
text object (TextResponseFormat)
image object (ImageResponseFormat)
video object (VideoResponseFormat)
structValue object (Struct)

GAOS 中已啟用多重鑑別值

JSON 表示法
{

  // type
  "audio": {
    object (AudioResponseFormat)
  },
  "text": {
    object (TextResponseFormat)
  },
  "image": {
    object (ImageResponseFormat)
  },
  "video": {
    object (VideoResponseFormat)
  },
  "structValue": {
    object (Struct)
  }
  // Union type
}

TextResponseFormat

文字輸出格式的設定。

欄位
mimeType enum (MimeType)

文字輸出的 MIME 類型。

schema object (Struct)

輸出內容應符合的 JSON 結構定義。僅適用於 mimeType 為 application/json 的情況。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "schema": {
    object (Struct)
  }
}

ImageResponseFormat

圖片輸出格式的設定。

欄位
mimeType enum (MimeType)

圖片輸出的 MIME 類型。

delivery enum (Delivery)

圖片輸出內容的傳送模式。

aspectRatio enum (AspectRatio)

輸出圖片的顯示比例。

imageSize enum (ImageSize)

輸出圖片的大小。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "delivery": enum (Delivery),
  "aspectRatio": enum (AspectRatio),
  "imageSize": enum (ImageSize)
}

VideoResponseFormat

影片輸出格式的設定。

欄位
delivery enum (Delivery)

影片輸出內容的傳送模式。

aspectRatio enum (AspectRatio)

影片輸出的顯示比例。

duration string (Duration format)

影片輸出時間長度。

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

JSON 表示法
{
  "delivery": enum (Delivery),
  "aspectRatio": enum (AspectRatio),
  "duration": string
}

ModelInteraction

使用模型生成完成內容的互動。

欄位
model string

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

generationConfig object (GenerationConfig)

僅供輸入。模型互動的設定參數。

JSON 表示法
{
  "model": string,
  "generationConfig": {
    object (GenerationConfig)
  }
}

GenerationConfig

模型互動的設定參數。

欄位
temperature number

控制輸出內容的隨機程度。

topP number

取樣時要考慮的符記累積分數上限。

seed integer

用於解碼的種子,確保可以重現結果。

stopSequences[] string

停止輸出互動的字元序列清單。

thinkingLevel enum (ThinkingLevel)

模型應生成的思考權杖數量。

thinkingSummaries enum (ThinkingSummaries)

是否要在回覆中加入想法摘要。

maxOutputTokens integer

回覆中可包含的詞元數量上限。

speechConfig[] object (SpeechConfig)

語音互動設定。

imageConfig
(deprecated)
object (ImageConfig)

圖片互動設定。

videoConfig object (VideoConfig)

影片生成設定。

tool_choice Union type
工具選擇設定。tool_choice 只能是下列其中一項:
toolChoiceMode enum (ToolChoiceType)

工具選擇模式。

toolChoiceConfig object (ToolChoiceConfig)

工具選擇的設定。

JSON 表示法
{
  "temperature": number,
  "topP": number,
  "seed": integer,
  "stopSequences": [
    string
  ],
  "thinkingLevel": enum (ThinkingLevel),
  "thinkingSummaries": enum (ThinkingSummaries),
  "maxOutputTokens": integer,
  "speechConfig": [
    {
      object (SpeechConfig)
    }
  ],
  "imageConfig": {
    object (ImageConfig)
  },
  "videoConfig": {
    object (VideoConfig)
  },

  // tool_choice
  "toolChoiceMode": enum (ToolChoiceType),
  "toolChoiceConfig": {
    object (ToolChoiceConfig)
  }
  // Union type
}

ToolChoiceConfig

包含允許使用的工具的工具選擇設定。

欄位
allowedTools object (AllowedTools)

允許使用的工具。

JSON 表示法
{
  "allowedTools": {
    object (AllowedTools)
  }
}

SpeechConfig

語音互動的設定。

欄位
voice string

說話者的聲音。

language string

語音的語言。

speaker string

說話者姓名,應與提示中提供的說話者姓名相符。

JSON 表示法
{
  "voice": string,
  "language": string,
  "speaker": string
}

ImageConfig

圖片互動的設定。

欄位
aspectRatio string

要生成的圖片顯示比例。支援的顯示比例:1:1、2:3、3:2、3:4、4:3、9:16、16:9、21:9。

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

imageSize string

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

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

VideoConfig

影片生成設定選項。

欄位
task enum (Task)

生成影片的選用工作模式。如未指定,模型會根據提供的文字提示詞和輸入媒體,自動判斷合適的模式。

JSON 表示法
{
  "task": enum (Task)
}

EnvironmentConfig

自訂環境的設定。

欄位
sources[] object (Source)
environmentId string

(選用步驟) 互動的環境 ID。如果指定,要求會更新現有環境,而不是建立新環境。

network Union type
環境的網路設定。network 只能是下列其中一項:
networkAllowlist object (EnvironmentNetworkEgressAllowlist)

僅允許特定網域。

networkMode enum (NetworkMode)

網路輸出模式。

JSON 表示法
{
  "sources": [
    {
      object (Source)
    }
  ],
  "environmentId": string,

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

EnvironmentNetworkEgressAllowlist

環境的網路輸出設定。

欄位
allowlist[] object (EgressRule)

允許的網域及其設定清單。

JSON 表示法
{
  "allowlist": [
    {
      object (EgressRule)
    }
  ]
}

EgressRule

網路輸出規則,可控管環境允許連線的外部網域。每條規則都會識別目標網域,並視需要指定一組 HTTP 標頭,插入每個相符的外送要求。

欄位
domain string

這項規則要比對的網域模式。使用確切主機名稱 (例如 github.com)、萬用字元前置字串 (例如 *.googleapis.com),或 * 來比對所有網域。

transform map (key: string, value: string)

要插入符合這項規則之要求的標頭。鍵:標頭名稱 (例如「Authorization」)。值:標頭值 (例如「Bearer your-token」)。

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

JSON 表示法
{
  "domain": string,
  "transform": {
    string: string,
    ...
  }
}

來源

要掛接至環境的來源。

欄位
type enum (Type)
source string

環境來源。如果是 GCS,則為 GCS 路徑。如果是 GitHub,這是指 GitHub 路徑。

target string

來源在環境中的顯示位置。

content string

如果 typeINLINE,則為內嵌內容。

encoding string

內嵌內容的選用編碼 (例如 base64)。

JSON 表示法
{
  "type": enum (Type),
  "source": string,
  "target": string,
  "content": string,
  "encoding": string
}

LocalEnvironmentConfig

這個類型沒有任何欄位。

環境設定,位於用戶端連線,而非伺服器管理的沙箱。

設定後 (透過 Interaction.local_environment),系統會將代理程式的檔案系統和殼層視為位於用戶端:代理程式的內建環境作業 (例如讀取/列出/編輯檔案和執行指令) 會在伺服器上暫停,並產生回用戶端執行的結果,結果會在後續回合中傳回。這與伺服器管理的 EnvironmentConfig (remoteEnvironment) 互斥,因為環境不是在用戶端,就是在伺服器沙箱中,絕不會同時存在。

這項設定只會控管代理程式的內建環境。無論這個欄位為何,用戶端宣告的函式工具一律會在用戶端執行。

工具

模型可使用的工具。

欄位
type Union type
要使用的工具。type 只能是下列其中一項:
function object (Function)

模型可使用的函式。

codeExecution object (CodeExecution)

模型可用來執行程式碼的工具。

urlContext object (UrlContext)

模型可用來擷取網址背景資訊的工具。

computerUse object (ComputerUse)

支援模型直接與電腦互動的工具。

mcpServer object (McpServer)

MCPServer 是模型可呼叫的伺服器,可執行動作。

googleMaps object (GoogleMaps)

模型可用來搜尋 Google 地圖的工具。

retrieval object (Retrieval)

模型可用來擷取檔案的工具。

JSON 表示法
{

  // type
  "function": {
    object (Function)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "urlContext": {
    object (UrlContext)
  },
  "computerUse": {
    object (ComputerUse)
  },
  "mcpServer": {
    object (McpServer)
  },
  "googleSearch": {
    object (GoogleSearch)
  },
  "fileSearch": {
    object (FileSearch)
  },
  "googleMaps": {
    object (GoogleMaps)
  },
  "retrieval": {
    object (Retrieval)
  }
  // Union type
}

函式

模型可使用的工具。

欄位
name string

函式名稱。

description string

函式說明。

parameters object (Value)

函式參數的 JSON 結構定義。

JSON 表示法
{
  "name": string,
  "description": string,
  "parameters": {
    object (Value)
  }
}

UrlContext

這個類型沒有任何欄位。

模型可用來擷取網址背景資訊的工具。

McpServer

MCPServer 是模型可呼叫的伺服器,可執行動作。

欄位
name string

MCPServer 的名稱。

url string

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

headers map (key: string, value: string)

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

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

allowedTools[] object (AllowedTools)

允許使用的工具。

JSON 表示法
{
  "name": string,
  "url": string,
  "headers": {
    string: string,
    ...
  },
  "allowedTools": [
    {
      object (AllowedTools)
    }
  ]
}

GoogleSearch

模型可用來搜尋 Google 的工具。

欄位
searchTypes[] enum (SearchType)

要啟用的搜尋基準建立功能類型。

JSON 表示法
{
  "searchTypes": [
    enum (SearchType)
  ]
}

FileSearch

模型可用來搜尋檔案的工具。

欄位
fileSearchStoreNames[] string

要搜尋的檔案搜尋商店名稱。

topK integer

要擷取的語意擷取區塊數量。

metadataFilter string

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

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

GoogleMaps

模型可用來呼叫 Google 地圖的工具。

欄位
enableWidget boolean

是否要在回應的工具呼叫結果中傳回小工具內容符記。

latitude number

使用者所在位置的緯度。

longitude number

使用者所在位置的經度。

JSON 表示法
{
  "enableWidget": boolean,
  "latitude": number,
  "longitude": number
}

用量

互動要求的權杖用量統計資料。

欄位
totalInputTokens integer

提示 (脈絡) 中的權杖數量。

inputTokensByModality[] object (ModalityTokens)

依模式細分的輸入權杖用量。

totalCachedTokens integer

提示快取部分 (快取內容) 中的權杖數量。

cachedTokensByModality[] object (ModalityTokens)

依模式細分快取權杖使用情形。

totalOutputTokens integer

所有生成回覆的詞元總數。

outputTokensByModality[] object (ModalityTokens)

依模式細分的輸出權杖用量。

totalToolUseTokens integer

工具使用提示中的權杖數量。

toolUseTokensByModality[] object (ModalityTokens)

依模式細分工具使用權杖用量。

totalThoughtTokens integer

思考模型思考時的詞元數量。

totalTokens integer

互動要求的詞元數總計 (提示 + 回覆 + 其他內部詞元)。

groundingToolCount[] object (GroundingToolCount)

基礎工具計數。

JSON 表示法
{
  "totalInputTokens": integer,
  "inputTokensByModality": [
    {
      object (ModalityTokens)
    }
  ],
  "totalCachedTokens": integer,
  "cachedTokensByModality": [
    {
      object (ModalityTokens)
    }
  ],
  "totalOutputTokens": integer,
  "outputTokensByModality": [
    {
      object (ModalityTokens)
    }
  ],
  "totalToolUseTokens": integer,
  "toolUseTokensByModality": [
    {
      object (ModalityTokens)
    }
  ],
  "totalThoughtTokens": integer,
  "totalTokens": integer,
  "groundingToolCount": [
    {
      object (GroundingToolCount)
    }
  ]
}

ModalityTokens

單一回覆模式的詞元數。

欄位
modality enum (ResponseModality)

與詞元數相關聯的模態。

tokens integer

模態的權杖數量。

JSON 表示法
{
  "modality": enum (ResponseModality),
  "tokens": integer
}

GroundingToolCount

接地工具的數量。

欄位
type enum (Type)

與計數相關聯的基礎工具類型。

count integer

接地工具的數量。

JSON 表示法
{
  "type": enum (Type),
  "count": integer
}

WebhookConfig

訊息:為要求設定 Webhook 事件。

欄位
uris[] string

(選用步驟) 如果設定了這些 Webhook URI,系統就會使用這些 URI 傳送 Webhook 事件,而非使用已註冊的 Webhook。

userMetadata object (Struct format)

(選用步驟) 系統在每次將事件傳送至 Webhook 時,都會傳回使用者中繼資料。

JSON 表示法
{
  "uris": [
    string
  ],
  "userMetadata": {
    object
  }
}

SafetySetting

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

[SafetySetting][google.cloud.aiplatform.master.SafetySetting] 包含危害 [類別][google.cloud.aiplatform.master.SafetySetting.category] 和該類別的 [門檻][google.cloud.aiplatform.master.SafetySetting.threshold]。

欄位
type enum (HarmCategory)

必填。要封鎖的危害類別類型。

threshold enum (HarmBlockThreshold)

必填。封鎖內容的門檻。如果有害機率超過這個門檻,系統就會封鎖內容。

method enum (HarmBlockMethod)

(選用步驟) 封鎖內容的方法。如未指定,預設行為是使用機率分數。

JSON 表示法
{
  "type": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold),
  "method": enum (HarmBlockMethod)
}

外送

音訊輸出的傳送模式。

列舉
DELIVERY_UNSPECIFIED 預設值。這個值不會使用。
INLINE 音訊資料會內嵌在回應中傳回。
URI 音訊資料會以 URI 形式傳回。

環境

代表作業環境,例如網路瀏覽器。

列舉
ENVIRONMENT_UNSPECIFIED 預設為瀏覽器。
BROWSER 在網路瀏覽器中運作。
MOBILE 在行動環境中運作。
DESKTOP 在電腦環境中運作。

HarmBlockMethod

封鎖內容的方法。

列舉
HARM_BLOCK_METHOD_UNSPECIFIED 未指定危害封鎖方法。
SEVERITY 損害封鎖方法會同時使用機率和嚴重程度分數。
PROBABILITY 危害封鎖方法會使用機率分數。

HarmBlockThreshold

根據有害機率封鎖內容的門檻。

列舉
HARM_BLOCK_THRESHOLD_UNSPECIFIED 未指定有害內容封鎖門檻。
BLOCK_LOW_AND_ABOVE 封鎖有害機率低等以上的內容。
BLOCK_MEDIUM_AND_ABOVE 封鎖有害機率中等以上的內容。
BLOCK_ONLY_HIGH 封鎖有害機率高的內容。
BLOCK_NONE 無論有害機率為何,一律不封鎖任何內容。
OFF 完全關閉安全篩選器。

ImageSize

支援的圖片輸出大小。

列舉
IMAGE_SIZE_UNSPECIFIED 預設值。這個值不會使用。
IMAGE_SIZE_FIVE_TWELVE 圖片大小為 512 像素。
IMAGE_SIZE_ONE_K 1K 圖片大小。
IMAGE_SIZE_TWO_K 2K 圖片大小。
IMAGE_SIZE_FOUR_K 4K 圖片大小。

語言

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

列舉
LANGUAGE_UNSPECIFIED 未指定語言。請勿使用此值。
PYTHON Python >= 3.10,並提供 numpy 和 simpy。

MediaResolution

輸入媒體 (圖片/影片) 的解析度。

列舉
MEDIA_RESOLUTION_UNSPECIFIED 預設值。這個值不會使用。
LOW 低解析度。
MEDIUM 中等解析度。
HIGH 高解析度。
ULTRA_HIGH 超高解析度。

MimeType

列舉
TYPE_UNSPECIFIED
TYPE_WAV WAV 音訊格式
TYPE_MP3 MP3 音訊格式
TYPE_AIFF AIFF 音訊格式
TYPE_AAC AAC 音訊格式
TYPE_OGG OGG 音訊格式
TYPE_FLAC FLAC 音訊格式
TYPE_MPEG MPEG 音訊格式
TYPE_M4A M4A 音訊格式
TYPE_L16 L16 音訊格式
TYPE_OPUS OPUS 音訊格式
TYPE_ALAW ALAW 音訊格式
TYPE_MULAW MULAW 音訊格式

模式

定義尋找工作階段的深度和徹底程度。

列舉
MODE_UNSPECIFIED 預設值。這個值不會使用。
MODE_SCAN 只使用初始分類器進行快速掃描。
MODE_VERIFY 執行分類,然後進行詳細調查。

NetworkMode

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

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

ResponseModality

回覆的模式。

列舉
RESPONSE_MODALITY_UNSPECIFIED 預設值。這個值不會使用。
TEXT 表示模型應傳回文字。
IMAGE 表示模型應傳回圖片。
AUDIO 表示模型應傳回音訊。
VIDEO 表示模型應傳回影片。
DOCUMENT 表示模型應傳回文件。

ReviewSnippet

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

欄位
title string

評論標題。

url string

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

reviewId string

評論摘錄的 ID。

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

SafetyPolicy

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

結構定義

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

欄位
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 空值型別。

搜尋類型

要啟用的搜尋基準建立功能類型。

列舉
SEARCH_TYPE_UNSPECIFIED 未指定搜尋類型。請勿使用此值。

結構

Struct 代表結構化資料值,由對應至動態型別值的欄位組成。

欄位
fields[] object (Field)

動態型別欄位。我們提供清單而非地圖,是因為 LLM 對排序很敏感,且我們希望使用者能完全掌控。

JSON 表示法
{
  "fields": [
    {
      object (Field)
    }
  ]
}

欄位

代表結構體中的單一欄位。

欄位
name string
value object (Value)
JSON 表示法
{
  "name": string,
  "value": {
    object (Value)
  }
}

工作

支援的影片生成工作。

列舉
TASK_UNSPECIFIED 未指定工作。系統會根據輸入提示和媒體推斷工作。
TEXT_TO_VIDEO 僅根據文字提示詞生成影片。
IMAGE_TO_VIDEO 根據一或兩張來源圖片生成影片。第一張圖片定義起始影格,第二張圖片 (選用) 則定義結束影格。
REFERENCE_TO_VIDEO 使用參考媒體 (例如圖片、音訊或影片) 生成影片。
EDIT 修改現有的輸入影片。

ThinkingLevel

模型應生成的思考權杖數量。

列舉
THINKING_LEVEL_UNSPECIFIED 預設值。這個值不會使用。
THINKING_LEVEL_MINIMAL 幾乎不用思考。
THINKING_LEVEL_LOW 思考程度較低。
THINKING_LEVEL_MEDIUM 中等思考程度。
THINKING_LEVEL_HIGH 高思考程度。

ThinkingSummaries

是否要在回覆中加入想法摘要。

列舉
THINKING_SUMMARIES_UNSPECIFIED 預設值。這個值不會使用。
THINKING_SUMMARIES_AUTO 自動生成思考摘要。
THINKING_SUMMARIES_NONE 沒有思考摘要。

工具

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

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

下一個 ID:16

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

欄位
name string

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

description string

必填。簡短說明功能。

behavior enum (Behavior)

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

parameters object (Schema)

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

parametersJsonSchema value (Value format)

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

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

這個欄位與 parameters 互斥。

response object (Schema)

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

responseJsonSchema value (Value format)

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

這個欄位與 response 互斥。

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

行為

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

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

GoogleSearchRetrieval

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

欄位
dynamicRetrievalConfig object (DynamicRetrievalConfig)

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

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

DynamicRetrievalConfig

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

欄位
mode enum (Mode)

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

dynamicThreshold number

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

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

模式

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

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

CodeExecution

這個類型沒有任何欄位。

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

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

GoogleSearch

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

欄位
timeRangeFilter object (Interval)

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

searchTypes object (SearchTypes)

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

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

時間間隔

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

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

欄位
startTime string (Timestamp format)

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

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

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

endTime string (Timestamp format)

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

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

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

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

SearchTypes

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

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

WebSearch

這個類型沒有任何欄位。

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

ImageSearch

這個類型沒有任何欄位。

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

ComputerUse

電腦使用工具類型。

欄位
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 將檔案匯入語意擷取語料庫。

欄位
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

欄位
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

欄位
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 地圖工具,可為使用者的查詢提供地理空間脈絡。

欄位
enableWidget boolean

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

JSON 表示法
{
  "enableWidget": boolean
}

ToolChoiceType

工具選擇類型。

列舉
TOOL_CHOICE_TYPE_UNSPECIFIED 預設值。這個值不會使用。
AUTO 自動選擇工具。
ANY 選擇任何工具。
NONE 未選擇工具。
VALIDATED 已驗證的工具選擇。

Value 代表動態型別的值,可以是空值、數字、字串、布林值、遞迴結構體值或值清單。價值生產者應設定其中一個變體。如果沒有任何變體,表示發生錯誤。

欄位
kind Union type
值的類型。kind 只能是下列其中一項:
nullValue null

代表空值。

numberValue number

表示雙精度浮點數值。

stringValue string

代表字串值。

boolValue boolean

表示布林值。

structValue object (Struct)

代表結構化值。

listValue object (ListValue)

代表重複的 Value

contentValue object (Content)

代表多媒體內容 (文字、圖片等)。

JSON 表示法
{

  // kind
  "nullValue": null,
  "numberValue": number,
  "stringValue": string,
  "boolValue": boolean,
  "structValue": {
    object (Struct)
  },
  "listValue": {
    object (ListValue)
  },
  "contentValue": {
    object (Content)
  }
  // Union type
}

ListValue

ListValue 是值重複欄位的包裝函式。

欄位
values[] object (Value)

動態型別值的重複欄位。

JSON 表示法
{
  "values": [
    {
      object (Value)
    }
  ]
}

VisualizationMode

圖表模式的列舉。我們最終會支援互動模式,讓使用者選擇是否要在回覆中加入 HTML 視覺化內容。

列舉
UNSPECIFIED 預設的視覺化模式。預設為 AUTO。
OFF 請勿加入視覺化內容。
AUTO 自動加入視覺化內容。

REST 資源:auth_tokens

資源:AuthToken

要求建立臨時驗證權杖。

欄位
name string

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

expireTime string (Timestamp format)

(選用步驟) 僅供輸入。不可變動。這個時間是選填項目,如果使用產生的符記,超過這個時間後,系統就會拒絕 BidiGenerateContent 工作階段中的訊息。(Gemini 可能會在時間到期後預先關閉工作階段)。

如未設定,預設值為 30 分鐘後。設定的值必須在 20 小時內。

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

newSessionExpireTime string (Timestamp format)

(選用步驟) 僅供輸入。不可變動。使用這項要求產生的權杖建立新的 Live API 工作階段時,系統會拒絕要求,這個欄位會指出拒絕要求的時間。

如未設定,預設值為 60 秒。設定的值必須在 20 小時內。

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

fieldMask string (FieldMask format)

(選用步驟) 僅供輸入。不可變動。如果 fieldMask 為空,且沒有 bidiGenerateContentSetup,系統會從 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 訊息,再傳送任何其他訊息。

欄位
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)

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

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

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

欄位
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)

(選用步驟) 翻譯設定。

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

模態

支援的回覆模式。

列舉
MODALITY_UNSPECIFIED 預設值。
TEXT 表示模型應傳回文字。
IMAGE 表示模型應傳回圖片。
AUDIO 表示模型應傳回音訊。

SpeechConfig

語音生成和轉錄的設定。

欄位
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

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

欄位
voiceName string

要使用的預設語音名稱。

JSON 表示法
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

多音箱設定的設定。

欄位
speakerVoiceConfigs[] object (SpeakerVoiceConfig)

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

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

SpeakerVoiceConfig

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

欄位
speaker string

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

voiceConfig object (VoiceConfig)

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

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

ThinkingConfig

思考功能的設定。

欄位
includeThoughts boolean

表示是否要在回覆中加入想法。如果為 true,則只會在有想法時傳回。

thinkingBudget integer

模型應生成的想法權杖數量。

thinkingLevel enum (ThinkingLevel)

(選用步驟) 控制模型產生回覆前,內部推論過程的最大深度。預設值取決於模型。詳情請參閱思考層級指南。建議用於 Gemini 3 以上版本。如果搭配舊版模型使用,會導致錯誤。

JSON 表示法
{
  "includeThoughts": boolean,
  "thinkingBudget": integer,
  "thinkingLevel": enum (ThinkingLevel)
}

ThinkingLevel

允許使用者使用列舉,而非整數預算,指定思考量。

列舉
THINKING_LEVEL_UNSPECIFIED 預設值。
MINIMAL 幾乎不用思考。
LOW 思考程度較低。
MEDIUM 中等思考程度。
HIGH 高思考程度。

ImageConfig

圖片生成功能的設定。

欄位
aspectRatio string

(選用步驟) 要生成的圖片顯示比例。支援的顯示比例:1: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

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

欄位
text object (TextResponseFormat)

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

audio object (AudioResponseFormat)

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

image object (ImageResponseFormat)

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

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

TextResponseFormat

文字輸出格式的設定。

欄位
mimeType enum (MimeType)

(選用步驟) 文字輸出的 MIME 類型。

schema value (Value format)

(選用步驟) 輸出內容應符合的 JSON 結構定義。僅適用於 mimeType 為 APPLICATION_JSON 的情況。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "schema": value
}

MimeType

支援文字輸出的 MIME 類型。

列舉
MIME_TYPE_UNSPECIFIED 預設值。這個值不會使用。
APPLICATION_JSON JSON 輸出格式。
TEXT_PLAIN 純文字輸出格式。

AudioResponseFormat

音訊輸出格式設定。

欄位
mimeType enum (MimeType)

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

delivery enum (Delivery)

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

sampleRate integer

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

bitRate integer

(選用步驟) 位元率,以每秒位元數 (bps) 為單位。僅適用於壓縮格式 (MP3、Opus)。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "delivery": enum (Delivery),
  "sampleRate": integer,
  "bitRate": integer
}

MimeType

支援音訊輸出的 MIME 類型。

列舉
MIME_TYPE_UNSPECIFIED 預設值。這個值不會使用。
AUDIO_MP3 MP3 音訊格式。
AUDIO_OGG_OPUS OGG Opus 音訊格式。
AUDIO_L16 原始 PCM (L16) 音訊格式。
AUDIO_WAV WAV 音訊格式。
AUDIO_ALAW A-law 音訊格式。
AUDIO_MULAW Mu-law 音訊格式。

外送

音訊輸出的傳送模式。

列舉
DELIVERY_UNSPECIFIED 預設值。這個值不會使用。
INLINE 音訊資料會內嵌在回應中傳回。
URI 音訊資料會以 URI 形式傳回。

ImageResponseFormat

圖片輸出格式的設定。

欄位
mimeType enum (MimeType)

(選用步驟) 圖片輸出的 MIME 類型。

delivery enum (Delivery)

(選用步驟) 圖片輸出內容的傳送模式。

aspectRatio enum (AspectRatio)

(選用步驟) 輸出圖片的顯示比例。

imageSize enum (ImageSize)

(選用步驟) 輸出圖片的大小。

JSON 表示法
{
  "mimeType": enum (MimeType),
  "delivery": enum (Delivery),
  "aspectRatio": enum (AspectRatio),
  "imageSize": enum (ImageSize)
}

MimeType

支援的圖片輸出 MIME 類型。

列舉
MIME_TYPE_UNSPECIFIED 預設值。這個值不會使用。
IMAGE_JPEG JPEG 圖片格式。

外送

圖片輸出的傳送模式。

列舉
DELIVERY_UNSPECIFIED 預設值。這個值不會使用。
INLINE 圖片資料會內嵌在回應中傳回。
URI 圖片資料會以 URI 形式傳回。

AspectRatio

支援的圖像輸出顯示比例。

列舉
ASPECT_RATIO_UNSPECIFIED 預設值。這個值不會使用。
ASPECT_RATIO_ONE_BY_ONE 顯示比例為 1:1。
ASPECT_RATIO_TWO_BY_THREE 顯示比例為 2:3。
ASPECT_RATIO_THREE_BY_TWO 顯示比例為 3:2。
ASPECT_RATIO_THREE_BY_FOUR 顯示比例 3:4。
ASPECT_RATIO_FOUR_BY_THREE 顯示比例為 4:3。
ASPECT_RATIO_FOUR_BY_FIVE 顯示比例 4:5。
ASPECT_RATIO_FIVE_BY_FOUR 顯示比例為 5:4。
ASPECT_RATIO_NINE_BY_SIXTEEN 顯示比例為 9:16。
ASPECT_RATIO_SIXTEEN_BY_NINE 顯示比例為 16:9。
ASPECT_RATIO_TWENTY_ONE_BY_NINE 顯示比例 21:9。
ASPECT_RATIO_ONE_BY_EIGHT 顯示比例為 1:8。
ASPECT_RATIO_EIGHT_BY_ONE 顯示比例 8:1。
ASPECT_RATIO_ONE_BY_FOUR 顯示比例 1:4。
ASPECT_RATIO_FOUR_BY_ONE 長寬比為 4:1。

ImageSize

支援的圖片輸出大小。

列舉
IMAGE_SIZE_UNSPECIFIED 預設值。這個值不會使用。
IMAGE_SIZE_FIVE_TWELVE 圖片大小為 512 像素。
IMAGE_SIZE_ONE_K 1K 圖片大小。
IMAGE_SIZE_TWO_K 2K 圖片大小。
IMAGE_SIZE_FOUR_K 4K 圖片大小。

TranslationConfig

翻譯功能設定。

欄位
targetLanguageCode string

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

echoTargetLanguage boolean

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

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

RealtimeInputConfig

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

欄位
automaticActivityDetection object (AutomaticActivityDetection)

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

activityHandling enum (ActivityHandling)

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

turnCoverage enum (TurnCoverage)

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

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

AutomaticActivityDetection

設定自動偵測活動。

欄位
disabled boolean

(選用步驟) 啟用此覆寫值時,系統會將偵測到的語音和文字輸入視為活動。預設為啟用。如果停用,用戶端必須傳送活動信號。

startOfSpeechSensitivity enum (StartSensitivity)

(選用步驟) 決定語音偵測的機率。

prefixPaddingMs integer

(選用步驟) 系統偵測到語音後,必須經過這段時間才會開始辨識語音。這個值越低,語音開始偵測的靈敏度就越高,可辨識的語音長度就越短。但這也會增加誤判的機率。

endOfSpeechSensitivity enum (EndSensitivity)

(選用步驟) 決定偵測到的語音結束的可能性。

silenceDurationMs integer

(選用步驟) 系統偵測到非語音 (例如靜音) 的必要時間長度,之後才會提交語音結尾。這個值越大,語音間隔時間就越長,不會中斷使用者的活動,但會增加模型的延遲時間。

JSON 表示法
{
  "disabled": boolean,
  "startOfSpeechSensitivity": enum (StartSensitivity),
  "prefixPaddingMs": integer,
  "endOfSpeechSensitivity": enum (EndSensitivity),
  "silenceDurationMs": integer
}

StartSensitivity

決定如何偵測語音的開始。

列舉
START_SENSITIVITY_UNSPECIFIED 預設值為 START_SENSITIVITY_HIGH。
START_SENSITIVITY_HIGH 自動偵測功能會更頻繁地偵測語音開始時間。
START_SENSITIVITY_LOW 自動偵測功能會減少偵測到語音的次數。

EndSensitivity

決定如何偵測語音結束。

列舉
END_SENSITIVITY_UNSPECIFIED 預設值為 END_SENSITIVITY_HIGH。
END_SENSITIVITY_HIGH 自動偵測功能會更頻繁地結束語音。
END_SENSITIVITY_LOW 自動偵測功能較少會中斷語音。

ActivityHandling

處理使用者活動的不同方式。

列舉
ACTIVITY_HANDLING_UNSPECIFIED 如未指定,預設行為為 START_OF_ACTIVITY_INTERRUPTS
START_OF_ACTIVITY_INTERRUPTS 如果設為 true,活動開始時會中斷模型的回答 (也稱為「插話」)。模型目前的回覆會在您中斷時停止。此為預設行為。
NO_INTERRUPTION 模型不會中斷回覆。

TurnCoverage

選項:使用者回合中包含哪些輸入內容。

列舉
TURN_COVERAGE_UNSPECIFIED 如未指定,系統會根據模型選取預設行為。舉例來說,Gemini 2.5 的預設值為 TURN_INCLUDES_ONLY_ACTIVITY,Gemini 3.1 以上版本則為 TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO
TURN_INCLUDES_ONLY_ACTIVITY 包括上次輪流發言後的活動,但不包括閒置狀態 (例如音訊串流中的無聲狀態)。
TURN_INCLUDES_ALL_INPUT 包括自上次輪流發言以來的所有即時輸入內容,包括無活動狀態 (例如音訊串流中的靜音)。
TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO 包括音訊活動和上回合以來的所有影片。如果啟用自動活動偵測功能,音訊活動是指語音,不包括無聲狀態。

SessionResumptionConfig

工作階段恢復設定。

這則訊息已納入工作階段設定,顯示為 BidiGenerateContentSetup.session_resumption。如果已設定,伺服器會傳送 SessionResumptionUpdate 訊息。

欄位
handle string

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

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

JSON 表示法
{
  "handle": string
}

ContextWindowCompressionConfig

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

欄位
compression_mechanism Union type
使用的脈絡窗口壓縮機制。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 一律會放在結果開頭。

欄位
targetTokens string (int64 format)

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

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

JSON 表示法
{
  "targetTokens": string
}

AudioTranscriptionConfig

音訊轉錄設定。

欄位
adaptationPhrases[]
(deprecated)
string

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

customVocabulary[] string

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

language_config Union type
音訊轉錄的語言設定。如果是 ASR 模型,則為必要欄位,如未設定,系統會傳回錯誤。language_config 只能是下列其中一項:
languageAuto object (LanguageAuto)

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

languageHints object (LanguageHints)

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

JSON 表示法
{
  "adaptationPhrases": [
    string
  ],
  "customVocabulary": [
    string
  ],

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

LanguageAuto

這個類型沒有任何欄位。

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

LanguageHints

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

欄位
languageCodes[] string

必填。BCP-47 語言代碼。

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

HistoryConfig

記錄設定。

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

欄位
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 執行個體。