Generating content

Gemini API รองรับการสร้างเนื้อหาด้วยรูปภาพ เสียง โค้ด เครื่องมือ และอื่นๆ อ่านรายละเอียดเกี่ยวกับฟีเจอร์แต่ละรายการเหล่านี้ต่อและดูโค้ดตัวอย่างที่มุ่งเน้นงาน หรืออ่านคู่มือที่ครอบคลุม

เมธอด: models.generateContent

สร้างคำตอบของโมเดลจากอินพุต GenerateContentRequest ดูข้อมูลการใช้งานโดยละเอียดได้ในคู่มือการสร้างข้อความ ความสามารถในการป้อนข้อมูลจะแตกต่างกันไปในแต่ละรุ่น ซึ่งรวมถึงรุ่นที่ปรับแต่งแล้ว ดูรายละเอียดได้ในคู่มือโมเดลและคู่มือการปรับแต่ง

โพสต์ https://generativelanguage.googleapis.com/v1beta/{model=models/*}:generateContent
model string

ต้องระบุ ชื่อของ Model ที่จะใช้สําหรับสร้างการทํางานให้เสร็จสมบูรณ์

รูปแบบ: models/{model} โดยจะมีรูปแบบเป็น models/{model}

เนื้อความของคำขอมีข้อมูลซึ่งมีโครงสร้างดังต่อไปนี้

ฟิลด์
contents[] object (Content)

ต้องระบุ เนื้อหาของการสนทนาปัจจุบันกับโมเดล

สําหรับการค้นหาแบบเทิร์นเดียว อินสแตนซ์นี้จะเป็นแบบเดี่ยว สําหรับคําค้นหาแบบหลายรอบ เช่น chat ช่องนี้จะซ้ำกันซึ่งมีประวัติการสนทนาและคําขอล่าสุด

tools[] object (Tool)

ไม่บังคับ รายการ Tools ที่ Model อาจใช้เพื่อสร้างคำตอบถัดไป

Tool คือโค้ดที่ช่วยให้ระบบโต้ตอบกับระบบภายนอกเพื่อดำเนินการหรือชุดการดำเนินการที่อยู่นอกเหนือความรู้และขอบเขตของ Model Tool ที่รองรับคือ Function และ codeExecution ดูข้อมูลเพิ่มเติมได้จากคู่มือการเรียกใช้ฟังก์ชันและการเรียกใช้โค้ด

toolConfig object (ToolConfig)

ไม่บังคับ การกําหนดค่าเครื่องมือสําหรับ Tool ที่ระบุในคําขอ ดูตัวอย่างการใช้งานได้ในคู่มือการเรียกใช้ฟังก์ชัน

safetySettings[] object (SafetySetting)

ไม่บังคับ รายการอินสแตนซ์ SafetySetting ที่ไม่ซ้ำกันสำหรับการบล็อกเนื้อหาที่ไม่ปลอดภัย

ซึ่งจะมีผลกับ GenerateContentRequest.contents และ GenerateContentResponse.candidates การตั้งค่า SafetyCategory แต่ละประเภทไม่ควรมีมากกว่า 1 รายการ API จะบล็อกเนื้อหาและการตอบกลับที่ไม่เป็นไปตามเกณฑ์ที่กำหนดโดยการตั้งค่าเหล่านี้ รายการนี้จะลบล้างการตั้งค่าเริ่มต้นสำหรับ SafetyCategory แต่ละรายการที่ระบุไว้ใน safetySettings หากไม่มี SafetySetting สำหรับ SafetyCategory ที่ระบุในรายการ API จะใช้การตั้งค่าความปลอดภัยเริ่มต้นสำหรับหมวดหมู่นั้น ระบบรองรับหมวดหมู่อันตราย HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY ดูข้อมูลโดยละเอียดเกี่ยวกับการตั้งค่าความปลอดภัยที่ใช้ได้ได้จากคู่มือ นอกจากนี้ โปรดดูคำแนะนำด้านความปลอดภัยเพื่อดูวิธีนำข้อควรพิจารณาด้านความปลอดภัยมาใช้ในการประยุกต์ใช้ AI

systemInstruction object (Content)

ไม่บังคับ คำสั่งของระบบที่นักพัฒนาแอปตั้งค่าไว้ ปัจจุบันมีเฉพาะข้อความเท่านั้น

generationConfig object (GenerationConfig)

ไม่บังคับ ตัวเลือกการกําหนดค่าสําหรับการสร้างโมเดลและเอาต์พุต

cachedContent string

ไม่บังคับ ชื่อของเนื้อหาที่แคชไว้เพื่อใช้เป็นบริบทในการแสดงการคาดคะเน รูปแบบ: cachedContents/{cachedContent}

from google import genai

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Write a story about a magic backpack."
)
print(response.text)
// 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-2.0-flash",
  contents: "Write a story about a magic backpack.",
});
console.log(response.text);
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.", "user"),
}
response, err := client.Models.GenerateContent(ctx, "gemini-2.0-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
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)
let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

let prompt = "Write a story about a magic backpack."
let response = try await generativeModel.generateContent(prompt)
if let text = response.text {
  print(text)
}
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Write a story about a magic backpack.';

final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Content content =
    new Content.Builder().addText("Write a story about a magic backpack.").build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);
from google import genai
import PIL.Image

client = genai.Client()
organ = PIL.Image.open(media / "organ.jpg")
response = client.models.generate_content(
    model="gemini-2.0-flash", contents=["Tell me about this instrument", organ]
)
print(response.text)
// 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-2.0-flash",
  contents: [
    createUserContent([
      "Tell me about this instrument", 
      createPartFromUri(organ.uri, organ.mimeType)
    ]),
  ],
});
console.log(response.text);
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, "user"),
}

response, err := client.Models.GenerateContent(ctx, "gemini-2.0-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
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val image: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image)
val inputContent = content {
  image(image)
  text("What's in this picture?")
}

val response = generativeModel.generateContent(inputContent)
print(response.text)
let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

guard let image = UIImage(systemName: "cloud.sun") else { fatalError() }

let prompt = "What's in this picture?"

let response = try await generativeModel.generateContent(image, prompt)
if let text = response.text {
  print(text)
}
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);

Future<DataPart> fileToPart(String mimeType, String path) async {
  return DataPart(mimeType, await File(path).readAsBytes());
}

final prompt = 'Describe how this product might be manufactured.';
final image = await fileToPart('image/jpeg', 'resources/jetpack.jpg');

final response = await model.generateContent([
  Content.multi([TextPart(prompt), image])
]);
print(response.text);
// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap image = BitmapFactory.decodeResource(context.getResources(), R.drawable.image);

Content content =
    new Content.Builder()
        .addText("What's different between these pictures?")
        .addImage(image)
        .build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);
PythonNode.jsเปลือกหอย
from google import genai

client = genai.Client()
sample_audio = client.files.upload(file=media / "sample.mp3")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
print(response.text)
// 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-2.0-flash",
  contents: [
    createUserContent([
      "Give me a summary of this audio file.",
      createPartFromUri(audio.uri, audio.mimeType),
    ]),
  ],
});
console.log(response.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: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
PythonNode.jsGoเปลือกหอย
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-2.0-flash", contents=[myfile, "Describe this video clip"]
)
print(f"{response.text=}")
// 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-2.0-flash",
  contents: [
    createUserContent([
      "Describe this video clip",
      createPartFromUri(video.uri, video.mimeType),
    ]),
  ],
});
console.log(response.text);
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, "user"),
}

response, err := client.Models.GenerateContent(ctx, "gemini-2.0-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
Pythonเปลือกหอย
from google import genai

client = genai.Client()
sample_pdf = client.files.upload(file=media / "test.pdf")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["Give me a summary of this document:", sample_pdf],
)
print(f"{response.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: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
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-2.0-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)
// 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-2.0-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);
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", "user"),
	genai.NewContentFromText("Great to meet you. What would you like to know?", "model"),
}

