Generating content

Gemini API; resim, ses, kod ve araçlarla içerik oluşturmayı destekler. Bu özelliklerin her biriyle ilgili ayrıntılar için okumaya devam edin ve göreve odaklanmış örnek kodu inceleyin veya kapsamlı kılavuzları okuyun.

Yöntem: models.generateContent

GenerateContentRequest girişi verildiğinde model yanıtı oluşturur. Ayrıntılı kullanım bilgileri için metin oluşturma kılavuzuna bakın. Giriş özellikleri, ince ayarlı modeller de dahil olmak üzere modeller arasında farklılık gösterir. Ayrıntılar için model kılavuzuna ve ayarlama kılavuzuna bakın.

Uç nokta

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

Yol parametreleri

model string

Zorunlu. Tamamlama oluşturmak için kullanılacak Model öğesinin adı.

Biçim: models/{model}. models/{model} biçimindedir.

İstek içeriği

İstek metni aşağıdaki yapıyla birlikte verileri içerir:

Alanlar
contents[] object (Content)

Zorunlu. Modelle yapılan mevcut görüşmenin içeriği.

Tek dönüşlü sorgular için bu tek bir örnektir. Chat gibi çok turlu sorgular için bu, sohbet geçmişini ve son isteği içeren yinelenen bir alandır.

tools[] object (Tool)

İsteğe bağlı. Bir sonraki yanıtı oluşturmak için Tools kullanılabilecek Model listesi.

Tool, sistemin Model'nin bilgisi ve kapsamı dışında bir işlem veya işlemler dizisi gerçekleştirmek için harici sistemlerle etkileşime girmesini sağlayan bir kod parçasıdır. Desteklenen Tool'ler Function ve codeExecution'dir. Daha fazla bilgi edinmek için İşlev çağırma ve Kod yürütme kılavuzlarına bakın.

toolConfig object (ToolConfig)

İsteğe bağlı. İstek içinde belirtilen herhangi bir Tool için araç yapılandırması. Kullanım örneği için İşlev çağırma kılavuzuna bakın.

safetySettings[] object (SafetySetting)

İsteğe bağlı. Güvenli olmayan içeriğin engellenmesi için benzersiz SafetySetting örneklerinin listesi.

Bu kısıtlama GenerateContentRequest.contents ve GenerateContentResponse.candidates üzerinde uygulanacak. Her SafetyCategory türü için birden fazla ayar olmamalıdır. API, bu ayarlarda belirlenen eşikleri karşılamayan tüm içerikleri ve yanıtları engeller. Bu liste, safetySettings içinde belirtilen her SafetyCategory için varsayılan ayarları geçersiz kılar. Listede belirtilen belirli bir SafetyCategory için SafetySetting yoksa API, bu kategori için varsayılan güvenlik ayarını kullanır. HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY zarar kategorileri desteklenir. Kullanılabilir güvenlik ayarları hakkında ayrıntılı bilgi için kılavuza bakın. Ayrıca, yapay zeka uygulamalarınıza güvenlikle ilgili hususları nasıl dahil edeceğinizi öğrenmek için Güvenlik rehberine de göz atın.

systemInstruction object (Content)

İsteğe bağlı. Geliştirici tarafından belirlenen sistem talimatları. Şu anda yalnızca metin.

generationConfig object (GenerationConfig)

İsteğe bağlı. Model oluşturma ve çıkışlarla ilgili yapılandırma seçenekleri.

cachedContent string

İsteğe bağlı. Tahmini sunmak için bağlam olarak kullanılacak önbelleğe alınan içeriğin adı. Biçim: cachedContents/{cachedContent}

Örnek istek

Metin

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)

kabuk

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

Java

Client client = new Client();

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

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

Resim

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)

kabuk

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

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

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

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

Java

Client client = new Client();

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

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

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

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

Ses

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)

kabuk

# 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

Video

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)

kabuk

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

kabuk

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

Sohbet

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

kabuk

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

Java

Client client = new Client();

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

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

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

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

Önbellek

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)

Tuned Model

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 Modu

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)

kabuk

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

Java

Client client = new Client();

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

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

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

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

Kod yürütme

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

Client client = new Client();

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

GenerateContentResponse response =
        client.models.generateContent(
                "gemini-2.0-pro-exp-02-05",
                prompt,
                null);

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

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

İşlev Çağırma

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

kabuk


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

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

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

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

Java

Client client = new Client();

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

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

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

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

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

                )
        )
        .build();

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


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

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

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

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

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

System.out.println(result);

Oluşturma yapılandırması

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)

kabuk

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

Java

Client client = new Client();

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

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

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

Güvenlik ayarları

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

kabuk

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

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

Java

Client client = new Client();

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

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

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

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

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

Sistem Talimatı

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)

kabuk

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

Java

Client client = new Client();

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

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

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

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

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

Yanıt gövdesi

Başarılıysa yanıt metni, GenerateContentResponse öğesinin bir örneğini içerir.

Yöntem: models.streamGenerateContent

GenerateContentRequest girişi verildiğinde modelden yayın yanıtı oluşturur.

Uç nokta

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

Yol parametreleri

model string

Zorunlu. Tamamlama oluşturmak için kullanılacak Model öğesinin adı.

Biçim: models/{model}. models/{model} biçimindedir.

İstek içeriği

İstek metni aşağıdaki yapıyla birlikte verileri içerir:

Alanlar
contents[] object (Content)

Zorunlu. Modelle yapılan mevcut görüşmenin içeriği.

