Tuning

การรองรับการปรับแต่ง Gemini API จะมีกลไกในการดูแลเอาต์พุตเมื่อคุณมีชุดข้อมูลตัวอย่างอินพุต/เอาต์พุตขนาดเล็ก ดูรายละเอียดเพิ่มเติมได้ที่คู่มือการปรับแต่งโมเดลและบทแนะนำ

เมธอด: tunedModels.create

สร้างโมเดลที่ปรับแต่งแล้ว ตรวจสอบความคืบหน้าในการปรับแต่งระดับกลาง (หากมี) ผ่านgoogle.longrunning.Operationsบริการ

เข้าถึงสถานะและผลลัพธ์ผ่านบริการการดำเนินการ ตัวอย่าง: GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222

ปลายทาง

post https://generativelanguage.googleapis.com/v1beta/tunedModels

พารามิเตอร์การค้นหา

tunedModelId string

ไม่บังคับ รหัสที่ไม่ซ้ำกันสำหรับโมเดลที่ปรับแต่งแล้ว หากระบุ ค่านี้ควรมีอักขระไม่เกิน 40 ตัว โดยอักขระตัวแรกต้องเป็นตัวอักษร และอักขระตัวสุดท้ายอาจเป็นตัวอักษรหรือตัวเลข รหัสต้องตรงกับนิพจน์ทั่วไป [a-z]([a-z0-9-]{0,38}[a-z0-9])?

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

เนื้อความของคำขอมีอินสแตนซ์ของ TunedModel

ฟิลด์
displayName string

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

description string

ไม่บังคับ คำอธิบายสั้นๆ ของโมเดลนี้

tuningTask object (TuningTask)

ต้องระบุ งานการปรับแต่งที่สร้างโมเดลที่ปรับแต่งแล้ว

readerProjectNumbers[] string (int64 format)

ไม่บังคับ รายการหมายเลขโปรเจ็กต์ที่มีสิทธิ์เข้าถึงแบบอ่านสำหรับโมเดลที่ปรับแต่งแล้ว

source_model Union type
โมเดลที่ใช้เป็นจุดเริ่มต้นสำหรับการปรับแต่ง source_model ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
tunedModelSource object (TunedModelSource)

ไม่บังคับ TunedModel เพื่อใช้เป็นจุดเริ่มต้นในการฝึกโมเดลใหม่

baseModel string

เปลี่ยนแปลงไม่ได้ ชื่อของ Model ที่จะปรับ ตัวอย่าง: models/gemini-1.5-flash-001

temperature number

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

ค่าที่ใช้ได้อยู่ในช่วง [0.0,1.0] ค่าที่ใกล้เคียงกับ 1.0 จะสร้างคำตอบที่หลากหลายมากขึ้น ในขณะที่ค่าที่ใกล้เคียงกับ 0.0 โดยทั่วไปจะทำให้โมเดลสร้างคำตอบที่น่าประหลาดใจน้อยลง

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

topP number

ไม่บังคับ สำหรับการสุ่มตัวอย่าง Nucleus

การสุ่มตัวอย่างนิวเคลียสจะพิจารณาชุดโทเค็นที่เล็กที่สุดซึ่งมีผลรวมความน่าจะเป็นอย่างน้อย topP

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

topK integer

ไม่บังคับ สำหรับการสุ่มตัวอย่าง Top-k

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

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

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

Python

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

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

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

เมธอด: tunedModels.generateContent

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

ปลายทาง

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

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

model string

ต้องระบุ ชื่อของ Model ที่จะใช้ในการสร้างข้อความเติม

รูปแบบ: models/{model} ซึ่งจะอยู่ในรูปแบบ tunedModels/{tunedmodel}

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

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

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

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

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

tools[] object (Tool)

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

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

toolConfig object (ToolConfig)

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

safetySettings[] object (SafetySetting)

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

โดยจะมีผลบังคับใช้ในวันที่ GenerateContentRequest.contents และ GenerateContentResponse.candidates ไม่ควรมีการตั้งค่ามากกว่า 1 รายการสำหรับSafetyCategoryแต่ละประเภท 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}

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

ข้อความ

Python

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)

Node.js

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

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

Go

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

Java

// 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);

รูปภาพ

Python

from google import genai
import PIL.Image

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

Node.js

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

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

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

Go

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

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

response, err := client.Models.GenerateContent(ctx, "gemini-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

Java

// 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);

เสียง

Python

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)