chat, err := client.Chats.Create(ctx, "gemini-2.0-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"
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val chat =
    generativeModel.startChat(
        history =
            listOf(
                content(role = "user") { text("Hello, I have 2 dogs in my house.") },
                content(role = "model") {
                  text("Great to meet you. What would you like to know?")
                }))

val response = chat.sendMessage("How many paws are in my house?")
print(response.text)
let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

// Optionally specify existing chat history
let history = [
  ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."),
  ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"),
]

// Initialize the chat with optional chat history
let chat = generativeModel.startChat(history: history)

// To generate text output, call sendMessage and pass in the message
let response = try await chat.sendMessage("How many paws are in my house?")
if let text = response.text {
  print(text)
}
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final chat = model.startChat(history: [
  Content.text('hello'),
  Content.model([TextPart('Great to meet you. What would you like to know?')])
]);
var response =
    await chat.sendMessage(Content.text('I have 2 dogs in my house.'));
print(response.text);
response =
    await chat.sendMessage(Content.text('How many paws are in my house?'));
print(response.text);
// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

// (optional) Create previous chat history for context
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();

Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();

List<Content> history = Arrays.asList(userContent, modelContent);

// Initialize the chat
ChatFutures chat = model.startChat(history);

// Create a new user message
Content.Builder userMessageBuilder = new Content.Builder();
userMessageBuilder.setRole("user");
userMessageBuilder.addText("How many paws are in my house?");
Content userMessage = userMessageBuilder.build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(userMessage);

Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);
PythonNode.js
from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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);
Python
# With Gemini 2 we're launching a new SDK. See the following doc for details.
# https://ai.google.dev/gemini-api/docs/migrate
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-2.0-flash",
    contents="List a few popular cookie recipes.",
    config=types.GenerateContentConfig(
        response_mime_type="application/json", response_schema=list[Recipe]
    ),
)
print(result)
// 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-2.0-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);
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-2.0-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
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-pro",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey,
        generationConfig = generationConfig {
            responseMimeType = "application/json"
            responseSchema = Schema(
                name = "recipes",
                description = "List of recipes",
                type = FunctionType.ARRAY,
                items = Schema(
                    name = "recipe",
                    description = "A recipe",
                    type = FunctionType.OBJECT,
                    properties = mapOf(
                        "recipeName" to Schema(
                            name = "recipeName",
                            description = "Name of the recipe",
                            type = FunctionType.STRING,
                            nullable = false
                        ),
                    ),
                    required = listOf("recipeName")
                ),
            )
        })

val prompt = "List a few popular cookie recipes."
val response = generativeModel.generateContent(prompt)
print(response.text)
let jsonSchema = Schema(
  type: .array,
  description: "List of recipes",
  items: Schema(
    type: .object,
    properties: [
      "recipeName": Schema(type: .string, description: "Name of the recipe", nullable: false),
    ],
    requiredProperties: ["recipeName"]
  )
)

let generativeModel = GenerativeModel(
  // Specify a model that supports controlled generation like Gemini 1.5 Pro
  name: "gemini-1.5-pro",
  // Access your API key from your on-demand resource .plist file (see "Set up your API key"
  // above)
  apiKey: APIKey.default,
  generationConfig: GenerationConfig(
    responseMIMEType: "application/json",
    responseSchema: jsonSchema
  )
)

let prompt = "List a few popular cookie recipes."
let response = try await generativeModel.generateContent(prompt)
if let text = response.text {
  print(text)
}
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final schema = Schema.array(
    description: 'List of recipes',
    items: Schema.object(properties: {
      'recipeName':
          Schema.string(description: 'Name of the recipe.', nullable: false)
    }, requiredProperties: [
      'recipeName'
    ]));

final model = GenerativeModel(
    model: 'gemini-1.5-pro',
    apiKey: apiKey,
    generationConfig: GenerationConfig(
        responseMimeType: 'application/json', responseSchema: schema));

final prompt = 'List a few popular cookie recipes.';
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
Schema<List<String>> schema =
    new Schema(
        /* name */ "recipes",
        /* description */ "List of recipes",
        /* format */ null,
        /* nullable */ false,
        /* list */ null,
        /* properties */ null,
        /* required */ null,
        /* items */ new Schema(
            /* name */ "recipe",
            /* description */ "A recipe",
            /* format */ null,
            /* nullable */ false,
            /* list */ null,
            /* properties */ Map.of(
                "recipeName",
                new Schema(
                    /* name */ "recipeName",
                    /* description */ "Name of the recipe",
                    /* format */ null,
                    /* nullable */ false,
                    /* list */ null,
                    /* properties */ null,
                    /* required */ null,
                    /* items */ null,
                    /* type */ FunctionType.STRING)),
            /* required */ null,
            /* items */ null,
            /* type */ FunctionType.OBJECT),
        /* type */ FunctionType.ARRAY);

GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "application/json";
configBuilder.responseSchema = schema;

GenerationConfig generationConfig = configBuilder.build();

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-pro",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey,
        /* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Content content = new Content.Builder().addText("List a few popular cookie recipes.").build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);
PythonKotlinJava
from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-pro-exp-02-05",
    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)

val model = GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    modelName = "gemini-1.5-pro",
    // Access your API key as a Build Configuration variable (see "Set up your API key" above)
    apiKey = BuildConfig.apiKey,
    tools = listOf(Tool.CODE_EXECUTION)
)

val response = model.generateContent("What is the sum of the first 50 prime numbers?")

// Each `part` either contains `text`, `executable_code` or an `execution_result`
println(response.candidates[0].content.parts.joinToString("\n"))

// Alternatively, you can use the `text` accessor which joins the parts into a markdown compatible
// text representation
println(response.text)
// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
        new GenerativeModel(
                /* modelName */ "gemini-1.5-pro",
                // Access your API key as a Build Configuration variable (see "Set up your API key"
                // above)
                /* apiKey */ BuildConfig.apiKey,
                /* generationConfig */ null,
                /* safetySettings */ null,
                /* requestOptions */ new RequestOptions(),
                /* tools */ Collections.singletonList(Tool.CODE_EXECUTION));
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Content inputContent =
        new Content.Builder().addText("What is the sum of the first 50 prime numbers?").build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(inputContent);
Futures.addCallback(
        response,
        new FutureCallback<GenerateContentResponse>() {
            @Override
            public void onSuccess(GenerateContentResponse result) {
                // Each `part` either contains `text`, `executable_code` or an
                // `execution_result`
                Candidate candidate = result.getCandidates().get(0);
                for (Part part : candidate.getContent().getParts()) {
                    System.out.println(part);
                }

                // Alternatively, you can use the `text` accessor which joins the parts into a
                // markdown compatible text representation
                String resultText = result.getText();
                System.out.println(resultText);
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        },
        executor);
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-2.0-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)
  // 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-2.0-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-2.0-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'
fun multiply(a: Double, b: Double) = a * b

val multiplyDefinition = defineFunction(
    name = "multiply",
    description = "returns the product of the provided numbers.",
    parameters = listOf(
    Schema.double("a", "First number"),
    Schema.double("b", "Second number")
    )
)

val usableFunctions = listOf(multiplyDefinition)

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey,
        // List the functions definitions you want to make available to the model
        tools = listOf(Tool(usableFunctions))
    )

val chat = generativeModel.startChat()
val prompt = "I have 57 cats, each owns 44 mittens, how many mittens is that in total?"

// Send the message to the generative model
var response = chat.sendMessage(prompt)

// Check if the model responded with a function call
response.functionCalls.first { it.name == "multiply" }.apply {
    val a: String by args
    val b: String by args

    val result = JSONObject(mapOf("result" to multiply(a.toDouble(), b.toDouble())))
    response = chat.sendMessage(
        content(role = "function") {
            part(FunctionResponsePart("multiply", result))
        }
    )
}

// Whenever the model responds with text, show it in the UI
response.text?.let { modelResponse ->
    println(modelResponse)
}
// Calls a hypothetical API to control a light bulb and returns the values that were set.
func controlLight(brightness: Double, colorTemperature: String) -> JSONObject {
  return ["brightness": .number(brightness), "colorTemperature": .string(colorTemperature)]
}

let generativeModel =
  GenerativeModel(
    // Use a model that supports function calling, like a Gemini 1.5 model
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    tools: [Tool(functionDeclarations: [
      FunctionDeclaration(
        name: "controlLight",
        description: "Set the brightness and color temperature of a room light.",
        parameters: [
          "brightness": Schema(
            type: .number,
            format: "double",
            description: "Light level from 0 to 100. Zero is off and 100 is full brightness."
          ),
          "colorTemperature": Schema(
            type: .string,
            format: "enum",
            description: "Color temperature of the light fixture.",
            enumValues: ["daylight", "cool", "warm"]
          ),
        ],
        requiredParameters: ["brightness", "colorTemperature"]
      ),
    ])]
  )

let chat = generativeModel.startChat()

let prompt = "Dim the lights so the room feels cozy and warm."

// Send the message to the model.
let response1 = try await chat.sendMessage(prompt)

// Check if the model responded with a function call.
// For simplicity, this sample uses the first function call found.
guard let functionCall = response1.functionCalls.first else {
  fatalError("Model did not respond with a function call.")
}
// Print an error if the returned function was not declared
guard functionCall.name == "controlLight" else {
  fatalError("Unexpected function called: \(functionCall.name)")
}
// Verify that the names and types of the parameters match the declaration
guard case let .number(brightness) = functionCall.args["brightness"] else {
  fatalError("Missing argument: brightness")
}
guard case let .string(colorTemperature) = functionCall.args["colorTemperature"] else {
  fatalError("Missing argument: colorTemperature")
}

// Call the executable function named in the FunctionCall with the arguments specified in the
// FunctionCall and let it call the hypothetical API.
let apiResponse = controlLight(brightness: brightness, colorTemperature: colorTemperature)

// Send the API response back to the model so it can generate a text response that can be
// displayed to the user.
let response2 = try await chat.sendMessage([ModelContent(
  role: "function",
  parts: [.functionResponse(FunctionResponse(name: "controlLight", response: apiResponse))]
)])

if let text = response2.text {
  print(text)
}
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
Map<String, Object?> setLightValues(Map<String, Object?> args) {
  return args;
}