Tek dönüşlü sorgular için bu tek bir örnektir. Chat gibi çok turlu sorgular için bu, sohbet geçmişini ve son isteği içeren yinelenen bir alandır.

tools[] object (Tool)

İsteğe bağlı. Bir sonraki yanıtı oluşturmak için Tools kullanılabilecek Model listesi.

Tool, sistemin Model'nin bilgisi ve kapsamı dışında bir işlem veya işlemler dizisi gerçekleştirmek için harici sistemlerle etkileşime girmesini sağlayan bir kod parçasıdır. Desteklenen Tool'ler Function ve codeExecution'dir. Daha fazla bilgi edinmek için İşlev çağırma ve Kod yürütme kılavuzlarına bakın.

toolConfig object (ToolConfig)

İsteğe bağlı. İstek içinde belirtilen herhangi bir Tool için araç yapılandırması. Kullanım örneği için İşlev çağırma kılavuzuna bakın.

safetySettings[] object (SafetySetting)

İsteğe bağlı. Güvenli olmayan içeriğin engellenmesi için benzersiz SafetySetting örneklerinin listesi.

Bu kısıtlama GenerateContentRequest.contents ve GenerateContentResponse.candidates üzerinde uygulanacak. Her SafetyCategory türü için birden fazla ayar olmamalıdır. API, bu ayarlarda belirlenen eşikleri karşılamayan tüm içerikleri ve yanıtları engeller. Bu liste, safetySettings içinde belirtilen her SafetyCategory için varsayılan ayarları geçersiz kılar. Listede belirtilen belirli bir SafetyCategory için SafetySetting yoksa API, bu kategori için varsayılan güvenlik ayarını kullanır. HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY zarar kategorileri desteklenir. Kullanılabilir güvenlik ayarları hakkında ayrıntılı bilgi için kılavuza bakın. Ayrıca, yapay zeka uygulamalarınıza güvenlikle ilgili hususları nasıl dahil edeceğinizi öğrenmek için Güvenlik rehberine de göz atın.

systemInstruction object (Content)

İsteğe bağlı. Geliştirici tarafından belirlenen sistem talimatları. Şu anda yalnızca metin.

generationConfig object (GenerationConfig)

İsteğe bağlı. Model oluşturma ve çıkışlarla ilgili yapılandırma seçenekleri.

cachedContent string

İsteğe bağlı. Tahmini sunmak için bağlam olarak kullanılacak önbelleğe alınan içeriğin adı. Biçim: cachedContents/{cachedContent}

Örnek istek

Metin

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

kabuk

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

Java

Client client = new Client();

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

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

responseStream.close();

Resim

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

kabuk

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

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

Java

Client client = new Client();

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

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


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

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

responseStream.close();

Ses

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

kabuk

# 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

Video

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

kabuk

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

kabuk

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

Sohbet

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

kabuk

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"

Yanıt gövdesi

Başarılı olursa yanıt gövdesi, GenerateContentResponse örneklerinin bir akışını içerir.

GenerateContentResponse

Birden fazla aday yanıtını destekleyen modelden gelen yanıt.

Güvenlik derecelendirmeleri ve içerik filtreleme, hem GenerateContentResponse.prompt_feedback içindeki istem hem de finishReason ve safetyRatings içindeki her aday için bildirilir. API: - İstenen adayların tümünü veya hiçbirini döndürür. - Yalnızca istemle ilgili bir sorun varsa hiç aday döndürmez (promptFeedback bölümüne bakın). - finishReason ve safetyRatings bölümlerinde her aday hakkında geri bildirim raporlar.

Alanlar
candidates[] object (Candidate)

Modelin aday yanıtları.

promptFeedback object (PromptFeedback)

İçerik filtreleriyle ilgili istem geri bildirimini döndürür.

usageMetadata object (UsageMetadata)

Yalnızca çıkış. Oluşturma isteklerinin jeton kullanımıyla ilgili meta veriler.

modelVersion string

Yalnızca çıkış. Yanıtı oluşturmak için kullanılan model sürümü.

responseId string

Yalnızca çıkış. responseId, her yanıtı tanımlamak için kullanılır.

JSON gösterimi
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string,
  "responseId": string
}

PromptFeedback

İstemde GenerateContentRequest.content içinde belirtilen geri bildirim meta verileri kümesi.

Alanlar
blockReason enum (BlockReason)

İsteğe bağlı. Ayarlandıysa istem engellenir ve aday döndürülmez. İstemi yeniden ifade edin.

safetyRatings[] object (SafetyRating)

İstem güvenliğiyle ilgili puanlar. Kategori başına en fazla bir puan verilebilir.

JSON gösterimi
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

BlockReason

İstemin neden engellendiğini belirtir.

Sıralamalar
BLOCK_REASON_UNSPECIFIED Varsayılan değer. Bu değer kullanılmıyor.
SAFETY İstem, güvenlikle ilgili nedenlerden dolayı engellendi. Hangi güvenlik kategorisinin engellediğini anlamak için safetyRatings simgesini inceleyin.
OTHER İstem, bilinmeyen nedenlerle engellendi.
BLOCKLIST İstem, terminoloji engelleme listesinde yer alan terimler nedeniyle engellendi.
PROHIBITED_CONTENT İstem, yasaklanmış içerik nedeniyle engellendi.
IMAGE_SAFETY Güvenli olmayan resim oluşturma içeriği nedeniyle adaylar engellendi.

UsageMetadata

Üretim isteğinin jeton kullanımıyla ilgili meta veriler.