Node.js

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

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

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

Go

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

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

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

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

response, err := client.Models.GenerateContent(ctx, "gemini-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 "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

วิดีโอ

Python

from google import genai
import time

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

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

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

Node.js

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

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

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

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

Go

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

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

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

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

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

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

response, err := client.Models.GenerateContent(ctx, "gemini-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

PDF

Python

from google import genai

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

Go

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

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

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

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

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

เปลือกหอย

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

แชท

Python

from google import genai
from google.genai import types

client = genai.Client()
# Pass initial history using the "history" argument
chat = client.chats.create(
    model="gemini-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)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const chat = ai.chats.create({
  model: "gemini-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);

Go

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

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

chat, err := client.Chats.Create(ctx, "gemini-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"

Java

// 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);

แคช

Python

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)

Node.js

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

Go

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

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

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

โมเดลที่ปรับแต่งแล้ว

Python

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

โหมด JSON

Python

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

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

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

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
  model: "gemini-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);

Go

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

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

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

response, err := client.Models.GenerateContent(
	ctx,
	"gemini-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

Java

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

การรันโค้ด

Python

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)

Go

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

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

// Print the response.
printResponse(response)

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

Java

// 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);

การเรียกใช้ฟังก์ชัน

Python

from google import genai
from google.genai import types

client = genai.Client()

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

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

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

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

# Create a chat session; function calling (via tools) is enabled in the config.
chat = client.chats.create(
    model="gemini-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)

Go

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

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

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

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

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

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

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

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

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

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

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

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

printResponse(finalResponse)

Node.js

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

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

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

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

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

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

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

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

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

  // Step 1: Call generateContent with function calling enabled.
  const generateContentResponse = await ai.models.generateContent({
    model: "gemini-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'

Java

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

การกำหนดค่าการสร้าง

Python

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)

Node.js

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

const response = await ai.models.generateContent({
  model: "gemini-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);

Go

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

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

response, err := client.Models.GenerateContent(
	ctx,
	"gemini-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"

Java

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

การตั้งค่าความปลอดภัย

Python

from google import genai
from google.genai import types

client = genai.Client()
unsafe_prompt = (
    "I support Martians Soccer Club and I think Jupiterians Football Club sucks! "
    "Write a ironic phrase about them including expletives."
)
response = client.models.generate_content(
    model="gemini-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)

Node.js

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

  const response = await ai.models.generateContent({
    model: "gemini-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;
}

Go

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

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

config := &genai.GenerateContentConfig{
	SafetySettings: []*genai.SafetySetting{
		{
			Category:  "HARM_CATEGORY_HATE_SPEECH",
			Threshold: "BLOCK_MEDIUM_AND_ABOVE",
		},
		{
			Category:  "HARM_CATEGORY_HARASSMENT",
			Threshold: "BLOCK_ONLY_HIGH",
		},
	},
}
contents := []*genai.Content{
	genai.NewContentFromText(unsafePrompt, genai.RoleUser),
}
response, err := client.Models.GenerateContent(ctx, "gemini-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

Java

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

คำสั่งของระบบ

Python

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)

Node.js

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

Go

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

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

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

response, err := client.Models.GenerateContent(ctx, "gemini-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"}}}'

Java

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

เมธอด: tunedModels.streamGenerateContent

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

ปลายทาง

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

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

model string

ต้องระบุ ชื่อของ Model ที่จะใช้ในการสร้างข้อความเติม

รูปแบบ: models/{model} ซึ่งจะอยู่ในรูปแบบ tunedModels/{tunedmodel}

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

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

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

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

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

tools[] object (Tool)

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

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

toolConfig object (ToolConfig)

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

safetySettings[] object (SafetySetting)

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

โดยจะมีผลบังคับใช้ในวันที่ GenerateContentRequest.contents และ GenerateContentResponse.candidates ไม่ควรมีการตั้งค่ามากกว่า 1 รายการสำหรับSafetyCategoryแต่ละประเภท 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}

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

ข้อความ

Python

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)

Node.js

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

const response = await ai.models.generateContentStream({
  model: "gemini-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;
}

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
contents := []*genai.Content{
	genai.NewContentFromText("Write a story about a magic backpack.", genai.RoleUser),
}
for response, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-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."}]}]}'

Java

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

รูปภาพ

Python

from google import genai
import PIL.Image

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

Node.js

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

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

const response = await ai.models.generateContentStream({
  model: "gemini-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;
}

Go

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

Java

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

Go

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

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

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

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

for result, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-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 "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

วิดีโอ

Python

from google import genai
import time

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

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

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

Node.js

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

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

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

const response = await ai.models.generateContentStream({
  model: "gemini-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;
}

Go

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

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

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

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

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

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

for result, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-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

PDF

Python

from google import genai

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

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

Go

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

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

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

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

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

เปลือกหอย

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

แชท

Python

from google import genai
from google.genai import types

client = genai.Client()
chat = client.chats.create(
    model="gemini-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())

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const chat = ai.chats.create({
  model: "gemini-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());

Go

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

history := []*genai.Content{
	genai.NewContentFromText("Hello", genai.RoleUser),
	genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),
}
chat, err := client.Chats.Create(ctx, "gemini-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"

Java

// 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

เมธอด: tunedModels.get

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

ปลายทาง

get https://generativelanguage.googleapis.com/v1beta/{name=tunedModels/*}

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

name string

ต้องระบุ ชื่อทรัพยากรของโมเดล

รูปแบบ: tunedModels/my-model-id มีรูปแบบเป็น tunedModels/{tunedmodel}

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

เนื้อหาของคำขอต้องว่างเปล่า

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

Python

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

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

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

เมธอด: tunedModels.list

แสดงรายการโมเดลที่ปรับแต่งแล้ว

ปลายทาง

get https://generativelanguage.googleapis.com/v1beta/tunedModels

พารามิเตอร์การค้นหา

pageSize integer

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

หากไม่ระบุ ระบบจะแสดงผลโมเดลที่ปรับแต่งแล้วอย่างน้อย 10 รายการ วิธีนี้จะแสดงโมเดลสูงสุด 1, 000 รายการต่อหน้า แม้ว่าคุณจะส่ง pageSize ที่ใหญ่กว่าก็ตาม

pageToken string

ไม่บังคับ โทเค็นหน้าเว็บที่ได้รับจากการเรียกใช้ tunedModels.list ก่อนหน้า

ระบุ pageToken ที่ส่งคืนโดยคำขอหนึ่งเป็นอาร์กิวเมนต์ของคำขอถัดไปเพื่อดึงข้อมูลหน้าถัดไป

เมื่อแบ่งหน้า พารามิเตอร์อื่นๆ ทั้งหมดที่ระบุให้กับ tunedModels.list ต้องตรงกับการเรียกที่ระบุโทเค็นหน้าเว็บ

filter string

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

โอเปอเรเตอร์เพิ่มเติม - owner:me - writers:me - readers:me - readers:everyone

ตัวอย่าง: "owner:me" จะแสดงโมเดลที่ปรับแต่งแล้วทั้งหมดที่ผู้โทรมีบทบาทเจ้าของ "readers:me" จะแสดงโมเดลที่ปรับแต่งแล้วทั้งหมดที่ผู้โทรมีบทบาทผู้อ่าน "readers:everyone" จะแสดงโมเดลที่ปรับแต่งแล้วทั้งหมดที่แชร์กับทุกคน

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

เนื้อหาของคำขอต้องว่างเปล่า

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

Python

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

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

การตอบกลับจาก tunedModels.list ที่มีรายการโมเดลแบบแบ่งหน้า

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีข้อมูลซึ่งมีโครงสร้างดังต่อไปนี้

ฟิลด์
tunedModels[] object (TunedModel)

โมเดลที่ส่งคืน

nextPageToken string

โทเค็นซึ่งส่งเป็น pageToken เพื่อเรียกข้อมูลหน้าถัดไปได้

หากไม่ระบุฟิลด์นี้ แสดงว่าไม่มีหน้าอื่นอีก

การแสดง JSON
{
  "tunedModels": [
    {
      object (TunedModel)
    }
  ],
  "nextPageToken": string
}

เมธอด: tunedModels.patch

อัปเดตโมเดลที่ปรับแต่งแล้ว

ปลายทาง

patch https://generativelanguage.googleapis.com/v1beta/{tunedModel.name=tunedModels/*}

PATCH https://generativelanguage.googleapis.com/v1beta/{tunedModel.name=tunedModels/*}

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

tunedModel.name string

เอาต์พุตเท่านั้น ชื่อโมเดลที่ปรับ ระบบจะสร้างชื่อที่ไม่ซ้ำกันเมื่อสร้าง ตัวอย่าง: tunedModels/az2mb0bpw6i หากตั้งค่า displayName เมื่อสร้าง ระบบจะตั้งค่าส่วนรหัสของชื่อโดยการต่อคำของ displayName ด้วยเครื่องหมายขีดกลางและเพิ่มส่วนแบบสุ่มเพื่อให้ไม่ซ้ำกัน

ตัวอย่าง

  • displayName = Sentence Translator
  • name = tunedModels/sentence-translator-u3b7m มีรูปแบบเป็น tunedModels/{tunedmodel}

พารามิเตอร์การค้นหา

updateMask string (FieldMask format)

ไม่บังคับ รายการช่องที่จะอัปเดต

ซึ่งเป็นรายการชื่อฟิลด์แบบสมบูรณ์ในตัวเองที่คั่นด้วยคอมมา ตัวอย่าง: "user.displayName,photo"

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

เนื้อความของคำขอมีอินสแตนซ์ของ TunedModel

ฟิลด์
displayName string

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

description string

ไม่บังคับ คำอธิบายสั้นๆ ของโมเดลนี้

tuningTask object (TuningTask)

ต้องระบุ งานการปรับแต่งที่สร้างโมเดลที่ปรับแต่งแล้ว

readerProjectNumbers[] string (int64 format)

ไม่บังคับ รายการหมายเลขโปรเจ็กต์ที่มีสิทธิ์เข้าถึงแบบอ่านสำหรับโมเดลที่ปรับแต่งแล้ว

source_model Union type
โมเดลที่ใช้เป็นจุดเริ่มต้นสำหรับการปรับแต่ง source_model ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
tunedModelSource object (TunedModelSource)

ไม่บังคับ TunedModel เพื่อใช้เป็นจุดเริ่มต้นในการฝึกโมเดลใหม่

temperature number

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

ค่าที่ใช้ได้อยู่ในช่วง [0.0,1.0] ค่าที่ใกล้เคียงกับ 1.0 จะสร้างคำตอบที่หลากหลายมากขึ้น ในขณะที่ค่าที่ใกล้เคียงกับ 0.0 โดยทั่วไปจะทำให้โมเดลสร้างคำตอบที่น่าประหลาดใจน้อยลง

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

topP number

ไม่บังคับ สำหรับการสุ่มตัวอย่าง Nucleus

การสุ่มตัวอย่างนิวเคลียสจะพิจารณาชุดโทเค็นที่เล็กที่สุดซึ่งมีผลรวมความน่าจะเป็นอย่างน้อย topP

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

topK integer

ไม่บังคับ สำหรับการสุ่มตัวอย่าง Top-k

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

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

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

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

วิธีการ: tunedModels.delete

ลบโมเดลที่ปรับแต่งแล้ว

ปลายทาง

ลบ https://generativelanguage.googleapis.com/v1beta/{name=tunedModels/*}

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

name string

ต้องระบุ ชื่อทรัพยากรของโมเดล รูปแบบ: tunedModels/my-model-id มีรูปแบบเป็น tunedModels/{tunedmodel}

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

เนื้อหาของคำขอต้องว่างเปล่า

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

หากทำสำเร็จ เนื้อหาการตอบกลับจะเป็นออบเจ็กต์ JSON ที่ว่างเปล่า

ทรัพยากร REST: tunedModels

ทรัพยากร: TunedModel

โมเดลที่ปรับแต่งแล้วซึ่งสร้างขึ้นโดยใช้ ModelService.CreateTunedModel

ฟิลด์
name string

เอาต์พุตเท่านั้น ชื่อโมเดลที่ปรับ ระบบจะสร้างชื่อที่ไม่ซ้ำกันเมื่อสร้าง ตัวอย่าง: tunedModels/az2mb0bpw6i หากตั้งค่า displayName เมื่อสร้าง ระบบจะตั้งค่าส่วนรหัสของชื่อโดยการต่อคำของ displayName ด้วยเครื่องหมายขีดกลางและเพิ่มส่วนแบบสุ่มเพื่อให้ไม่ซ้ำกัน

ตัวอย่าง

  • displayName = Sentence Translator
  • name = tunedModels/sentence-translator-u3b7m
displayName string

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

description string

ไม่บังคับ คำอธิบายสั้นๆ ของโมเดลนี้

state enum (State)

เอาต์พุตเท่านั้น สถานะของโมเดลที่ปรับแต่งแล้ว

createTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่อสร้างโมเดลนี้

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย ตัวอย่าง: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

updateTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่อมีการอัปเดตรูปแบบนี้

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย ตัวอย่าง: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

tuningTask object (TuningTask)

ต้องระบุ งานการปรับแต่งที่สร้างโมเดลที่ปรับแต่งแล้ว

readerProjectNumbers[] string (int64 format)

ไม่บังคับ รายการหมายเลขโปรเจ็กต์ที่มีสิทธิ์เข้าถึงแบบอ่านสำหรับโมเดลที่ปรับแต่งแล้ว

source_model Union type
โมเดลที่ใช้เป็นจุดเริ่มต้นสำหรับการปรับแต่ง source_model ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
tunedModelSource object (TunedModelSource)

ไม่บังคับ TunedModel เพื่อใช้เป็นจุดเริ่มต้นในการฝึกโมเดลใหม่

baseModel string

เปลี่ยนแปลงไม่ได้ ชื่อของ Model ที่จะปรับ ตัวอย่าง: models/gemini-1.5-flash-001

temperature number

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

ค่าที่ใช้ได้อยู่ในช่วง [0.0,1.0] ค่าที่ใกล้เคียงกับ 1.0 จะสร้างคำตอบที่หลากหลายมากขึ้น ในขณะที่ค่าที่ใกล้เคียงกับ 0.0 โดยทั่วไปจะทำให้โมเดลสร้างคำตอบที่น่าประหลาดใจน้อยลง

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

topP number

ไม่บังคับ สำหรับการสุ่มตัวอย่าง Nucleus

การสุ่มตัวอย่างนิวเคลียสจะพิจารณาชุดโทเค็นที่เล็กที่สุดซึ่งมีผลรวมความน่าจะเป็นอย่างน้อย topP

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

topK integer

ไม่บังคับ สำหรับการสุ่มตัวอย่าง Top-k

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

ค่านี้จะระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลพื้นฐานใช้ขณะสร้างโมเดล

การแสดง JSON
{
  "name": string,
  "displayName": string,
  "description": string,
  "state": enum (State),
  "createTime": string,
  "updateTime": string,
  "tuningTask": {
    object (TuningTask)
  },
  "readerProjectNumbers": [
    string
  ],

  // source_model
  "tunedModelSource": {
    object (TunedModelSource)
  },
  "baseModel": string
  // Union type
  "temperature": number,
  "topP": number,
  "topK": integer
}

TunedModelSource

โมเดลที่ปรับแต่งแล้วเป็นแหล่งที่มาสำหรับการฝึกโมเดลใหม่

ฟิลด์
tunedModel string

เปลี่ยนแปลงไม่ได้ ชื่อของ TunedModel ที่จะใช้เป็นจุดเริ่มต้นในการฝึกโมเดลใหม่ ตัวอย่าง: tunedModels/my-tuned-model

baseModel string

เอาต์พุตเท่านั้น ชื่อของโมเดลพื้นฐานที่ใช้ปรับแต่งโมเดลนี้ModelTunedModel ตัวอย่าง: models/gemini-1.5-flash-001

การแสดง JSON
{
  "tunedModel": string,
  "baseModel": string
}

รัฐ

สถานะของโมเดลที่ปรับแต่งแล้ว

Enum
STATE_UNSPECIFIED ค่าเริ่มต้น ค่านี้ไม่ได้ใช้
CREATING กำลังสร้างโมเดล
ACTIVE โมเดลพร้อมใช้งานแล้ว
FAILED สร้างโมเดลไม่สำเร็จ

TuningTask

งานการปรับแต่งที่สร้างโมเดลที่ปรับแต่งแล้ว

ฟิลด์
startTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่อเริ่มปรับแต่งโมเดลนี้

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย ตัวอย่าง: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

completeTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่อการปรับแต่งโมเดลนี้เสร็จสมบูรณ์

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย ตัวอย่าง: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

snapshots[] object (TuningSnapshot)

เอาต์พุตเท่านั้น เมตริกที่รวบรวมระหว่างการปรับ

trainingData object (Dataset)

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

hyperparameters object (Hyperparameters)

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

การแสดง JSON
{
  "startTime": string,
  "completeTime": string,
  "snapshots": [
    {
      object (TuningSnapshot)
    }
  ],
  "trainingData": {
    object (Dataset)
  },
  "hyperparameters": {
    object (Hyperparameters)
  }
}

TuningSnapshot

บันทึกสำหรับการปรับแต่งเพียงขั้นตอนเดียว

ฟิลด์
step integer

เอาต์พุตเท่านั้น ขั้นตอนการปรับ

epoch integer

เอาต์พุตเท่านั้น Epoch ที่ขั้นตอนนี้เป็นส่วนหนึ่ง

meanLoss number

เอาต์พุตเท่านั้น การสูญเสียเฉลี่ยของตัวอย่างการฝึกสำหรับขั้นตอนนี้

computeTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่อมีการคำนวณเมตริกนี้

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย ตัวอย่าง: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

การแสดง JSON
{
  "step": integer,
  "epoch": integer,
  "meanLoss": number,
  "computeTime": string
}

ชุดข้อมูล

ชุดข้อมูลสำหรับการฝึกหรือการตรวจสอบ

ฟิลด์
dataset Union type
ข้อมูลในบรรทัดหรือการอ้างอิงถึงข้อมูล dataset ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
examples object (TuningExamples)

ไม่บังคับ ตัวอย่างในบรรทัดที่มีข้อความอินพุต/เอาต์พุตอย่างง่าย

การแสดง JSON
{

  // dataset
  "examples": {
    object (TuningExamples)
  }
  // Union type
}

TuningExamples

ชุดตัวอย่างการปรับ อาจเป็นข้อมูลการฝึกหรือการตรวจสอบ

ฟิลด์
examples[] object (TuningExample)

ตัวอย่าง อินพุตตัวอย่างอาจเป็นข้อความหรือการสนทนา แต่ตัวอย่างทั้งหมดในชุดต้องเป็นประเภทเดียวกัน

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

TuningExample

ตัวอย่างเดียวสำหรับการปรับ

ฟิลด์
output string

ต้องระบุ เอาต์พุตโมเดลที่คาดไว้

model_input Union type
อินพุตของโมเดลสำหรับตัวอย่างนี้ model_input ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
textInput string

ไม่บังคับ อินพุตโมเดลข้อความ

การแสดง JSON
{
  "output": string,

  // model_input
  "textInput": string
  // Union type
}

ไฮเปอร์พารามิเตอร์

ไฮเปอร์พารามิเตอร์ที่ควบคุมกระบวนการปรับแต่ง อ่านเพิ่มเติมได้ที่ https://ai.google.dev/docs/model_tuning_guidance

ฟิลด์
learning_rate_option Union type
ตัวเลือกสำหรับการระบุอัตราการเรียนรู้ระหว่างการปรับ learning_rate_option ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
learningRate number

ไม่บังคับ เปลี่ยนแปลงไม่ได้ ไฮเปอร์พารามิเตอร์อัตราการเรียนรู้สำหรับการปรับแต่ง หากไม่ได้ตั้งค่า ระบบจะคำนวณค่าเริ่มต้นเป็น 0.001 หรือ 0.0002 โดยอิงตามจำนวนตัวอย่างการฝึก

learningRateMultiplier number

ไม่บังคับ เปลี่ยนแปลงไม่ได้ ตัวคูณอัตราการเรียนรู้ใช้ในการคำนวณ learningRate สุดท้ายตามค่าเริ่มต้น (แนะนำ) อัตราการเรียนรู้จริง := learningRateMultiplier * อัตราการเรียนรู้เริ่มต้น อัตราการเรียนรู้เริ่มต้นขึ้นอยู่กับโมเดลพื้นฐานและขนาดชุดข้อมูล หากไม่ได้ตั้งค่า ระบบจะใช้ค่าเริ่มต้นเป็น 1.0

epochCount integer

เปลี่ยนแปลงไม่ได้ จำนวน Epoch การฝึก Epoch คือการส่งผ่านข้อมูลการฝึก 1 ครั้ง หากไม่ได้ตั้งค่า ระบบจะใช้ค่าเริ่มต้นเป็น 5

batchSize integer

เปลี่ยนแปลงไม่ได้ ไฮเปอร์พารามิเตอร์ขนาดกลุ่มสำหรับการปรับแต่ง หากไม่ได้ตั้งค่า ระบบจะใช้ค่าเริ่มต้นเป็น 4 หรือ 16 โดยอิงตามจำนวนตัวอย่างการฝึก

การแสดง JSON
{

  // learning_rate_option
  "learningRate": number,
  "learningRateMultiplier": number
  // Union type
  "epochCount": integer,
  "batchSize": integer
}