final controlLightFunction = FunctionDeclaration(
    'controlLight',
    'Set the brightness and color temperature of a room light.',
    Schema.object(properties: {
      'brightness': Schema.number(
          description:
              'Light level from 0 to 100. Zero is off and 100 is full brightness.',
          nullable: false),
      'colorTemperatur': Schema.string(
          description:
              'Color temperature of the light fixture which can be `daylight`, `cool`, or `warm`',
          nullable: false),
    }));

final functions = {controlLightFunction.name: setLightValues};
FunctionResponse dispatchFunctionCall(FunctionCall call) {
  final function = functions[call.name]!;
  final result = function(call.args);
  return FunctionResponse(call.name, result);
}

final model = GenerativeModel(
  model: 'gemini-1.5-pro',
  apiKey: apiKey,
  tools: [
    Tool(functionDeclarations: [controlLightFunction])
  ],
);

final prompt = 'Dim the lights so the room feels cozy and warm.';
final content = [Content.text(prompt)];
var response = await model.generateContent(content);

List<FunctionCall> functionCalls;
while ((functionCalls = response.functionCalls.toList()).isNotEmpty) {
  var responses = <FunctionResponse>[
    for (final functionCall in functionCalls)
      dispatchFunctionCall(functionCall)
  ];
  content
    ..add(response.candidates.first.content)
    ..add(Content.functionResponses(responses));
  response = await model.generateContent(content);
}
print('Response: ${response.text}');
FunctionDeclaration multiplyDefinition =
    defineFunction(
        /* name  */ "multiply",
        /* description */ "returns a * b.",
        /* parameters */ Arrays.asList(
            Schema.numDouble("a", "First parameter"),
            Schema.numDouble("b", "Second parameter")),
        /* required */ Arrays.asList("a", "b"));

Tool tool = new Tool(Arrays.asList(multiplyDefinition), null);

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey,
        /* generationConfig (optional) */ null,
        /* safetySettings (optional) */ null,
        /* requestOptions (optional) */ new RequestOptions(),
        /* functionDeclarations (optional) */ Arrays.asList(tool));
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

// Create prompt
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText(
    "I have 57 cats, each owns 44 mittens, how many mittens is that in total?");
Content userMessage = userContentBuilder.build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

// Initialize the chat
ChatFutures chat = model.startChat();

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(userMessage);

Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        if (!result.getFunctionCalls().isEmpty()) {
          handleFunctionCall(result);
        }
        if (!result.getText().isEmpty()) {
          System.out.println(result.getText());
        }
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }

      private void handleFunctionCall(GenerateContentResponse result) {
        FunctionCallPart multiplyFunctionCallPart =
            result.getFunctionCalls().stream()
                .filter(fun -> fun.getName().equals("multiply"))
                .findFirst()
                .get();
        double a = Double.parseDouble(multiplyFunctionCallPart.getArgs().get("a"));
        double b = Double.parseDouble(multiplyFunctionCallPart.getArgs().get("b"));

        try {
          // `multiply(a, b)` is a regular java function defined in another class
          FunctionResponsePart functionResponsePart =
              new FunctionResponsePart(
                  "multiply", new JSONObject().put("result", multiply(a, b)));

          // Create prompt
          Content.Builder functionCallResponse = new Content.Builder();
          userContentBuilder.setRole("user");
          userContentBuilder.addPart(functionResponsePart);
          Content userMessage = userContentBuilder.build();

          chat.sendMessage(userMessage);
        } catch (JSONException e) {
          throw new RuntimeException(e);
        }
      }
    },
    executor);
from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-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)
// 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-2.0-flash",
  contents: "Tell me a story about a magic backpack.",
  config: {
    candidateCount: 1,
    stopSequences: ["x"],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

console.log(response.text);
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-2.0-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"
val config = generationConfig {
  temperature = 0.9f
  topK = 16
  topP = 0.1f
  maxOutputTokens = 200
  stopSequences = listOf("red")
}

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        generationConfig = config)
let config = GenerationConfig(
  temperature: 0.9,
  topP: 0.1,
  topK: 16,
  candidateCount: 1,
  maxOutputTokens: 200,
  stopSequences: ["red", "orange"]
)

let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    generationConfig: config
  )
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Tell me a story about a magic backpack.';

final response = await model.generateContent(
  [Content.text(prompt)],
  generationConfig: GenerationConfig(
    candidateCount: 1,
    stopSequences: ['x'],
    maxOutputTokens: 20,
    temperature: 1.0,
  ),
);
print(response.text);
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.temperature = 0.9f;
configBuilder.topK = 16;
configBuilder.topP = 0.1f;
configBuilder.maxOutputTokens = 200;
configBuilder.stopSequences = Arrays.asList("red");

GenerationConfig generationConfig = configBuilder.build();

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel("gemini-1.5-flash", BuildConfig.apiKey, generationConfig);

GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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-2.0-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)
  // 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-2.0-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;
}
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, "user"),
}
response, err := client.Models.GenerateContent(ctx, "gemini-2.0-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
val harassmentSafety = SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH)

val hateSpeechSafety = SafetySetting(HarmCategory.HATE_SPEECH, BlockThreshold.MEDIUM_AND_ABOVE)

val generativeModel =
    GenerativeModel(
        // The Gemini 1.5 models are versatile and work with most use cases
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        safetySettings = listOf(harassmentSafety, hateSpeechSafety))
let safetySettings = [
  SafetySetting(harmCategory: .dangerousContent, threshold: .blockLowAndAbove),
  SafetySetting(harmCategory: .harassment, threshold: .blockMediumAndAbove),
  SafetySetting(harmCategory: .hateSpeech, threshold: .blockOnlyHigh),
]

let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    safetySettings: safetySettings
  )
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'I support Martians Soccer Club and I think '
    'Jupiterians Football Club sucks! Write an ironic phrase telling '
    'them how I feel about them.';

final response = await model.generateContent(
  [Content.text(prompt)],
  safetySettings: [
    SafetySetting(HarmCategory.harassment, HarmBlockThreshold.medium),
    SafetySetting(HarmCategory.hateSpeech, HarmBlockThreshold.low),
  ],
);
try {
  print(response.text);
} catch (e) {
  print(e);
  for (final SafetyRating(:category, :probability)
      in response.candidates.first.safetyRatings!) {
    print('Safety Rating: $category - $probability');
  }
}
SafetySetting harassmentSafety =
    new SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH);

SafetySetting hateSpeechSafety =
    new SafetySetting(HarmCategory.HATE_SPEECH, BlockThreshold.MEDIUM_AND_ABOVE);

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        "gemini-1.5-flash",
        BuildConfig.apiKey,
        null, // generation config is optional
        Arrays.asList(harassmentSafety, hateSpeechSafety));

GenerativeModelFutures model = GenerativeModelFutures.from(gm);
from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Good morning! How are you?",
    config=types.GenerateContentConfig(
        system_instruction="You are a cat. Your name is Neko."
    ),
)
print(response.text)
// 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-2.0-flash",
  contents: "Good morning! How are you?",
  config: {
    systemInstruction: "You are a cat. Your name is Neko.",
  },
});
console.log(response.text);
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?", "user"),
}

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

response, err := client.Models.GenerateContent(ctx, "gemini-2.0-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"}}}'
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        systemInstruction = content { text("You are a cat. Your name is Neko.") },
    )
let generativeModel =
  GenerativeModel(
    // Specify a model that supports system instructions, like a Gemini 1.5 model
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    systemInstruction: ModelContent(role: "system", parts: "You are a cat. Your name is Neko.")
  )
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
  systemInstruction: Content.system('You are a cat. Your name is Neko.'),
);
final prompt = 'Good morning! How are you?';

final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
GenerativeModel model =
    new GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        /* modelName */ "gemini-1.5-flash",
        /* apiKey */ BuildConfig.apiKey,
        /* generationConfig (optional) */ null,
        /* safetySettings (optional) */ null,
        /* requestOptions (optional) */ new RequestOptions(),
        /* tools (optional) */ null,
        /* toolsConfig (optional) */ null,
        /* systemInstruction (optional) */ new Content.Builder()
            .addText("You are a cat. Your name is Neko.")
            .build());

เนื้อหาการตอบกลับ

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีอินสแตนซ์ GenerateContentResponse

เมธอด: models.streamGenerateContent

สร้างคำตอบแบบสตรีมจากโมเดลที่ได้รับอินพุต GenerateContentRequest

ปลายทาง

โพสต์ https://generativelanguage.googleapis.com/v1beta/{model=models/*}:streamGenerateContent

พารามิเตอร์เส้นทาง

model string

ต้องระบุ ชื่อของ Model ที่จะใช้สําหรับสร้างการทํางานให้เสร็จสมบูรณ์

รูปแบบ: models/{model} โดยจะมีรูปแบบเป็น models/{model}

เนื้อความของคำขอ

เนื้อความของคำขอมีข้อมูลซึ่งมีโครงสร้างดังต่อไปนี้

ฟิลด์
contents[] object (Content)