Alanlar
promptTokenCount integer

İstemdeki jeton sayısı. cachedContent ayarlandığında bu değer, toplam etkili istem boyutu olmaya devam eder. Yani, önbelleğe alınan içerikteki jeton sayısını da içerir.

cachedContentTokenCount integer

İstemin önbelleğe alınan bölümündeki (önbelleğe alınan içerik) jeton sayısı

candidatesTokenCount integer

Oluşturulan tüm yanıt adaylarındaki toplam jeton sayısı.

toolUsePromptTokenCount integer

Yalnızca çıkış. Araç kullanma istemlerinde bulunan jeton sayısı.

thoughtsTokenCount integer

Yalnızca çıkış. Düşünme modelleri için düşünce jetonlarının sayısı.

totalTokenCount integer

Üretim isteğinin (istem + yanıt adayları) toplam jeton sayısı.

promptTokensDetails[] object (ModalityTokenCount)

Yalnızca çıkış. İstek girişinde işlenen yöntemlerin listesi.

cacheTokensDetails[] object (ModalityTokenCount)

Yalnızca çıkış. İstek girişindeki önbelleğe alınmış içeriğin biçimlerinin listesi.

candidatesTokensDetails[] object (ModalityTokenCount)

Yalnızca çıkış. Yanıtta döndürülen yöntemlerin listesi.

toolUsePromptTokensDetails[] object (ModalityTokenCount)

Yalnızca çıkış. Araç kullanımı isteği girişleri için işlenen yöntemlerin listesi.

JSON gösterimi
{
  "promptTokenCount": integer,
  "cachedContentTokenCount": integer,
  "candidatesTokenCount": integer,
  "toolUsePromptTokenCount": integer,
  "thoughtsTokenCount": integer,
  "totalTokenCount": integer,
  "promptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "cacheTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "candidatesTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "toolUsePromptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ]
}

Aday

Modelden oluşturulan yanıt adayı.

Alanlar
content object (Content)

Yalnızca çıkış. Modelden döndürülen oluşturulmuş içerik.

finishReason enum (FinishReason)

İsteğe bağlı. Yalnızca çıkış. Modelin jeton oluşturmayı durdurma nedeni.

Boşsa model, jeton oluşturmayı durdurmamıştır.

safetyRatings[] object (SafetyRating)

Yanıt adayının güvenliğiyle ilgili puanların listesi.

Kategori başına en fazla bir puan verilebilir.

citationMetadata object (CitationMetadata)

Yalnızca çıkış. Model tarafından oluşturulan aday için alıntı bilgileri.

Bu alan, content içinde yer alan tüm metinler için okuma bilgileriyle doldurulabilir. Bunlar, temel LLM'nin eğitim verilerindeki telif hakkıyla korunan materyallerden"alıntılanan" pasajlardır.

tokenCount integer

Yalnızca çıkış. Bu aday için jeton sayısı.

groundingAttributions[] object (GroundingAttribution)

Yalnızca çıkış. Dayanaklı bir yanıta katkıda bulunan kaynakların atıf bilgileri.

Bu alan, GenerateAnswer görüşmeleri için doldurulur.

groundingMetadata object (GroundingMetadata)

Yalnızca çıkış. Aday için temellendirme meta verileri.

Bu alan, GenerateContent görüşmeleri için doldurulur.

avgLogprobs number

Yalnızca çıkış. Adayın ortalama log olasılığı puanı.

logprobsResult object (LogprobsResult)

Yalnızca çıkış. Yanıt jetonları ve en iyi jetonlar için log-likelihood puanları

urlContextMetadata object (UrlContextMetadata)

Yalnızca çıkış. URL bağlamı alma aracıyla ilgili meta veriler.

index integer

Yalnızca çıkış. Yanıt adayları listesindeki adayın dizini.

JSON gösterimi
{
  "content": {
    object (Content)
  },
  "finishReason": enum (FinishReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ],
  "citationMetadata": {
    object (CitationMetadata)
  },
  "tokenCount": integer,
  "groundingAttributions": [
    {
      object (GroundingAttribution)
    }
  ],
  "groundingMetadata": {
    object (GroundingMetadata)
  },
  "avgLogprobs": number,
  "logprobsResult": {
    object (LogprobsResult)
  },
  "urlContextMetadata": {
    object (UrlContextMetadata)
  },
  "index": integer
}

FinishReason

Modelin jeton oluşturmayı durdurma nedenini tanımlar.

Sıralamalar
FINISH_REASON_UNSPECIFIED Varsayılan değer. Bu değer kullanılmıyor.
STOP Modelin doğal durdurma noktası veya sağlanan durdurma sırası.
MAX_TOKENS İstekle belirtilen maksimum jeton sayısına ulaşıldı.
SAFETY Yanıt adayı içeriği, güvenlik nedeniyle işaretlendi.
RECITATION Yanıt adayı içeriği, okuma nedenleriyle işaretlendi.
LANGUAGE Yanıt adayı içeriği, desteklenmeyen bir dil kullanıldığı için işaretlendi.
OTHER Bilinmeyen neden.
BLOCKLIST İçerikte yasaklanmış terimler bulunduğundan jeton oluşturma işlemi durduruldu.
PROHIBITED_CONTENT Yasaklanmış içerik barındırabileceği için jeton oluşturma işlemi durduruldu.
SPII İçerik, hassas kimliği tanımlayabilecek bilgiler (SPII) içerebileceğinden jeton oluşturma işlemi durduruldu.
MALFORMED_FUNCTION_CALL Model tarafından oluşturulan işlev çağrısı geçersiz.
IMAGE_SAFETY Oluşturulan resimlerde güvenlik ihlalleri olduğu için jeton oluşturma işlemi durduruldu.
UNEXPECTED_TOOL_CALL Model, bir araç çağrısı oluşturdu ancak istekte hiçbir araç etkinleştirilmedi.
TOO_MANY_TOOL_CALLS Model, çok fazla aracı art arda çağırdığı için sistem yürütmeden çıktı.