ต้องระบุ เนื้อหาของการสนทนาปัจจุบันกับโมเดล

สําหรับการค้นหาแบบเทิร์นเดียว อินสแตนซ์นี้จะเป็นแบบเดี่ยว สําหรับคําค้นหาแบบหลายรอบ เช่น chat ช่องนี้จะซ้ำกันซึ่งมีประวัติการสนทนาและคําขอล่าสุด

tools[] object (Tool)

ไม่บังคับ รายการ Tools ที่ Model อาจใช้เพื่อสร้างคำตอบถัดไป

Tool คือโค้ดที่ช่วยให้ระบบโต้ตอบกับระบบภายนอกเพื่อดำเนินการหรือชุดการดำเนินการที่อยู่นอกเหนือความรู้และขอบเขตของ Model Tool ที่รองรับคือ Function และ codeExecution ดูข้อมูลเพิ่มเติมได้จากคู่มือการเรียกใช้ฟังก์ชันและการเรียกใช้โค้ด

toolConfig object (ToolConfig)

ไม่บังคับ การกําหนดค่าเครื่องมือสําหรับ Tool ที่ระบุในคําขอ ดูตัวอย่างการใช้งานได้ในคู่มือการเรียกใช้ฟังก์ชัน

safetySettings[] object (SafetySetting)

ไม่บังคับ รายการอินสแตนซ์ SafetySetting ที่ไม่ซ้ำกันสำหรับการบล็อกเนื้อหาที่ไม่ปลอดภัย

ซึ่งจะมีผลกับ GenerateContentRequest.contents และ GenerateContentResponse.candidates การตั้งค่า SafetyCategory แต่ละประเภทไม่ควรมีมากกว่า 1 รายการ API จะบล็อกเนื้อหาและการตอบกลับที่ไม่เป็นไปตามเกณฑ์ที่กำหนดโดยการตั้งค่าเหล่านี้ รายการนี้จะลบล้างการตั้งค่าเริ่มต้นสำหรับ SafetyCategory แต่ละรายการที่ระบุไว้ใน safetySettings หากไม่มี SafetySetting สำหรับ SafetyCategory ที่ระบุในรายการ API จะใช้การตั้งค่าความปลอดภัยเริ่มต้นสำหรับหมวดหมู่นั้น ระบบรองรับหมวดหมู่อันตราย HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY ดูข้อมูลโดยละเอียดเกี่ยวกับการตั้งค่าความปลอดภัยที่ใช้ได้ได้จากคู่มือ นอกจากนี้ โปรดดูคำแนะนำด้านความปลอดภัยเพื่อดูวิธีนำข้อควรพิจารณาด้านความปลอดภัยมาใช้ในการประยุกต์ใช้ AI

systemInstruction object (Content)

ไม่บังคับ คำสั่งของระบบที่นักพัฒนาแอปตั้งค่าไว้ ปัจจุบันมีเฉพาะข้อความเท่านั้น

generationConfig object (GenerationConfig)

ไม่บังคับ ตัวเลือกการกําหนดค่าสําหรับการสร้างโมเดลและเอาต์พุต

cachedContent string

ไม่บังคับ ชื่อของเนื้อหาที่แคชไว้เพื่อใช้เป็นบริบทในการแสดงการคาดคะเน รูปแบบ: cachedContents/{cachedContent}

ตัวอย่างคำขอ

from google import genai

client = genai.Client()
response = client.models.generate_content_stream(
    model="gemini-2.0-flash", contents="Write a story about a magic backpack."
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
// 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-2.0-flash",
  contents: "Write a story about a magic backpack.",
});
let text = "";
for await (const chunk of response) {
  console.log(chunk.text);
  text += chunk.text;
}
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.", "user"),
}
for response, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-2.0-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."}]}]}'
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val prompt = "Write a story about a magic backpack."
// Use streaming with text-only input
generativeModel.generateContentStream(prompt).collect { chunk -> print(chunk.text) }
let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

let prompt = "Write a story about a magic backpack."
// Use streaming with text-only input
for try await response in generativeModel.generateContentStream(prompt) {
  if let text = response.text {
    print(text)
  }
}
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Write a story about a magic backpack.';

final responses = model.generateContentStream([Content.text(prompt)]);
await for (final response in responses) {
  print(response.text);
}
// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Content content =
    new Content.Builder().addText("Write a story about a magic backpack.").build();

Publisher<GenerateContentResponse> streamingResponse = model.generateContentStream(content);

StringBuilder outputContent = new StringBuilder();

streamingResponse.subscribe(
    new Subscriber<GenerateContentResponse>() {
      @Override
      public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        outputContent.append(chunk);
      }

      @Override
      public void onComplete() {
        System.out.println(outputContent);
      }

      @Override
      public void onError(Throwable t) {
        t.printStackTrace();
      }

      @Override
      public void onSubscribe(Subscription s) {
        s.request(Long.MAX_VALUE);
      }
    });
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-2.0-flash", contents=["Tell me about this instrument", organ]
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
// 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-2.0-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;
}
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, "user"),
}
for response, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-2.0-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
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val image: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image)
val inputContent = content {
  image(image)
  text("What's in this picture?")
}

generativeModel.generateContentStream(inputContent).collect { chunk -> print(chunk.text) }
let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

guard let image = UIImage(systemName: "cloud.sun") else { fatalError() }

let prompt = "What's in this picture?"

for try await response in generativeModel.generateContentStream(image, prompt) {
  if let text = response.text {
    print(text)
  }
}
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);

Future<DataPart> fileToPart(String mimeType, String path) async {
  return DataPart(mimeType, await File(path).readAsBytes());
}

final prompt = 'Describe how this product might be manufactured.';
final image = await fileToPart('image/jpeg', 'resources/jetpack.jpg');

final responses = model.generateContentStream([
  Content.multi([TextPart(prompt), image])
]);
await for (final response in responses) {
  print(response.text);
}
// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap image1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.image1);
Bitmap image2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.image2);

Content content =
    new Content.Builder()
        .addText("What's different between these pictures?")
        .addImage(image1)
        .addImage(image2)
        .build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

Publisher<GenerateContentResponse> streamingResponse = model.generateContentStream(content);

StringBuilder outputContent = new StringBuilder();

streamingResponse.subscribe(
    new Subscriber<GenerateContentResponse>() {
      @Override
      public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        outputContent.append(chunk);
      }

      @Override
      public void onComplete() {
        System.out.println(outputContent);
      }

      @Override
      public void onError(Throwable t) {
        t.printStackTrace();
      }

      @Override
      public void onSubscribe(Subscription s) {
        s.request(Long.MAX_VALUE);
      }
    });
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-2.0-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
# 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
PythonNode.jsGoเปลือกหอย
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-2.0-flash", contents=[myfile, "Describe this video clip"]
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
// 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-2.0-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;
}
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, "user"),
}

for result, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-2.0-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
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-2.0-flash",
    contents=["Give me a summary of this document:", sample_pdf],
)

for chunk in response:
    print(chunk.text)
    print("_" * 80)
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
from google import genai
from google.genai import types

client = genai.Client()
chat = client.chats.create(
    model="gemini-2.0-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())
// 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-2.0-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());
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", "user"),
	genai.NewContentFromText("Great to meet you. What would you like to know?", "model"),
}
chat, err := client.Chats.Create(ctx, "gemini-2.0-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"
// Use streaming with multi-turn conversations (like chat)
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val chat =
    generativeModel.startChat(
        history =
            listOf(
                content(role = "user") { text("Hello, I have 2 dogs in my house.") },
                content(role = "model") {
                  text("Great to meet you. What would you like to know?")
                }))

chat.sendMessageStream("How many paws are in my house?").collect { chunk -> print(chunk.text) }
let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

// Optionally specify existing chat history
let history = [
  ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."),
  ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"),
]

// Initialize the chat with optional chat history
let chat = generativeModel.startChat(history: history)

// To stream generated text output, call sendMessageStream and pass in the message
let contentStream = chat.sendMessageStream("How many paws are in my house?")
for try await chunk in contentStream {
  if let text = chunk.text {
    print(text)
  }
}
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final chat = model.startChat(history: [
  Content.text('hello'),
  Content.model([TextPart('Great to meet you. What would you like to know?')])
]);
var responses =
    chat.sendMessageStream(Content.text('I have 2 dogs in my house.'));
await for (final response in responses) {
  print(response.text);
  print('_' * 80);
}
responses =
    chat.sendMessageStream(Content.text('How many paws are in my house?'));
await for (final response in responses) {
  print(response.text);
  print('_' * 80);
}
// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

// (optional) Create previous chat history for context
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();

Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();

List<Content> history = Arrays.asList(userContent, modelContent);

// Initialize the chat
ChatFutures chat = model.startChat(history);

// Create a new user message
Content.Builder userMessageBuilder = new Content.Builder();
userMessageBuilder.setRole("user");
userMessageBuilder.addText("How many paws are in my house?");
Content userMessage = userMessageBuilder.build();

// Use streaming with text-only input
Publisher<GenerateContentResponse> streamingResponse = model.generateContentStream(userMessage);

StringBuilder outputContent = new StringBuilder();

streamingResponse.subscribe(
    new Subscriber<GenerateContentResponse>() {
      @Override
      public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        outputContent.append(chunk);
      }

      @Override
      public void onComplete() {
        System.out.println(outputContent);
      }

      @Override
      public void onSubscribe(Subscription s) {
        s.request(Long.MAX_VALUE);
      }

      @Override
      public void onError(Throwable t) {}

    });

เนื้อหาการตอบกลับ

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีสตรีมของอินสแตนซ์ GenerateContentResponse

GenerateContentResponse

การตอบกลับจากโมเดลที่รองรับคำตอบที่เป็นไปได้หลายรายการ

ระบบจะรายงานการจัดประเภทความปลอดภัยและการกรองเนื้อหาสำหรับทั้งพรอมต์ใน GenerateContentResponse.prompt_feedback และสำหรับผู้สมัครแต่ละรายใน finishReason และใน safetyRatings API จะดำเนินการดังนี้ - แสดงผลลัพธ์ทั้งหมดที่ขอหรือไม่แสดงผลลัพธ์ใดๆ เลย - แสดงผลลัพธ์เป็น 0 เฉพาะในกรณีที่พรอมต์ไม่ถูกต้อง (ดู promptFeedback) - รายงานความคิดเห็นเกี่ยวกับผู้สมัครแต่ละรายใน finishReason และ safetyRatings

ฟิลด์
candidates[] object (Candidate)

คำตอบที่เป็นไปได้จากโมเดล

promptFeedback object (PromptFeedback)

แสดงความคิดเห็นของพรอมต์ที่เกี่ยวข้องกับตัวกรองเนื้อหา

usageMetadata object (UsageMetadata)

เอาต์พุตเท่านั้น ข้อมูลเมตาเกี่ยวกับการใช้โทเค็นของคำขอสร้าง

modelVersion string

เอาต์พุตเท่านั้น เวอร์ชันโมเดลที่ใช้สร้างคำตอบ

responseId string

เอาต์พุตเท่านั้น responseId ใช้เพื่อระบุคำตอบแต่ละรายการ

การแสดง JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string,
  "responseId": string
}

PromptFeedback

ชุดข้อมูลเมตาของความคิดเห็นที่พรอมต์ระบุใน GenerateContentRequest.content

ฟิลด์
blockReason enum (BlockReason)

ไม่บังคับ หากตั้งค่าไว้ ระบบจะบล็อกพรอมต์และจะไม่แสดงรายการที่ตรงกัน เปลี่ยนข้อความแจ้ง

safetyRatings[] object (SafetyRating)

คะแนนความปลอดภัยของพรอมต์ แต่ละหมวดหมู่มีการจัดประเภทได้สูงสุด 1 รายการ

การแสดง JSON
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

BlockReason

ระบุเหตุผลที่บล็อกพรอมต์

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

เอาต์พุตเท่านั้น รายการรูปแบบที่ประมวลผลสำหรับอินพุตคำขอใช้เครื่องมือ

การแสดง 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)
    }
  ]
}

ผู้สมัคร

ตัวเลือกคำตอบที่สร้างขึ้นจากโมเดล

ฟิลด์
content object (Content)

เอาต์พุตเท่านั้น เนื้อหาที่สร้างขึ้นซึ่งแสดงผลจากโมเดล

finishReason enum (FinishReason)

ไม่บังคับ เอาต์พุตเท่านั้น สาเหตุที่โมเดลหยุดสร้างโทเค็น

หากเป็นค่าว่าง แสดงว่าโมเดลยังไม่ได้หยุดสร้างโทเค็น

safetyRatings[] object (SafetyRating)

รายการคะแนนความปลอดภัยของคำตอบที่เป็นไปได้

แต่ละหมวดหมู่มีการจัดประเภทได้สูงสุด 1 รายการ

citationMetadata object (CitationMetadata)

เอาต์พุตเท่านั้น ข้อมูลการอ้างอิงสำหรับคำตอบที่ระบบสร้างขึ้น

ฟิลด์นี้อาจมีการป้อนข้อมูลการท่องจำสำหรับข้อความที่รวมอยู่ใน content ข้อความเหล่านี้คือข้อความที่ "ท่อง" จากเนื้อหาที่มีลิขสิทธิ์ในข้อมูลที่ใช้ฝึกของ LLM พื้นฐาน

tokenCount integer

เอาต์พุตเท่านั้น จํานวนโทเค็นของรายการนี้

groundingAttributions[] object (GroundingAttribution)

เอาต์พุตเท่านั้น ข้อมูลการระบุแหล่งที่มาของแหล่งข้อมูลที่มีส่วนทำให้เกิดคำตอบที่อิงตามข้อมูลจริง

ช่องนี้จะแสดงข้อมูลสำหรับสาย GenerateAnswer

groundingMetadata object (GroundingMetadata)

เอาต์พุตเท่านั้น ข้อมูลเมตาพื้นฐานสำหรับผู้สมัคร

ช่องนี้จะแสดงข้อมูลสำหรับสาย GenerateContent

avgLogprobs number

เอาต์พุตเท่านั้น คะแนนความน่าจะเป็นแบบลอจิสติกเฉลี่ยของผู้สมัคร

logprobsResult object (LogprobsResult)

เอาต์พุตเท่านั้น คะแนนความน่าจะเป็นเชิงสถิติสำหรับโทเค็นคำตอบและโทเค็นยอดนิยม

urlRetrievalMetadata object (UrlRetrievalMetadata)

เอาต์พุตเท่านั้น ข้อมูลเมตาที่เกี่ยวข้องกับเครื่องมือการดึงข้อมูลบริบทของ URL

urlContextMetadata object (UrlContextMetadata)

เอาต์พุตเท่านั้น ข้อมูลเมตาที่เกี่ยวข้องกับเครื่องมือการดึงข้อมูลบริบทของ URL

index integer

เอาต์พุตเท่านั้น ดัชนีของผู้สมัครในรายการผู้สมัครตอบกลับ

การแสดง 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)
  },
  "urlRetrievalMetadata": {
    object (UrlRetrievalMetadata)
  },
  "urlContextMetadata": {
    object (UrlContextMetadata)
  },
  "index": integer
}

FinishReason

ระบุสาเหตุที่โมเดลหยุดสร้างโทเค็น

Enum
FINISH_REASON_UNSPECIFIED ค่าเริ่มต้น ค่านี้ไม่ได้ใช้งาน
STOP จุดสิ้นสุดตามปกติของโมเดลหรือลําดับการหยุดที่ระบุ
MAX_TOKENS มีโทเค็นถึงจำนวนสูงสุดตามที่ระบุไว้ในคำขอแล้ว
SAFETY เนื้อหาที่เป็นไปได้สำหรับคำตอบถูกแจ้งว่าไม่เหมาะสมเนื่องจากเหตุผลด้านความปลอดภัย
RECITATION เนื้อหาคำตอบของผู้สมัครถูกแจ้งว่าเป็นการท่องจำ
LANGUAGE เนื้อหาคำตอบที่เป็นไปได้ถูกแจ้งว่าไม่เหมาะสมเนื่องจากใช้ภาษาที่ไม่รองรับ
OTHER ไม่ทราบสาเหตุ
BLOCKLIST การสร้างโทเค็นหยุดลงเนื่องจากเนื้อหามีคำต้องห้าม
PROHIBITED_CONTENT การสร้างโทเค็นหยุดลงเนื่องจากมีเนื้อหาที่อาจไม่เหมาะสม
SPII การสร้างโทเค็นหยุดลงเนื่องจากเนื้อหาอาจมีข้อมูลส่วนบุคคลที่ละเอียดอ่อนและระบุตัวบุคคลนั้นได้ (SPII)
MALFORMED_FUNCTION_CALL การเรียกใช้ฟังก์ชันที่โมเดลสร้างขึ้นไม่ถูกต้อง
IMAGE_SAFETY การสร้างโทเค็นหยุดลงเนื่องจากรูปภาพที่สร้างขึ้นมีการละเมิดความปลอดภัย

GroundingAttribution

การระบุแหล่งที่มาของแหล่งข้อมูลที่มีส่วนทำให้เกิดคำตอบ

ฟิลด์
sourceId object (AttributionSourceId)

เอาต์พุตเท่านั้น ตัวระบุแหล่งที่มาที่มีส่วนร่วมในการระบุแหล่งที่มานี้

content object (Content)

เนื้อหาแหล่งที่มาที่เป็นต้นทางของการระบุแหล่งที่มานี้

การแสดง JSON
{
  "sourceId": {
    object (AttributionSourceId)
  },
  "content": {
    object (Content)
  }
}

AttributionSourceId

ตัวระบุแหล่งที่มาที่มีส่วนร่วมในการระบุแหล่งที่มานี้

ฟิลด์
source Union type
source ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
groundingPassage object (GroundingPassageId)

ตัวระบุสำหรับข้อความย่อยในบรรทัด

semanticRetrieverChunk object (SemanticRetrieverChunk)