GroundingAttribution

Bir yanıta katkıda bulunan kaynağın atfı.

Alanlar
sourceId object (AttributionSourceId)

Yalnızca çıkış. Bu ilişkilendirmeye katkıda bulunan kaynağın tanımlayıcısı.

content object (Content)

Bu ilişkilendirmeyi oluşturan temel kaynak içerik.

JSON gösterimi
{
  "sourceId": {
    object (AttributionSourceId)
  },
  "content": {
    object (Content)
  }
}

AttributionSourceId

Bu ilişkilendirmeye katkıda bulunan kaynağın tanımlayıcısı.

Alanlar
source Union type
source yalnızca aşağıdakilerden biri olabilir:
groundingPassage object (GroundingPassageId)

Satır içi pasajın tanımlayıcısı.

semanticRetrieverChunk object (SemanticRetrieverChunk)

Semantik Alıcı aracılığıyla Chunk alınan öğenin tanımlayıcısı.

JSON gösterimi
{

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

GroundingPassageId

GroundingPassage içindeki bir parçanın tanımlayıcısı.

Alanlar
passageId string

Yalnızca çıkış. GenerateAnswerRequest'nın GroundingPassage.id ile eşleşen geçiş kartının kimliği.

partIndex integer

Yalnızca çıkış. GenerateAnswerRequest'nın GroundingPassage.content içindeki bölümün dizini.

JSON gösterimi
{
  "passageId": string,
  "partIndex": integer
}

SemanticRetrieverChunk

Chunk için tanımlayıcı, SemanticRetrieverConfig kullanılarak GenerateAnswerRequest içinde belirtilen Semantik Alıcı aracılığıyla alınır.

Alanlar
source string

Yalnızca çıkış. İsteğin SemanticRetrieverConfig.source ile eşleşen kaynağın adı. Örnek: corpora/123 veya corpora/123/documents/abc

chunk string

Yalnızca çıkış. Atfedilen metni içeren Chunk öğesinin adı. Örnek: corpora/123/documents/abc/chunks/xyz

JSON gösterimi
{
  "source": string,
  "chunk": string
}

GroundingMetadata

Temellendirme etkinleştirildiğinde istemciye döndürülen meta veriler.

Alanlar
groundingChunks[] object (GroundingChunk)

Belirtilen temellendirme kaynağından alınan destekleyici referansların listesi.

groundingSupports[] object (GroundingSupport)

Temellendirme desteğinin listesi.

webSearchQueries[] string

Takip eden web araması için web arama sorguları.

searchEntryPoint object (SearchEntryPoint)

İsteğe bağlı. Takip eden web aramaları için Google arama girişi.

retrievalMetadata object (RetrievalMetadata)

Temellendirme akışında almayla ilgili meta veriler.

JSON gösterimi
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  }
}

SearchEntryPoint

Google arama giriş noktası.

Alanlar
renderedContent string

İsteğe bağlı. Bir web sayfasına veya uygulama web görünümüne yerleştirilebilen web içeriği snippet'i.

sdkBlob string (bytes format)

İsteğe bağlı. <Arama terimi, arama URL'si> demet dizisini temsil eden Base64 kodlu JSON.

Base64 kodlu bir dize.

JSON gösterimi
{
  "renderedContent": string,
  "sdkBlob": string
}

GroundingChunk

Temellendirme parçası.

Alanlar
chunk_type Union type
Parça türü. chunk_type yalnızca aşağıdakilerden biri olabilir:
web object (Web)

Web'den temellendirme parçası.

JSON gösterimi
{

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

Web

Web'den alınan bölüm.

Alanlar
uri string

Parçanın URI referansı.

title string

Parçanın başlığı.

JSON gösterimi
{
  "uri": string,
  "title": string
}

GroundingSupport

Temellendirme desteği.

Alanlar
groundingChunkIndices[] integer

Hak talebiyle ilişkili alıntıları belirten bir indeks listesi ("grounding_chunk" içinde). Örneğin, [1,3,4], grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] öğelerinin, iddiayla ilişkilendirilen alınan içerik olduğu anlamına gelir.

confidenceScores[] number

Destek referanslarının güven puanı. 0 ile 1 arasında değişir. 1 en güvenli seçenektir. Bu liste, groundingChunkIndices ile aynı boyutta olmalıdır.

segment object (Segment)

Bu desteğin ait olduğu içerik segmenti.

JSON gösterimi
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

Segment

İçeriğin segmenti.

Alanlar
partIndex integer

Yalnızca çıkış. Bir Part nesnesinin üst Content nesnesi içindeki dizini.

startIndex integer

Yalnızca çıkış. Verilen bölümdeki başlangıç dizini (bayt cinsinden). Parçanın başlangıcından itibaren (girilen tarihler dahil) sıfırdan başlayan uzaklık.

endIndex integer

Yalnızca çıkış. Belirtilen Bölüm'deki bayt cinsinden ölçülen bitiş dizini. Bölümün başlangıcından itibaren olan ve sıfırdan başlayan, hariç tutulan uzaklık.