ตัวระบุของ Chunk ที่ดึงข้อมูลผ่าน Semantic Retriever

การแสดง JSON
{

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

GroundingPassageId

ตัวระบุของชิ้นส่วนภายใน GroundingPassage

ฟิลด์
passageId string

เอาต์พุตเท่านั้น รหัสของข้อความที่ตรงกับGroundingPassage.idของ GenerateAnswerRequest

partIndex integer

เอาต์พุตเท่านั้น ดัชนีของส่วนภายใน GroundingPassage.content ของ GenerateAnswerRequest

การแสดง JSON
{
  "passageId": string,
  "partIndex": integer
}

SemanticRetrieverChunk

ตัวระบุสำหรับ Chunk ที่ดึงข้อมูลผ่าน Semantic Retriever ที่ระบุไว้ใน GenerateAnswerRequest โดยใช้ SemanticRetrieverConfig

ฟิลด์
source string

เอาต์พุตเท่านั้น ชื่อแหล่งที่มาที่ตรงกับ SemanticRetrieverConfig.source ของคําขอ ตัวอย่างเช่น corpora/123 หรือ corpora/123/documents/abc

chunk string

เอาต์พุตเท่านั้น ชื่อของ Chunk ที่มีข้อความระบุแหล่งที่มา ตัวอย่าง: corpora/123/documents/abc/chunks/xyz

การแสดง JSON
{
  "source": string,
  "chunk": string
}

GroundingMetadata

ข้อมูลเมตาที่แสดงผลกับไคลเอ็นต์เมื่อเปิดใช้การกราวด์

ฟิลด์
groundingChunks[] object (GroundingChunk)

รายการข้อมูลอ้างอิงสนับสนุนที่ดึงมาจากแหล่งข้อมูลอ้างอิง

groundingSupports[] object (GroundingSupport)

รายการการรองรับการต่อสายกราวด์

webSearchQueries[] string

คำค้นหาของ Web Search สำหรับการค้นหาเว็บที่ตามมา

searchEntryPoint object (SearchEntryPoint)

ไม่บังคับ รายการการค้นหาของ Google สําหรับการค้นหาเว็บที่ตามมา

retrievalMetadata object (RetrievalMetadata)

ข้อมูลเมตาที่เกี่ยวข้องกับการดึงข้อมูลในขั้นตอนการกราวด์

การแสดง JSON
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  }
}

SearchEntryPoint

จุดแรกเข้าของ Google Search

ฟิลด์
renderedContent string

ไม่บังคับ ข้อมูลโค้ดที่ติดทั่วเว็บไซต์ซึ่งฝังในหน้าเว็บหรือเว็บวิวของแอปได้

sdkBlob string (bytes format)

ไม่บังคับ JSON ที่เข้ารหัส Base64 ซึ่งแสดงอาร์เรย์ของคู่ <ข้อความค้นหา, URL การค้นหา>

สตริงที่เข้ารหัส Base64

การแสดง JSON
{
  "renderedContent": string,
  "sdkBlob": string
}

GroundingChunk

Chunk พื้นฐาน

ฟิลด์
chunk_type Union type
ประเภทข้อมูล chunk_type ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
web object (Web)

ส่วนของข้อมูลพื้นฐานจากเว็บ

การแสดง JSON
{

  // chunk_type
  "web": {
    object (Web)
  }
  // Union type
}

เว็บ

ข้อมูลบางส่วนจากเว็บ

ฟิลด์
uri string

ข้อมูลอ้างอิง URI ของข้อมูล

title string

ชื่อของข้อมูล

การแสดง JSON
{
  "uri": string,
  "title": string
}

GroundingSupport

การสนับสนุนการต่อสายกราวด์

ฟิลด์
groundingChunkIndices[] integer

รายการดัชนี (ใน "grounding_chunk") ที่ระบุการอ้างอิงที่เกี่ยวข้องกับการอ้างสิทธิ์ เช่น [1,3,4] หมายความว่า grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] คือเนื้อหาที่ดึงมาซึ่งมีการระบุแหล่งที่มาว่ามาจากการอ้างสิทธิ์

confidenceScores[] number

คะแนนความเชื่อมั่นของข้อมูลอ้างอิงการสนับสนุน อยู่ในช่วง 0 ถึง 1 โดย 1 คือมั่นใจมากที่สุด รายการนี้ต้องมีขนาดเท่ากับ groundingChunkIndices

segment object (Segment)

ส่วนเนื้อหาที่การสนับสนุนนี้เกี่ยวข้อง

การแสดง JSON
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

กลุ่ม

ส่วนของเนื้อหา

ฟิลด์
partIndex integer

เอาต์พุตเท่านั้น ดัชนีของออบเจ็กต์ส่วนภายในออบเจ็กต์เนื้อหาหลัก

startIndex integer

เอาต์พุตเท่านั้น ดัชนีเริ่มต้นในส่วนที่ระบุ ซึ่งวัดเป็นไบต์ ส่วนต่างจากจุดเริ่มต้นของส่วน โดยนับรวมและเริ่มต้นที่ 0

endIndex integer

เอาต์พุตเท่านั้น ดัชนีสิ้นสุดในส่วนที่ระบุ ซึ่งวัดเป็นไบต์ ส่วนต่างจากจุดเริ่มต้นของส่วน โดยเริ่มที่ 0

text string

เอาต์พุตเท่านั้น ข้อความที่สอดคล้องกับส่วนของคำตอบ

การแสดง JSON
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

RetrievalMetadata

ข้อมูลเมตาที่เกี่ยวข้องกับการดึงข้อมูลในขั้นตอนการกราวด์

ฟิลด์
googleSearchDynamicRetrievalScore number

ไม่บังคับ คะแนนที่บ่งบอกถึงความเป็นไปได้ที่ข้อมูลจากการค้นหาของ Google จะช่วยตอบพรอมต์ คะแนนอยู่ในช่วง [0, 1] โดยที่ 0 หมายถึงมีแนวโน้มน้อยที่สุดและ 1 หมายถึงมีแนวโน้มมากที่สุด ระบบจะป้อนข้อมูลคะแนนนี้เมื่อเปิดใช้การเชื่อมโยงกับ Google Search และการดึงข้อมูลแบบไดนามิกเท่านั้น ระบบจะเปรียบเทียบกับเกณฑ์เพื่อพิจารณาว่าจะเรียกใช้ Google Search หรือไม่

การแสดง JSON
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

ผลลัพธ์ Logprobs

ฟิลด์
topCandidates[] object (TopCandidates)

ความยาว = จํานวนขั้นตอนทั้งหมดในการถอดรหัส

chosenCandidates[] object (Candidate)

ความยาว = จํานวนขั้นตอนทั้งหมดในการถอดรหัส ผู้สมัครที่เลือกอาจอยู่ใน topCandidates หรือไม่ก็ได้

การแสดง JSON
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ]
}

TopCandidates

ผู้สมัครที่มีความน่าจะเป็นของบันทึกสูงสุดในแต่ละขั้นตอนการถอดรหัส

ฟิลด์
candidates[] object (Candidate)

จัดเรียงตามความน่าจะเป็นเชิงลอจิสติกจากมากไปน้อย

การแสดง JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

ผู้สมัคร

ผู้สมัครสำหรับโทเค็นและคะแนน logprobs

ฟิลด์
token string

ค่าสตริงโทเค็นของผู้สมัคร

tokenId integer

ค่ารหัสโทเค็นของผู้สมัคร

logProbability number

ความน่าจะเป็นของบันทึกของผู้สมัคร

การแสดง JSON
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

UrlRetrievalMetadata

ข้อมูลเมตาที่เกี่ยวข้องกับเครื่องมือการดึงข้อมูลบริบทของ URL

ฟิลด์
urlRetrievalContexts[] object (UrlRetrievalContext)

รายการบริบทการดึงข้อมูล URL

การแสดง JSON
{
  "urlRetrievalContexts": [
    {
      object (UrlRetrievalContext)
    }
  ]
}

UrlRetrievalContext

บริบทของการดึงข้อมูล URL รายการเดียว

ฟิลด์
retrievedUrl string

URL ที่เครื่องมือดึงข้อมูล

การแสดง JSON
{
  "retrievedUrl": string
}

UrlContextMetadata

ข้อมูลเมตาที่เกี่ยวข้องกับเครื่องมือการดึงข้อมูลบริบทของ URL

ฟิลด์
urlMetadata[] object (UrlMetadata)

รายการบริบท URL

การแสดง JSON
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}

UrlMetadata

บริบทของการดึงข้อมูล URL รายการเดียว

ฟิลด์
retrievedUrl string

URL ที่เครื่องมือดึงข้อมูล

urlRetrievalStatus enum (UrlRetrievalStatus)

สถานะการเรียกข้อมูล URL

การแสดง JSON
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}

UrlRetrievalStatus

สถานะการเรียกข้อมูล URL