text string

Yalnızca çıkış. Yanıttaki segmente karşılık gelen metin.

JSON gösterimi
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

RetrievalMetadata

Temellendirme akışında almayla ilgili meta veriler.

Alanlar
googleSearchDynamicRetrievalScore number

İsteğe bağlı. Google Arama'daki bilgilerin isteme yanıt vermeye ne kadar yardımcı olabileceğini gösteren puan. Puan [0, 1] aralığındadır. 0 en düşük olasılığı, 1 ise en yüksek olasılığı ifade eder. Bu puan yalnızca Google Arama'da temellendirme ve dinamik alma etkinleştirildiğinde doldurulur. Google Arama'nın tetiklenip tetiklenmeyeceğini belirlemek için eşikle karşılaştırılır.

JSON gösterimi
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

Logprobs Result

Alanlar
topCandidates[] object (TopCandidates)

Uzunluk = toplam kod çözme adımı sayısı.

chosenCandidates[] object (Candidate)

Uzunluk = toplam kod çözme adımı sayısı. Seçilen adaylar topCandidates içinde olabilir veya olmayabilir.

JSON gösterimi
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ]
}

TopCandidates

Her kod çözme adımında en yüksek günlük olasılıklara sahip adaylar.

Alanlar
candidates[] object (Candidate)

Log olasılığına göre azalan düzende sıralanır.

JSON gösterimi
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

Aday

Logprobs jetonu ve puanı için aday.

Alanlar
token string

Adayın jeton dize değeri.

tokenId integer

Adayın jeton kimliği değeri.

logProbability number

Adayın log olasılığı.

JSON gösterimi
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

UrlContextMetadata

URL bağlamı alma aracıyla ilgili meta veriler.

Alanlar
urlMetadata[] object (UrlMetadata)

URL bağlamı listesi.

JSON gösterimi
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}

UrlMetadata

Tek bir URL'nin alınmasıyla ilgili bağlam.

Alanlar
retrievedUrl string

Araç tarafından alınan URL.

urlRetrievalStatus enum (UrlRetrievalStatus)

URL alma işleminin durumu.

JSON gösterimi
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}

UrlRetrievalStatus

URL alma işleminin durumu.

Sıralamalar
URL_RETRIEVAL_STATUS_UNSPECIFIED Varsayılan değer. Bu değer kullanılmıyor.
URL_RETRIEVAL_STATUS_SUCCESS URL alma işlemi başarılı.
URL_RETRIEVAL_STATUS_ERROR URL alma işlemi hata nedeniyle başarısız oldu.
URL_RETRIEVAL_STATUS_PAYWALL İçerik ödeme duvarının arkasında olduğundan URL alma işlemi başarısız oldu.
URL_RETRIEVAL_STATUS_UNSAFE İçerik güvenli olmadığı için URL alma işlemi başarısız oldu.

CitationMetadata

Bir içerik için kaynak ilişkilendirmelerinin toplandığı yer.

Alanlar
citationSources[] object (CitationSource)

Belirli bir yanıtın kaynaklarına yapılan alıntılar.

JSON gösterimi
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}

CitationSource

Belirli bir yanıtın bir bölümü için kaynağa yapılan alıntı.

Alanlar
startIndex integer

İsteğe bağlı. Bu kaynağa atfedilen yanıt segmentinin başlangıcı.

Dizin, bayt cinsinden ölçülen segmentin başlangıcını gösterir.

endIndex integer

İsteğe bağlı. Atfedilen segmentin bitişi (girilen tarihler dahil değil).

uri string

İsteğe bağlı. Metnin bir bölümü için kaynak olarak atfedilen URI.

license string

İsteğe bağlı. Segment için kaynak olarak belirtilen GitHub projesinin lisansı.

Kod alıntıları için lisans bilgisi gereklidir.

JSON gösterimi
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}

GenerationConfig

Model oluşturma ve çıkışlarla ilgili yapılandırma seçenekleri. Her model için tüm parametreler yapılandırılamaz.

Alanlar
stopSequences[] string

İsteğe bağlı. Çıkış oluşturmayı durduracak karakter dizileri kümesi (en fazla 5). Belirtilirse API, stop_sequence karakterinin ilk görünümünde durur. Durdurma dizisi, yanıtın bir parçası olarak dahil edilmez.

responseMimeType string

İsteğe bağlı. Oluşturulan aday metnin MIME türü. Desteklenen MIME türleri şunlardır: text/plain: (varsayılan) Metin çıkışı. application/json: Yanıt adaylarındaki JSON yanıtı. text/x.enum: Yanıt adaylarında dize yanıtı olarak ENUM. Desteklenen tüm metin MIME türlerinin listesi için dokümanlara bakın.

responseSchema object (Schema)

İsteğe bağlı. Oluşturulan aday metnin çıkış şeması. Şemalar, OpenAPI şemasının bir alt kümesi olmalı ve nesneler, temel öğeler veya diziler olabilir.

Ayarlanırsa uyumlu bir responseMimeType da ayarlanmalıdır. Uyumlu MIME türleri: application/json: JSON yanıtı için şema. Daha fazla bilgi için JSON metin oluşturma kılavuzuna bakın.

responseJsonSchema value (Value format)

İsteğe bağlı. Oluşturulan yanıtın çıkış şeması. Bu, responseSchema yerine JSON şemasını kabul eden bir alternatiftir.