Enum
URL_RETRIEVAL_STATUS_UNSPECIFIED ค่าเริ่มต้น ค่านี้ไม่ได้ใช้งาน
URL_RETRIEVAL_STATUS_SUCCESS ดึงข้อมูล URL สำเร็จ
URL_RETRIEVAL_STATUS_ERROR ดึงข้อมูล URL ไม่สำเร็จเนื่องจากเกิดข้อผิดพลาด

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
}

GenerationConfig

ตัวเลือกการกําหนดค่าสําหรับการสร้างโมเดลและเอาต์พุต พารามิเตอร์บางรายการอาจกำหนดค่าไม่ได้สำหรับบางรุ่น

ฟิลด์
stopSequences[] string

ไม่บังคับ ชุดลำดับอักขระ (สูงสุด 5 ชุด) ที่จะหยุดการสร้างเอาต์พุต หากระบุไว้ API จะหยุดเมื่อ stop_sequence ปรากฏขึ้นครั้งแรก ลำดับการหยุดจะไม่รวมอยู่ในคำตอบ

responseMimeType string

ไม่บังคับ ประเภท MIME ของข้อความที่เป็นไปได้ที่สร้างขึ้น ประเภท MIME ที่รองรับ ได้แก่ text/plain: (ค่าเริ่มต้น) เอาต์พุตข้อความ application/json: การตอบกลับ JSON ในคำตอบที่เป็นไปได้ text/x.enum: ENUM เป็นคำตอบแบบสตริงในคำตอบที่เป็นไปได้ ดูรายการประเภท MIME ของข้อความที่รองรับทั้งหมดได้ในเอกสาร

responseSchema object (Schema)

ไม่บังคับ สคีมาเอาต์พุตของข้อความผู้สมัครที่สร้างขึ้น สคีมาต้องเป็นชุดย่อยของสคีมา OpenAPI และอาจเป็นออบเจ็กต์ พรอมต์ หรืออาร์เรย์

หากตั้งค่า responseMimeType ไว้ ก็ต้องตั้งค่า responseMimeType ที่เข้ากันได้ด้วย ประเภท MIME ที่เข้ากันได้: application/json: สคีมาสำหรับการตอบกลับ JSON ดูรายละเอียดเพิ่มเติมได้ที่คู่มือการสร้างข้อความ JSON

responseModalities[] enum (Modality)

ไม่บังคับ รูปแบบคำตอบที่ขอ แสดงชุดรูปแบบที่โมเดลสามารถแสดงผลได้และควรแสดงในการตอบกลับ รายการนี้ตรงกับรูปแบบของคำตอบทุกประการ

โมเดลหนึ่งอาจมีชุดค่าผสมของรูปแบบที่รองรับหลายชุด หากรูปแบบที่ขอไม่ตรงกับชุดค่าผสมที่รองรับ ระบบจะแสดงข้อผิดพลาด

รายการว่างจะเทียบเท่ากับการขอเฉพาะข้อความ

candidateCount integer

ไม่บังคับ จํานวนคําตอบที่สร้างขึ้นที่จะแสดง หากไม่ได้ตั้งค่าไว้ ระบบจะใช้ค่าเริ่มต้นเป็น 1 โปรดทราบว่าการอัปเดตนี้ใช้ไม่ได้กับรุ่นก่อนหน้า (กลุ่มผลิตภัณฑ์ Gemini 1.0)

maxOutputTokens integer

ไม่บังคับ จำนวนโทเค็นสูงสุดที่จะรวมไว้ในคำตอบที่เป็นไปได้

หมายเหตุ: ค่าเริ่มต้นจะแตกต่างกันไปตามรุ่น โปรดดูแอตทริบิวต์ Model.output_token_limit ของ Model ที่แสดงผลจากฟังก์ชัน getModel

temperature number

ไม่บังคับ ควบคุมความสุ่มของเอาต์พุต

หมายเหตุ: ค่าเริ่มต้นจะแตกต่างกันไปตามรุ่น โปรดดูแอตทริบิวต์ Model.temperature ของ Model ที่แสดงผลจากฟังก์ชัน getModel

ค่าที่ใช้ได้อยู่ในช่วง [0.0, 2.0]

topP number

ไม่บังคับ ความน่าจะเป็นสะสมสูงสุดของโทเค็นที่จะพิจารณาเมื่อสุ่มตัวอย่าง

โมเดลนี้ใช้การสุ่มตัวอย่าง Top-k และ Top-p (นิวเคลียส) รวมกัน

ระบบจะจัดเรียงโทเค็นตามความน่าจะเป็นที่กำหนดไว้เพื่อให้ระบบพิจารณาเฉพาะโทเค็นที่เป็นไปได้มากที่สุด การสุ่มตัวอย่าง Top-k จะจํากัดจํานวนโทเค็นสูงสุดที่จะพิจารณาโดยตรง ส่วนการสุ่มตัวอย่าง Nucleus จะจํากัดจํานวนโทเค็นตามความน่าจะเป็นสะสม

หมายเหตุ: ค่าเริ่มต้นจะแตกต่างกันไปตาม Model และระบุโดยแอตทริบิวต์Model.top_pที่แสดงผลจากฟังก์ชัน getModel แอตทริบิวต์ topK ที่ว่างเปล่าบ่งบอกว่าโมเดลไม่ได้ใช้การสุ่มตัวอย่าง Top-K และไม่อนุญาตให้ตั้งค่า topK ในคําขอ

topK integer

ไม่บังคับ จำนวนโทเค็นสูงสุดที่จะพิจารณาเมื่อสุ่มตัวอย่าง

โมเดล Gemini ใช้การสุ่มตัวอย่าง Top-p (นิวเคลียส) หรือการสุ่มตัวอย่าง Top-k และนิวเคลียสร่วมกัน การสุ่มตัวอย่าง Top-k จะพิจารณาชุดโทเค็นที่เป็นไปได้มากที่สุด topK รายการ โมเดลที่ทำงานด้วยการสุ่มตัวอย่าง Nucleus ไม่อนุญาตให้ตั้งค่า topK

หมายเหตุ: ค่าเริ่มต้นจะแตกต่างกันไปตาม Model และระบุโดยแอตทริบิวต์Model.top_pที่แสดงผลจากฟังก์ชัน getModel แอตทริบิวต์ topK ที่ว่างเปล่าบ่งบอกว่าโมเดลไม่ได้ใช้การสุ่มตัวอย่าง Top-K และไม่อนุญาตให้ตั้งค่า topK ในคําขอ

seed integer

ไม่บังคับ เมล็ดที่ใช้ในการถอดรหัส หากไม่ได้ตั้งค่า คำขอจะใช้ Seed ที่สร้างขึ้นแบบสุ่ม

presencePenalty number

ไม่บังคับ บทลงโทษการปรากฏมีผลกับ logprobs ของโทเค็นถัดไปหากระบบเคยเห็นโทเค็นนั้นในการตอบกลับแล้ว

การลงโทษนี้จะเป็นแบบเปิด/ปิดแบบ 2 ค่า และไม่ขึ้นอยู่กับจำนวนครั้งที่ใช้โทเค็น (หลังจากครั้งแรก) ใช้ frequencyPenalty สำหรับบทลงโทษที่เพิ่มขึ้นทุกครั้งที่มีการใช้

การลงโทษเชิงบวกจะทําให้ระบบไม่ใช้โทเค็นที่เคยใช้ในคําตอบแล้ว ซึ่งจะเพิ่มคําศัพท์

การลงโทษเชิงลบจะส่งเสริมให้ใช้โทเค็นที่เคยใช้ในคำตอบแล้ว ซึ่งจะลดคลังคำศัพท์

frequencyPenalty number

ไม่บังคับ การลดคะแนนความถี่ที่มีผลกับ logprobs ของโทเค็นถัดไป คูณด้วยจํานวนครั้งที่เห็นโทเค็นแต่ละรายการในการตอบกลับจนถึงตอนนี้

การลงโทษเชิงบวกจะทําให้ระบบไม่ใช้โทเค็นที่เคยใช้ไปแล้ว โดยการลงโทษจะสัมพันธ์กับจํานวนครั้งที่ใช้โทเค็นนั้น ยิ่งใช้โทเค็นมากเท่าใด โมเดลก็จะยิ่งใช้โทเค็นนั้นอีกครั้งได้ยากขึ้นเท่านั้น ซึ่งจะเพิ่มคําศัพท์ในการตอบกลับ

ข้อควรระวัง: การลดคะแนนเชิงลบจะกระตุ้นให้โมเดลนําโทเค็นมาใช้ซ้ำตามสัดส่วนจํานวนครั้งที่มีการใช้โทเค็น ค่าลบเล็กๆ จะลดคลังคำตอบ ค่าลบที่มากขึ้นจะทำให้โมเดลเริ่มใช้โทเค็นทั่วไปซ้ำๆ จนกว่าจะถึงขีดจํากัด maxOutputTokens

responseLogprobs boolean

ไม่บังคับ หากเป็น "จริง" ระบบจะส่งออกผลลัพธ์ logprobs ในการตอบกลับ

logprobs integer