Ayarlandıysa responseSchema atlanmalıdır ancak responseMimeType gereklidir.

JSON şemasının tamamı gönderilebilir ancak tüm özellikler desteklenmez. Özellikle yalnızca aşağıdaki özellikler desteklenir:

  • $id
  • $defs
  • $ref
  • $anchor
  • type
  • format
  • title
  • description
  • enum (dizeler ve sayılar için)
  • items
  • prefixItems
  • minItems
  • maxItems
  • minimum
  • maximum
  • anyOf
  • oneOf (anyOf ile aynı şekilde yorumlanır)
  • properties
  • additionalProperties
  • required

Standart olmayan propertyOrdering özelliği de ayarlanabilir.

Döngüsel referanslar sınırlı bir ölçüde açılır ve bu nedenle yalnızca zorunlu olmayan özelliklerde kullanılabilir. (Boş değer atanabilir özellikler yeterli değildir.) Bir alt şemada $ref ayarlanırsa $ ile başlayanlar dışında başka özellik ayarlanamaz.

responseModalities[] enum (Modality)

İsteğe bağlı. Yanıtın istenen biçimleri. Modelin döndürebileceği ve yanıtta beklenmesi gereken modaliteler kümesini temsil eder. Bu, yanıtın biçimleriyle tam olarak eşleşir.

Bir model, desteklenen formatların birden fazla kombinasyonuna sahip olabilir. İstenen yöntemler desteklenen kombinasyonlardan herhangi biriyle eşleşmiyorsa hata döndürülür.

Boş bir liste, yalnızca metin istemeye eşdeğerdir.

candidateCount integer

İsteğe bağlı. Döndürülecek oluşturulmuş yanıt sayısı. Ayarlanmamışsa varsayılan olarak 1 olur. Bu özelliğin önceki nesil modellerde (Gemini 1.0 ailesi) çalışmadığını lütfen unutmayın.

maxOutputTokens integer

İsteğe bağlı. Yanıt adayına dahil edilecek maksimum jeton sayısı.

Not: Varsayılan değer modele göre değişir. getModel işlevinden döndürülen Model öğesinin Model.output_token_limit özelliğine bakın.

temperature number

İsteğe bağlı. Çıkışın rastgeleliğini kontrol eder.

Not: Varsayılan değer modele göre değişir. getModel işlevinden döndürülen Model öğesinin Model.temperature özelliğine bakın.

Değerler [0,0, 2,0] arasında değişebilir.

topP number

İsteğe bağlı. Örnekleme sırasında dikkate alınacak jetonların maksimum kümülatif olasılığı.

Model, birleştirilmiş Top-k ve Top-p (nucleus) örneklemesini kullanır.

Parçalar, yalnızca en olası parçaların dikkate alınması için atanmış olasılıklarına göre sıralanır. Top-k örnekleme, dikkate alınacak maksimum jeton sayısını doğrudan sınırlar. Nucleus örnekleme ise jeton sayısını kümülatif olasılığa göre sınırlar.

Not: Varsayılan değer Model göre değişir ve getModel işlevinden döndürülen Model.top_p özelliğiyle belirtilir. Boş bir topK özelliği, modelin top-k örnekleme uygulamadığını ve isteklerde topK ayarlanmasına izin vermediğini gösterir.

topK integer

İsteğe bağlı. Örnekleme sırasında dikkate alınacak maksimum jeton sayısı.

Gemini modelleri, Top-p (çekirdek) örnekleme veya Top-k ile çekirdek örneklemenin bir kombinasyonunu kullanır. Top-k örnekleme, topK en olası jeton kümesini dikkate alır. Çekirdek örnekleme ile çalışan modellerde topK ayarına izin verilmez.

Not: Varsayılan değer Model göre değişir ve getModel işlevinden döndürülen Model.top_p özelliğiyle belirtilir. Boş bir topK özelliği, modelin top-k örnekleme uygulamadığını ve isteklerde topK ayarlanmasına izin vermediğini gösterir.

seed integer

İsteğe bağlı. Kod çözme işleminde kullanılan başlangıç değeri. Ayarlanmazsa istekte rastgele oluşturulmuş bir başlangıç değeri kullanılır.

presencePenalty number

İsteğe bağlı. Jeton yanıtta daha önce görülmüşse sonraki jetonun logprobs'ine varlık cezası uygulanır.

Bu ceza, ikili (açık/kapalı) bir cezadır ve jetonun (ilk kullanımdan sonra) kaç kez kullanıldığına bağlı değildir. Her kullanımla artan bir ceza için frequencyPenalty kullanın.

Pozitif ceza, yanıtta daha önce kullanılmış olan jetonların kullanılmasını engelleyerek kelime dağarcığını artırır.

Negatif ceza, yanıtta daha önce kullanılmış olan jetonların kullanılmasını teşvik ederek kelime dağarcığını azaltır.

frequencyPenalty number

İsteğe bağlı. Sonraki jetonun logprobs'una uygulanan sıklık cezası, her jetonun yanıtta şimdiye kadar görülme sayısıyla çarpılır.

Pozitif ceza, jetonun kullanıldığı sayıya orantılı olarak, daha önce kullanılmış jetonların kullanılmasını engeller: Bir jeton ne kadar çok kullanılırsa modelin bu jetonu tekrar kullanması o kadar zorlaşır ve yanıtların kelime dağarcığı artar.