ไม่บังคับ ใช้ได้เฉพาะในกรณีที่ responseLogprobs=True ซึ่งจะตั้งค่าจำนวน logprobs ยอดนิยมที่จะแสดงในแต่ละขั้นตอนการถอดรหัสใน Candidate.logprobs_result

enableEnhancedCivicAnswers boolean

ไม่บังคับ เปิดใช้คำตอบเกี่ยวกับข้อมูลประชากรที่ปรับปรุงแล้ว โดยอาจไม่พร้อมใช้งานสำหรับบางรุ่น

speechConfig object (SpeechConfig)

ไม่บังคับ การกําหนดค่าการสร้างเสียง

thinkingConfig object (ThinkingConfig)

ไม่บังคับ การกําหนดค่าสําหรับฟีเจอร์การคิด ระบบจะแสดงข้อผิดพลาดหากตั้งค่าช่องนี้สําหรับโมเดลที่ไม่รองรับการคิด

mediaResolution enum (MediaResolution)

ไม่บังคับ หากระบุไว้ ระบบจะใช้ความละเอียดของสื่อที่ระบุ

การแสดง JSON
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "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)
  },
  "mediaResolution": enum (MediaResolution)
}

รูปแบบ

รูปแบบคำตอบที่รองรับ

Enum
MODALITY_UNSPECIFIED ค่าเริ่มต้น
TEXT ระบุว่าโมเดลควรแสดงผลข้อความ
IMAGE ระบุว่าโมเดลควรแสดงผลรูปภาพ
AUDIO ระบุว่าโมเดลควรแสดงผลเป็นเสียง

SpeechConfig

การกําหนดค่าการสร้างเสียง

ฟิลด์
voiceConfig object (VoiceConfig)

การกําหนดค่าในกรณีที่มีเสียงพูดแบบเดียว

multiSpeakerVoiceConfig object (MultiSpeakerVoiceConfig)

ไม่บังคับ การกําหนดค่าสําหรับการตั้งค่าลําโพงหลายตัว ฟิลด์นี้ใช้ร่วมกับฟิลด์ voiceConfig ไม่ได้

languageCode string

ไม่บังคับ รหัสภาษา (ในรูปแบบ BCP 47 เช่น "en-US") สำหรับการสังเคราะห์เสียง

ค่าที่ใช้ได้มีดังนี้ de-DE, en-AU, en-GB, en-IN, en-US, es-US, fr-FR, hi-IN, pt-BR, ar-XA, es-ES, fr-CA, id-ID, it-IT, ja-JP, tr-TR, vi-VN, bn-IN, gu-IN, kn-IN, ml-IN, mr-IN, ta-IN, te-IN, nl-NL, ko-KR, cmn-CN, pl-PL, ru-RU และ th-TH

การแสดง JSON
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}

VoiceConfig

การกําหนดค่าเสียงที่จะใช้

ฟิลด์
voice_config Union type
การกําหนดค่าสําหรับลําโพงที่จะใช้ 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

ระบุว่าจะใส่ความคิดเห็นในการตอบกลับหรือไม่ หากเป็น "จริง" ระบบจะแสดงผลคําแนะนําเมื่อมีให้เท่านั้น

thinkingBudget integer

จำนวนโทเค็นความคิดที่โมเดลควรสร้าง

การแสดง JSON
{
  "includeThoughts": boolean,
  "thinkingBudget": integer
}

MediaResolution

ความละเอียดของสื่อสำหรับสื่ออินพุต

Enum
MEDIA_RESOLUTION_UNSPECIFIED ยังไม่ได้ตั้งค่าความละเอียดของสื่อ
MEDIA_RESOLUTION_LOW ความละเอียดของสื่อตั้งค่าเป็นต่ำ (โทเค็น 64 รายการ)
MEDIA_RESOLUTION_MEDIUM ความละเอียดของสื่อตั้งค่าเป็นปานกลาง (โทเค็น 256 รายการ)
MEDIA_RESOLUTION_HIGH ความละเอียดของสื่อตั้งค่าเป็นสูง (การจัดเฟรมแบบซูมด้วยโทเค็น 256 รายการ)

HarmCategory

หมวดหมู่ของการจัดประเภท

หมวดหมู่เหล่านี้ครอบคลุมอันตรายหลายประเภทที่นักพัฒนาแอปอาจต้องการปรับเปลี่ยน

Enum
HARM_CATEGORY_UNSPECIFIED ไม่ได้ระบุหมวดหมู่
HARM_CATEGORY_DEROGATORY PaLM - ความคิดเห็นเชิงลบหรือเป็นอันตรายซึ่งมุ่งเป้าไปที่ตัวตนและ/หรือแอตทริบิวต์ที่ได้รับการคุ้มครอง
HARM_CATEGORY_TOXICITY PaLM - เนื้อหาที่หยาบคาย ไม่สุภาพ หรือไม่เคารพ
HARM_CATEGORY_VIOLENCE PaLM - อธิบายสถานการณ์ที่แสดงภาพความรุนแรงต่อบุคคลหรือกลุ่มบุคคล หรือคำอธิบายทั่วไปเกี่ยวกับภาพเลือด
HARM_CATEGORY_SEXUAL PaLM - มีการอ้างอิงถึงกิจกรรมทางเพศหรือเนื้อหาลามกอื่นๆ
HARM_CATEGORY_MEDICAL PaLM - โปรโมตคำแนะนำทางการแพทย์ที่ไม่ได้ตรวจสอบ
HARM_CATEGORY_DANGEROUS PaLM - เนื้อหาที่เป็นอันตรายซึ่งส่งเสริม สนับสนุน หรือก่อให้เกิดการกระทําที่เป็นอันตราย
HARM_CATEGORY_HARASSMENT Gemini - เนื้อหาการคุกคาม
HARM_CATEGORY_HATE_SPEECH Gemini - วาจาสร้างความเกลียดชังและเนื้อหา
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini - เนื้อหาเกี่ยวกับเรื่องเพศอย่างโจ่งแจ้ง
HARM_CATEGORY_DANGEROUS_CONTENT Gemini - เนื้อหาที่เป็นอันตราย
HARM_CATEGORY_CIVIC_INTEGRITY Gemini - เนื้อหาที่อาจนำไปใช้เพื่อทำลายความสุจริตของพลเมือง

ModalityTokenCount

แสดงข้อมูลการนับโทเค็นสําหรับสื่อเดียว

ฟิลด์
modality enum (Modality)

รูปแบบที่เชื่อมโยงกับจํานวนโทเค็นนี้

tokenCount integer

จํานวนโทเค็น

การแสดง JSON
{
  "modality": enum (Modality),
  "tokenCount": integer
}

รูปแบบ

รูปแบบของเนื้อหาบางส่วน

Enum
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

ความน่าจะเป็นที่เนื้อหาจะเป็นอันตราย

ระบบการจัดประเภทจะระบุความน่าจะเป็นที่เนื้อหาจะไม่ปลอดภัย ซึ่งไม่ได้บ่งบอกถึงความรุนแรงของอันตรายในเนื้อหา

Enum
HARM_PROBABILITY_UNSPECIFIED ไม่ได้ระบุความน่าจะเป็น
NEGLIGIBLE เนื้อหามีความเสี่ยงต่ำที่จะไม่ปลอดภัย
LOW เนื้อหามีโอกาสไม่ปลอดภัยต่ำ
MEDIUM เนื้อหามีความเสี่ยงปานกลางที่จะไม่ปลอดภัย
HIGH เนื้อหามีแนวโน้มที่จะไม่ปลอดภัยสูง

SafetySetting

การตั้งค่าความปลอดภัยที่ส่งผลต่อลักษณะการบล็อกเพื่อความปลอดภัย

การส่งการตั้งค่าความปลอดภัยสำหรับหมวดหมู่หนึ่งๆ จะเปลี่ยนความน่าจะเป็นที่อนุญาตในการบล็อกเนื้อหา

ฟิลด์
category enum (HarmCategory)

ต้องระบุ หมวดหมู่สําหรับการตั้งค่านี้

threshold enum (HarmBlockThreshold)

ต้องระบุ ควบคุมเกณฑ์ความน่าจะเป็นที่ระบบจะบล็อกเนื้อหาที่เป็นอันตราย

การแสดง JSON
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

HarmBlockThreshold

บล็อกเมื่อมีโอกาสเกิดอันตรายที่ระบุไว้และสูงกว่า

Enum
HARM_BLOCK_THRESHOLD_UNSPECIFIED ไม่ได้ระบุเกณฑ์
BLOCK_LOW_AND_ABOVE เนื้อหาที่มีค่า NEGLIGIBLE จะได้รับการอนุญาต
BLOCK_MEDIUM_AND_ABOVE เนื้อหาที่มีระดับ "ไม่มีนัยสำคัญ" และ "ต่ำ" จะได้รับการอนุญาต
BLOCK_ONLY_HIGH เนื้อหาที่มีระดับ "ไม่มีนัยสำคัญ" "ต่ำ" และ "ปานกลาง" จะได้รับการอนุญาต
BLOCK_NONE อนุญาตเนื้อหาทั้งหมด
OFF ปิดตัวกรองความปลอดภัย