Dikkat: Negatif ceza, modeli, jetonun kullanıldığı sayıya orantılı olarak jetonları yeniden kullanmaya teşvik eder. Küçük negatif değerler, yanıtın kelime dağarcığını azaltır. Daha büyük negatif değerler, modelin maxOutputTokens sınırına ulaşana kadar ortak bir jetonu tekrarlamaya başlamasına neden olur.

responseLogprobs boolean

İsteğe bağlı. Doğruysa yanıtın logprobs sonuçlarını dışa aktarır.

logprobs integer

İsteğe bağlı. Yalnızca responseLogprobs=True ise geçerlidir. Bu, Candidate.logprobs_result içindeki her kod çözme adımında döndürülecek en yüksek logprobs sayısını ayarlar. Sayı [1, 5] aralığında olmalıdır.

enableEnhancedCivicAnswers boolean

İsteğe bağlı. Gelişmiş vatandaşlık yanıtlarını etkinleştirir. Bu özellik tüm modellerde kullanılamayabilir.

speechConfig object (SpeechConfig)

İsteğe bağlı. Konuşma üretme yapılandırması.

thinkingConfig object (ThinkingConfig)

İsteğe bağlı. Düşünme özellikleri için yapılandırma. Bu alan, düşünmeyi desteklemeyen modeller için ayarlanırsa hata döndürülür.

mediaResolution enum (MediaResolution)

İsteğe bağlı. Belirtilmişse belirtilen medya çözünürlüğü kullanılır.

JSON gösterimi
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "responseJsonSchema": value,
  "responseModalities": [
    enum (Modality)
  ],
  "candidateCount": integer,
  "maxOutputTokens": integer,
  "temperature": number,
  "topP": number,
  "topK": integer,
  "seed": integer,
  "presencePenalty": number,
  "frequencyPenalty": number,
  "responseLogprobs": boolean,
  "logprobs": integer,
  "enableEnhancedCivicAnswers": boolean,
  "speechConfig": {
    object (SpeechConfig)
  },
  "thinkingConfig": {
    object (ThinkingConfig)
  },
  "mediaResolution": enum (MediaResolution)
}

Yöntem

Yanıtın desteklenen biçimleri.

Sıralamalar
MODALITY_UNSPECIFIED Varsayılan değer.
TEXT Modelin metin döndürmesi gerektiğini belirtir.
IMAGE Modelin resim döndürmesi gerektiğini belirtir.
AUDIO Modelin ses döndürmesi gerektiğini belirtir.

SpeechConfig

Konuşma üretme yapılandırması.

Alanlar
voiceConfig object (VoiceConfig)

Tek sesli çıkış durumundaki yapılandırma.

multiSpeakerVoiceConfig object (MultiSpeakerVoiceConfig)

İsteğe bağlı. Çok hoparlörlü kurulumun yapılandırması. voiceConfig alanı ile aynı anda kullanılamaz.

languageCode string

İsteğe bağlı. Konuşma sentezi için dil kodu (BCP 47 biçiminde, ör. "en-US").

Geçerli değerler şunlardır: de-DE, en-AU, en-GB, en-IN, en-US, es-US, fr-FR, hi-IN, pt-BR, ar-XA, es-ES, fr-CA, id-ID, it-IT, ja-JP, tr-TR, vi-VN, bn-IN, gu-IN, kn-IN, ml-IN, mr-IN, ta-IN, te-IN, nl-NL, ko-KR, cmn-CN, pl-PL, ru-RU ve th-TH.

JSON gösterimi
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}

VoiceConfig

Kullanılacak sesin yapılandırması.

Alanlar
voice_config Union type
Hoparlörün kullanacağı yapılandırma. voice_config yalnızca aşağıdakilerden biri olabilir:
prebuiltVoiceConfig object (PrebuiltVoiceConfig)

Kullanılacak hazır sesin yapılandırması.

JSON gösterimi
{

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

PrebuiltVoiceConfig

Kullanılacak hazır hoparlör yapılandırması.

Alanlar
voiceName string

Kullanılacak hazır sesin adı.

JSON gösterimi
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

Çok hoparlörlü kurulumun yapılandırması.

Alanlar
speakerVoiceConfigs[] object (SpeakerVoiceConfig)

Zorunlu. Etkinleştirilmiş tüm konuşmacı sesleri.

JSON gösterimi
{
  "speakerVoiceConfigs": [
    {
      object (SpeakerVoiceConfig)
    }
  ]
}

SpeakerVoiceConfig

Çok hoparlörlü kurulumda tek bir hoparlörün yapılandırması.

Alanlar
speaker string

Zorunlu. Kullanılacak hoparlörün adı. İstemdekiyle aynı olmalıdır.

voiceConfig object (VoiceConfig)

Zorunlu. Kullanılacak sesin yapılandırması.

JSON gösterimi
{
  "speaker": string,
  "voiceConfig": {
    object (VoiceConfig)
  }
}

ThinkingConfig

Düşünme özellikleri için yapılandırma.

Alanlar
includeThoughts boolean

Yanıtın düşünceleri içerip içermeyeceğini belirtir. Doğruysa düşünceler yalnızca kullanılabilir olduğunda döndürülür.

thinkingBudget integer

Modelin oluşturması gereken düşünce jetonlarının sayısı.

JSON gösterimi
{
  "includeThoughts": boolean,
  "thinkingBudget": integer
}

MediaResolution

Giriş medyasının medya çözünürlüğü.

Sıralamalar
MEDIA_RESOLUTION_UNSPECIFIED Medya çözünürlüğü ayarlanmamış.
MEDIA_RESOLUTION_LOW Medya çözünürlüğü düşük (64 jeton) olarak ayarlanmış.
MEDIA_RESOLUTION_MEDIUM Medya çözünürlüğü orta (256 jeton) olarak ayarlanır.
MEDIA_RESOLUTION_HIGH Medya çözünürlüğü yüksek olarak ayarlanmış (256 jetonla yeniden çerçevelenmiş yakınlaştırma).

HarmCategory

Derecelendirmenin kategorisi.

Bu kategoriler, geliştiricilerin düzenlemek isteyebileceği çeşitli zararları kapsar.

Sıralamalar
HARM_CATEGORY_UNSPECIFIED Kategori belirtilmemiş.
HARM_CATEGORY_DEROGATORY PaLM: Kimliği ve/veya korunan özelliği hedefleyen olumsuz veya zararlı yorumlar.
HARM_CATEGORY_TOXICITY PaLM: Kaba, saygısız veya küfürlü içerik
HARM_CATEGORY_VIOLENCE PaLM: Bir bireye veya gruba karşı şiddet içeren senaryoları ya da kanlı sahnelerin genel açıklamalarını tanımlar.
HARM_CATEGORY_SEXUAL PaLM: Cinsel eylemlere veya diğer müstehcen içeriklere atıfta bulunuyor.
HARM_CATEGORY_MEDICAL PaLM: Kontrol edilmemiş tıbbi tavsiyeleri teşvik ediyor.
HARM_CATEGORY_DANGEROUS PaLM: Zararlı eylemleri teşvik eden, kolaylaştıran veya destekleyen tehlikeli içerikler.
HARM_CATEGORY_HARASSMENT Gemini - Taciz edici içerikler
HARM_CATEGORY_HATE_SPEECH Gemini - Nefret söylemi ve içerik.
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini - Müstehcen içerik
HARM_CATEGORY_DANGEROUS_CONTENT Gemini - Tehlikeli içerik
HARM_CATEGORY_CIVIC_INTEGRITY

Gemini: Sivil bütünlüğe zarar vermek için kullanılabilecek içerikler. DESTEĞİ SONLANDIRILDI: Bunun yerine enableEnhancedCivicAnswers'ı kullanın.

ModalityTokenCount

Tek bir yöntem için jeton sayma bilgilerini gösterir.

Alanlar
modality enum (Modality)

Bu jeton sayısıyla ilişkili yöntem.

tokenCount integer

Jeton sayısı.

JSON gösterimi
{
  "modality": enum (Modality),
  "tokenCount": integer
}

Yöntem

İçerik Bölümü modu

Sıralamalar
MODALITY_UNSPECIFIED Belirtilmemiş yöntem.
TEXT Düz metin.
IMAGE Resim.
VIDEO Video.
AUDIO Ses.
DOCUMENT Doküman (ör. PDF)

SafetyRating

Bir içeriğin güvenlik derecelendirmesi.

Güvenlik derecelendirmesi, bir içeriğin zarar kategorisini ve bu kategorideki zarar olasılığı düzeyini içerir. İçerik, çeşitli zarar kategorilerinde güvenlik açısından sınıflandırılır ve zarar sınıflandırmasının olasılığı burada yer alır.

Alanlar
category enum (HarmCategory)

Zorunlu. Bu puanın kategorisi.

probability enum (HarmProbability)

Zorunlu. Bu içeriğin zararlı olma olasılığı.

blocked boolean

Bu içerik, bu derecelendirme nedeniyle mi engellendi?

JSON gösterimi
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}

HarmProbability

Bir içeriğin zararlı olma olasılığı.

Sınıflandırma sistemi, içeriğin güvenli olmama olasılığını gösterir. Bu, bir içeriğin zararlılık düzeyini göstermez.

Sıralamalar
HARM_PROBABILITY_UNSPECIFIED Olasılık belirtilmemiş.
NEGLIGIBLE İçeriğin güvenli olmama ihtimali çok düşüktür.
LOW İçeriğin güvenli olmama olasılığı düşüktür.
MEDIUM İçeriğin güvenli olmama olasılığı orta seviyededir.
HIGH İçeriğin güvenli olmama olasılığı yüksekse

SafetySetting

Güvenlik engelleme davranışını etkileyen güvenlik ayarı.

Bir kategori için güvenlik ayarının geçirilmesi, içeriğin engellenmesine izin verilen olasılığı değiştirir.

Alanlar
category enum (HarmCategory)

Zorunlu. Bu ayarın kategorisi.

threshold enum (HarmBlockThreshold)

Zorunlu. Zararın engelleneceği olasılık eşiğini kontrol eder.

JSON gösterimi
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

HarmBlockThreshold

Belirli bir zarar olasılığında ve ötesinde engelleme

Sıralamalar
HARM_BLOCK_THRESHOLD_UNSPECIFIED Eşik belirtilmemiş.
BLOCK_LOW_AND_ABOVE NEGLIGIBLE (ÖNEMSİZ) derecesinde içeriklere izin verilir.
BLOCK_MEDIUM_AND_ABOVE ÖNEMSİZ (NEGLIGIBLE) ve DÜŞÜK (LOW) düzeyinde olan içeriklere izin verilir.
BLOCK_ONLY_HIGH NEGLIGIBLE (ÖNEMSİZ), LOW (DÜŞÜK) ve MEDIUM (ORTA) düzeyindeki içeriklere izin verilir.
BLOCK_NONE Tüm içeriğe izin verilir.
OFF Güvenlik filtresini devre dışı bırakın.