Generating content

জেমিনি এপিআই ছবি, অডিও, কোড, টুল এবং আরও অনেক কিছুর মাধ্যমে কন্টেন্ট তৈরিতে সহায়তা করে। এই প্রতিটি বৈশিষ্ট্য সম্পর্কে বিস্তারিত জানতে, টাস্ক-কেন্দ্রিক নমুনা কোডটি পড়ুন এবং দেখুন, অথবা বিস্তৃত নির্দেশিকাগুলি পড়ুন।

পদ্ধতি: models.generateContent

GenerateContentRequest ইনপুট দিলে একটি মডেল প্রতিক্রিয়া তৈরি করে। বিস্তারিত ব্যবহারের তথ্যের জন্য টেক্সট জেনারেশন গাইড দেখুন। টিউন করা মডেল সহ মডেলগুলির মধ্যে ইনপুট ক্ষমতা ভিন্ন হয়। বিস্তারিত জানার জন্য মডেল গাইড এবং টিউনিং গাইড দেখুন।

শেষবিন্দু

পোস্ট https: / /generativelanguage.googleapis.com /v1beta /{model=models /*}:generateContent

পথের পরামিতি

model string

প্রয়োজনীয়। সমাপ্তি তৈরির জন্য ব্যবহৃত Model নাম।

ফর্ম্যাট: models/{model} । এটি models/{model} রূপ নেয়।

অনুরোধের মূল অংশ

অনুরোধের মূল অংশে নিম্নলিখিত কাঠামো সহ ডেটা রয়েছে:

ক্ষেত্র
contents[] object ( Content )

প্রয়োজনীয়। মডেলের সাথে বর্তমান কথোপকথনের বিষয়বস্তু।

একক-পালা প্রশ্নের জন্য, এটি একটি একক উদাহরণ। chat এর মতো বহু-পালা প্রশ্নের জন্য, এটি একটি পুনরাবৃত্তি ক্ষেত্র যেখানে কথোপকথনের ইতিহাস এবং সর্বশেষ অনুরোধ থাকে।

tools[] object ( Tool )

ঐচ্ছিক। পরবর্তী প্রতিক্রিয়া তৈরি করতে Model যে Tools ব্যবহার করতে পারে তার একটি তালিকা।

একটি Tool হল কোডের একটি অংশ যা সিস্টেমকে Model জ্ঞান এবং পরিধির বাইরে কোনও ক্রিয়া বা ক্রিয়াকলাপ সম্পাদনের জন্য বহিরাগত সিস্টেমের সাথে ইন্টারঅ্যাক্ট করতে সক্ষম করে। সমর্থিত Tool হল Function এবং codeExecution । আরও জানতে ফাংশন কলিং এবং কোড এক্সিকিউশন গাইডগুলি পড়ুন।

toolConfig object ( ToolConfig )

ঐচ্ছিক। অনুরোধে উল্লেখিত যেকোনো Tool জন্য টুল কনফিগারেশন। ব্যবহারের উদাহরণের জন্য ফাংশন কলিং নির্দেশিকাটি দেখুন।

safetySettings[] object ( SafetySetting )

ঐচ্ছিক। অনিরাপদ কন্টেন্ট ব্লক করার জন্য অনন্য SafetySetting উদাহরণের একটি তালিকা।

এটি GenerateContentRequest.contents এবং GenerateContentResponse.candidates এ প্রয়োগ করা হবে। প্রতিটি SafetyCategory ধরণের জন্য একাধিক সেটিং থাকা উচিত নয়। API যেকোনো বিষয়বস্তু এবং প্রতিক্রিয়া ব্লক করবে যা এই সেটিংস দ্বারা সেট করা থ্রেশহোল্ড পূরণ করতে ব্যর্থ হয়। এই তালিকাটি safetySettings-এ নির্দিষ্ট প্রতিটি SafetyCategory জন্য ডিফল্ট সেটিংসকে ওভাররাইড করে। যদি তালিকায় প্রদত্ত কোনও SafetyCategory জন্য কোনও SafetySetting না থাকে, তাহলে API সেই বিভাগের জন্য ডিফল্ট নিরাপত্তা সেটিং ব্যবহার করবে। ক্ষতিকর বিভাগগুলি HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY সমর্থিত। উপলব্ধ নিরাপত্তা সেটিংস সম্পর্কে বিস্তারিত তথ্যের জন্য নির্দেশিকাটি পড়ুন। আপনার AI অ্যাপ্লিকেশনগুলিতে সুরক্ষা বিবেচনাগুলি কীভাবে অন্তর্ভুক্ত করবেন তা শিখতে নিরাপত্তা নির্দেশিকাটিও দেখুন।

systemInstruction object ( Content )

ঐচ্ছিক। ডেভেলপার সিস্টেম নির্দেশাবলী সেট করে। বর্তমানে, শুধুমাত্র টেক্সট।

generationConfig object ( GenerationConfig )

ঐচ্ছিক। মডেল জেনারেশন এবং আউটপুটগুলির জন্য কনফিগারেশন বিকল্প।

cachedContent string

ঐচ্ছিক। পূর্বাভাস পরিবেশনের জন্য প্রসঙ্গ হিসেবে ক্যাশে করা কন্টেন্টের নাম। ফর্ম্যাট: cachedContents/{cachedContent}

উদাহরণ অনুরোধ

টেক্সট

পাইথন

from google import genai

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Write a story about a magic backpack."
)
print(response.text)

নোড.জেএস

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

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

যাও

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

শেল

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

জাভা

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

ভাবমূর্তি

পাইথন

from google import genai
import PIL.Image

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

নোড.জেএস

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

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

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

যাও

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

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

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

শেল

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

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

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

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

জাভা

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

অডিও

পাইথন

from google import genai

client = genai.Client()
sample_audio = client.files.upload(file=media / "sample.mp3")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
print(response.text)

নোড.জেএস

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

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

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

যাও

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

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

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

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

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

শেল

# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

ভিডিও

পাইথন

from google import genai
import time

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

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

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

নোড.জেএস

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

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

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

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

যাও

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

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

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

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

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

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

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

শেল

# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${VIDEO_PATH}")
NUM_BYTES=$(wc -c < "${VIDEO_PATH}")
DISPLAY_NAME=VIDEO

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

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

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

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

state=$(jq ".file.state" file_info.json)
echo state=$state

name=$(jq ".file.name" file_info.json)
echo name=$name

while [[ "($state)" = *"PROCESSING"* ]];
do
  echo "Processing video..."
  sleep 5
  # Get the file of interest to check state
  curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
  state=$(jq ".file.state" file_info.json)
done

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions."},
          {"file_data":{"mime_type": "video/mp4", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

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

পিডিএফ

পাইথন

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

যাও

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

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

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

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

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

শেল

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

চ্যাট

পাইথন

from google import genai
from google.genai import types

client = genai.Client()
# Pass initial history using the "history" argument
chat = client.chats.create(
    model="gemini-2.0-flash",
    history=[
        types.Content(role="user", parts=[types.Part(text="Hello")]),
        types.Content(
            role="model",
            parts=[
                types.Part(
                    text="Great to meet you. What would you like to know?"
                )
            ],
        ),
    ],
)
response = chat.send_message(message="I have 2 dogs in my house.")
print(response.text)
response = chat.send_message(message="How many paws are in my house?")
print(response.text)

নোড.জেএস

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const chat = ai.chats.create({
  model: "gemini-2.0-flash",
  history: [
    {
      role: "user",
      parts: [{ text: "Hello" }],
    },
    {
      role: "model",
      parts: [{ text: "Great to meet you. What would you like to know?" }],
    },
  ],
});

const response1 = await chat.sendMessage({
  message: "I have 2 dogs in my house.",
});
console.log("Chat response 1:", response1.text);

const response2 = await chat.sendMessage({
  message: "How many paws are in my house?",
});
console.log("Chat response 2:", response2.text);

যাও

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

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

chat, err := client.Chats.Create(ctx, "gemini-2.0-flash", nil, history)
if err != nil {
	log.Fatal(err)
}

firstResp, err := chat.SendMessage(ctx, genai.Part{Text: "I have 2 dogs in my house."})
if err != nil {
	log.Fatal(err)
}
fmt.Println(firstResp.Text())

secondResp, err := chat.SendMessage(ctx, genai.Part{Text: "How many paws are in my house?"})
if err != nil {
	log.Fatal(err)
}
fmt.Println(secondResp.Text())

শেল

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

জাভা

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

ক্যাশে

পাইথন

from google import genai
from google.genai import types

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

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
print(cache)

response = client.models.generate_content(
    model=model_name,
    contents="Please summarize this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

নোড.জেএস

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

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
console.log("Cache created:", cache);

const response = await ai.models.generateContent({
  model: modelName,
  contents: "Please summarize this transcript",
  config: { cachedContent: cache.name },
});
console.log("Response text:", response.text);

যাও

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)

টিউন করা মডেল

পাইথন

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

JSON মোড

পাইথন

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

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

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

নোড.জেএস

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: "List a few popular cookie recipes.",
  config: {
    responseMimeType: "application/json",
    responseSchema: {
      type: "array",
      items: {
        type: "object",
        properties: {
          recipeName: { type: "string" },
          ingredients: { type: "array", items: { type: "string" } },
        },
        required: ["recipeName", "ingredients"],
      },
    },
  },
});
console.log(response.text);

যাও

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

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

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

response, err := client.Models.GenerateContent(
	ctx,
	"gemini-2.0-flash",
	genai.Text("List a few popular cookie recipes."),
	config,
)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

শেল

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

জাভা

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

কোড এক্সিকিউশন

পাইথন

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)

যাও

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

জাভা

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

ফাংশন কলিং

পাইথন

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)

যাও

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)

নোড.জেএস

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

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

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

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

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

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

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

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

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

  // Step 1: Call generateContent with function calling enabled.
  const generateContentResponse = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents:
      "I have 57 cats, each owns 44 mittens, how many mittens is that in total?",
    config: {
      toolConfig: {
        functionCallingConfig: {
          mode: FunctionCallingConfigMode.ANY,
        },
      },
      tools: [
        {
          functionDeclarations: [
            addDeclaration,
            subtractDeclaration,
            multiplyDeclaration,
            divideDeclaration,
          ],
        },
      ],
    },
  });

  // Step 2: Extract the function call.(
  // Assuming the response contains a 'functionCalls' array.
  const functionCall =
    generateContentResponse.functionCalls &&
    generateContentResponse.functionCalls[0];
  console.log(functionCall);

  // Parse the arguments.
  const args = functionCall.args;
  // Expected args format: { firstParam: number, secondParam: number }

  // Step 3: Invoke the actual function based on the function name.
  const functionMapping = {
    addNumbers: add,
    subtractNumbers: subtract,
    multiplyNumbers: multiply,
    divideNumbers: divide,
  };
  const func = functionMapping[functionCall.name];
  if (!func) {
    console.error("Unimplemented error:", functionCall.name);
    return generateContentResponse;
  }
  const resultValue = func(args.firstParam, args.secondParam);
  console.log("Function result:", resultValue);

  // Step 4: Use the chat API to send the result as the final answer.
  const chat = ai.chats.create({ model: "gemini-2.0-flash" });
  const chatResponse = await chat.sendMessage({
    message: "The final result is " + resultValue,
  });
  console.log(chatResponse.text);
  return chatResponse;
}

শেল


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

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

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

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

জাভা

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

জেনারেশন কনফিগারেশন

পাইথন

from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Tell me a story about a magic backpack.",
    config=types.GenerateContentConfig(
        candidate_count=1,
        stop_sequences=["x"],
        max_output_tokens=20,
        temperature=1.0,
    ),
)
print(response.text)

নোড.জেএস

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

const response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: "Tell me a story about a magic backpack.",
  config: {
    candidateCount: 1,
    stopSequences: ["x"],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

console.log(response.text);

যাও

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

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

response, err := client.Models.GenerateContent(
	ctx,
	"gemini-2.0-flash",
	genai.Text("Tell me a story about a magic backpack."),
	&genai.GenerateContentConfig{
		CandidateCount:  candidateCount,
		StopSequences:   []string{"x"},
		MaxOutputTokens: maxOutputTokens,
		Temperature:     &temperature,
	},
)
if err != nil {
	log.Fatal(err)
}

printResponse(response)

শেল

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

জাভা

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

নিরাপত্তা সেটিংস

পাইথন

from google import genai
from google.genai import types

client = genai.Client()
unsafe_prompt = (
    "I support Martians Soccer Club and I think Jupiterians Football Club sucks! "
    "Write a ironic phrase about them including expletives."
)
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=unsafe_prompt,
    config=types.GenerateContentConfig(
        safety_settings=[
            types.SafetySetting(
                category="HARM_CATEGORY_HATE_SPEECH",
                threshold="BLOCK_MEDIUM_AND_ABOVE",
            ),
            types.SafetySetting(
                category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_ONLY_HIGH"
            ),
        ]
    ),
)
try:
    print(response.text)
except Exception:
    print("No information generated by the model.")

print(response.candidates[0].safety_ratings)

নোড.জেএস

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

  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: unsafePrompt,
    config: {
      safetySettings: [
        {
          category: "HARM_CATEGORY_HATE_SPEECH",
          threshold: "BLOCK_MEDIUM_AND_ABOVE",
        },
        {
          category: "HARM_CATEGORY_HARASSMENT",
          threshold: "BLOCK_ONLY_HIGH",
        },
      ],
    },
  });

  try {
    console.log("Generated text:", response.text);
  } catch (error) {
    console.log("No information generated by the model.");
  }
  console.log("Safety ratings:", response.candidates[0].safetyRatings);
  return response;
}

যাও

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

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

config := &genai.GenerateContentConfig{
	SafetySettings: []*genai.SafetySetting{
		{
			Category:  "HARM_CATEGORY_HATE_SPEECH",
			Threshold: "BLOCK_MEDIUM_AND_ABOVE",
		},
		{
			Category:  "HARM_CATEGORY_HARASSMENT",
			Threshold: "BLOCK_ONLY_HIGH",
		},
	},
}
contents := []*genai.Content{
	genai.NewContentFromText(unsafePrompt, genai.RoleUser),
}
response, err := client.Models.GenerateContent(ctx, "gemini-2.0-flash", contents, config)
if err != nil {
	log.Fatal(err)
}

// Print the generated text.
text := response.Text()
fmt.Println("Generated text:", text)

// Print the and safety ratings from the first candidate.
if len(response.Candidates) > 0 {
	fmt.Println("Finish reason:", response.Candidates[0].FinishReason)
	safetyRatings, err := json.MarshalIndent(response.Candidates[0].SafetyRatings, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println("Safety ratings:", string(safetyRatings))
} else {
	fmt.Println("No candidate returned.")
}

শেল

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

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

জাভা

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

সিস্টেম নির্দেশনা

পাইথন

from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Good morning! How are you?",
    config=types.GenerateContentConfig(
        system_instruction="You are a cat. Your name is Neko."
    ),
)
print(response.text)

নোড.জেএস

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

যাও

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

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

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

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

শেল

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

জাভা

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

প্রতিক্রিয়া মূল অংশ

যদি সফল হয়, তাহলে রেসপন্স বডিতে GenerateContentResponse এর একটি উদাহরণ থাকবে।

পদ্ধতি: models.streamGenerateContent

GenerateContentRequest ইনপুট দেওয়া মডেল থেকে একটি স্ট্রিমযুক্ত প্রতিক্রিয়া তৈরি করে।

শেষবিন্দু

পোস্ট https: / /generativelanguage.googleapis.com /v1beta /{model=models /*}:streamGenerateContent

পথের পরামিতি

model string

প্রয়োজনীয়। সমাপ্তি তৈরির জন্য ব্যবহৃত Model নাম।

ফর্ম্যাট: models/{model} । এটি models/{model} রূপ নেয়।

অনুরোধের মূল অংশ

অনুরোধের মূল অংশে নিম্নলিখিত কাঠামো সহ ডেটা রয়েছে:

ক্ষেত্র
contents[] object ( Content )

প্রয়োজনীয়। মডেলের সাথে বর্তমান কথোপকথনের বিষয়বস্তু।

একক-পালা প্রশ্নের জন্য, এটি একটি একক উদাহরণ। chat এর মতো বহু-পালা প্রশ্নের জন্য, এটি একটি পুনরাবৃত্তি ক্ষেত্র যেখানে কথোপকথনের ইতিহাস এবং সর্বশেষ অনুরোধ থাকে।

tools[] object ( Tool )

ঐচ্ছিক। পরবর্তী প্রতিক্রিয়া তৈরি করতে Model যে Tools ব্যবহার করতে পারে তার একটি তালিকা।

একটি Tool হল কোডের একটি অংশ যা সিস্টেমকে Model জ্ঞান এবং পরিধির বাইরে কোনও ক্রিয়া বা ক্রিয়াকলাপ সম্পাদনের জন্য বহিরাগত সিস্টেমের সাথে ইন্টারঅ্যাক্ট করতে সক্ষম করে। সমর্থিত Tool হল Function এবং codeExecution । আরও জানতে ফাংশন কলিং এবং কোড এক্সিকিউশন গাইডগুলি পড়ুন।

toolConfig object ( ToolConfig )

ঐচ্ছিক। অনুরোধে উল্লেখিত যেকোনো Tool জন্য টুল কনফিগারেশন। ব্যবহারের উদাহরণের জন্য ফাংশন কলিং নির্দেশিকাটি দেখুন।

safetySettings[] object ( SafetySetting )

ঐচ্ছিক। অনিরাপদ কন্টেন্ট ব্লক করার জন্য অনন্য SafetySetting উদাহরণের একটি তালিকা।

এটি GenerateContentRequest.contents এবং GenerateContentResponse.candidates এ প্রয়োগ করা হবে। প্রতিটি SafetyCategory ধরণের জন্য একাধিক সেটিং থাকা উচিত নয়। API যেকোনো বিষয়বস্তু এবং প্রতিক্রিয়া ব্লক করবে যা এই সেটিংস দ্বারা সেট করা থ্রেশহোল্ড পূরণ করতে ব্যর্থ হয়। এই তালিকাটি safetySettings-এ নির্দিষ্ট প্রতিটি SafetyCategory জন্য ডিফল্ট সেটিংসকে ওভাররাইড করে। যদি তালিকায় প্রদত্ত কোনও SafetyCategory জন্য কোনও SafetySetting না থাকে, তাহলে API সেই বিভাগের জন্য ডিফল্ট নিরাপত্তা সেটিং ব্যবহার করবে। ক্ষতিকর বিভাগগুলি HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY সমর্থিত। উপলব্ধ নিরাপত্তা সেটিংস সম্পর্কে বিস্তারিত তথ্যের জন্য নির্দেশিকাটি পড়ুন। আপনার AI অ্যাপ্লিকেশনগুলিতে সুরক্ষা বিবেচনাগুলি কীভাবে অন্তর্ভুক্ত করবেন তা শিখতে নিরাপত্তা নির্দেশিকাটিও দেখুন।

systemInstruction object ( Content )

ঐচ্ছিক। ডেভেলপার সিস্টেম নির্দেশাবলী সেট করে। বর্তমানে, শুধুমাত্র টেক্সট।

generationConfig object ( GenerationConfig )

ঐচ্ছিক। মডেল জেনারেশন এবং আউটপুটগুলির জন্য কনফিগারেশন বিকল্প।

cachedContent string

ঐচ্ছিক। পূর্বাভাস পরিবেশনের জন্য প্রসঙ্গ হিসেবে ক্যাশে করা কন্টেন্টের নাম। ফর্ম্যাট: cachedContents/{cachedContent}

উদাহরণ অনুরোধ

টেক্সট

পাইথন

from google import genai

client = genai.Client()
response = client.models.generate_content_stream(
    model="gemini-2.0-flash", contents="Write a story about a magic backpack."
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)

নোড.জেএস

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

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

যাও

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
contents := []*genai.Content{
	genai.NewContentFromText("Write a story about a magic backpack.", genai.RoleUser),
}
for response, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-2.0-flash",
	contents,
	nil,
) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(response.Candidates[0].Content.Parts[0].Text)
}

শেল

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

জাভা

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

ভাবমূর্তি

পাইথন

from google import genai
import PIL.Image

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

নোড.জেএস

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

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

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

যাও

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

শেল

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

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

জাভা

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

অডিও

পাইথন

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)

যাও

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

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

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

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

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

শেল

# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

ভিডিও

পাইথন

from google import genai
import time

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

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

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

নোড.জেএস

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

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

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

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

যাও

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

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

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

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

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

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

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

শেল

# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${VIDEO_PATH}")
NUM_BYTES=$(wc -c < "${VIDEO_PATH}")
DISPLAY_NAME=VIDEO_PATH

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

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

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

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

state=$(jq ".file.state" file_info.json)
echo state=$state

while [[ "($state)" = *"PROCESSING"* ]];
do
  echo "Processing video..."
  sleep 5
  # Get the file of interest to check state
  curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
  state=$(jq ".file.state" file_info.json)
done

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

cat response.json
echo

পিডিএফ

পাইথন

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)

যাও

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

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

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

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

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

শেল

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

চ্যাট

পাইথন

from google import genai
from google.genai import types

client = genai.Client()
chat = client.chats.create(
    model="gemini-2.0-flash",
    history=[
        types.Content(role="user", parts=[types.Part(text="Hello")]),
        types.Content(
            role="model",
            parts=[
                types.Part(
                    text="Great to meet you. What would you like to know?"
                )
            ],
        ),
    ],
)
response = chat.send_message_stream(message="I have 2 dogs in my house.")
for chunk in response:
    print(chunk.text)
    print("_" * 80)
response = chat.send_message_stream(message="How many paws are in my house?")
for chunk in response:
    print(chunk.text)
    print("_" * 80)

print(chat.get_history())

নোড.জেএস

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const chat = ai.chats.create({
  model: "gemini-2.0-flash",
  history: [
    {
      role: "user",
      parts: [{ text: "Hello" }],
    },
    {
      role: "model",
      parts: [{ text: "Great to meet you. What would you like to know?" }],
    },
  ],
});

console.log("Streaming response for first message:");
const stream1 = await chat.sendMessageStream({
  message: "I have 2 dogs in my house.",
});
for await (const chunk of stream1) {
  console.log(chunk.text);
  console.log("_".repeat(80));
}

console.log("Streaming response for second message:");
const stream2 = await chat.sendMessageStream({
  message: "How many paws are in my house?",
});
for await (const chunk of stream2) {
  console.log(chunk.text);
  console.log("_".repeat(80));
}

console.log(chat.getHistory());

যাও

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

history := []*genai.Content{
	genai.NewContentFromText("Hello", genai.RoleUser),
	genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),
}
chat, err := client.Chats.Create(ctx, "gemini-2.0-flash", nil, history)
if err != nil {
	log.Fatal(err)
}

for chunk, err := range chat.SendMessageStream(ctx, genai.Part{Text: "I have 2 dogs in my house."}) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(chunk.Text())
	fmt.Println(strings.Repeat("_", 64))
}

for chunk, err := range chat.SendMessageStream(ctx, genai.Part{Text: "How many paws are in my house?"}) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(chunk.Text())
	fmt.Println(strings.Repeat("_", 64))
}

fmt.Println(chat.History(false))

শেল

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

প্রতিক্রিয়া মূল অংশ

যদি সফল হয়, তাহলে রেসপন্স বডিতে GenerateContentResponse ইনস্ট্যান্সের একটি স্ট্রিম থাকবে।

জেনারেটকন্টেন্টরেসপন্স

একাধিক প্রার্থীর প্রতিক্রিয়া সমর্থনকারী মডেলের প্রতিক্রিয়া।

GenerateContentResponse.prompt_feedback এবং finishReason এবং safetyRatings -এ প্রতিটি প্রার্থীর জন্য নিরাপত্তা রেটিং এবং কন্টেন্ট ফিল্টারিং রিপোর্ট করা হয়। API: - সমস্ত অনুরোধকৃত প্রার্থী ফেরত দেয় অথবা তাদের কেউ নয় - প্রম্পটে কিছু ভুল থাকলেই কোনও প্রার্থী ফেরত দেয় না ( promptFeedback দেখুন) - finishReason এবং safetyRatings -এ প্রতিটি প্রার্থীর প্রতিক্রিয়া রিপোর্ট করে।

ক্ষেত্র
candidates[] object ( Candidate )

মডেল থেকে প্রার্থীদের প্রতিক্রিয়া।

promptFeedback object ( PromptFeedback )

কন্টেন্ট ফিল্টার সম্পর্কিত প্রম্পটের প্রতিক্রিয়া ফেরত দেয়।

usageMetadata object ( UsageMetadata )

শুধুমাত্র আউটপুট। জেনারেশন রিকোয়েস্টের টোকেন ব্যবহারের মেটাডেটা।

modelVersion string

শুধুমাত্র আউটপুট। প্রতিক্রিয়া তৈরি করতে ব্যবহৃত মডেল সংস্করণ।

responseId string

শুধুমাত্র আউটপুট। প্রতিটি প্রতিক্রিয়া সনাক্ত করতে responseId ব্যবহার করা হয়।

modelStatus object ( ModelStatus )

শুধুমাত্র আউটপুট। এই মডেলের বর্তমান মডেলের অবস্থা।

JSON উপস্থাপনা
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string,
  "responseId": string,
  "modelStatus": {
    object (ModelStatus)
  }
}

প্রম্পটফিডব্যাক

GenerateContentRequest.content এ উল্লেখিত প্রতিক্রিয়া মেটাডেটার একটি সেট।

ক্ষেত্র
blockReason enum ( BlockReason )

ঐচ্ছিক। যদি সেট করা থাকে, তাহলে প্রম্পটটি ব্লক করা হয়েছে এবং কোনও প্রার্থী ফেরত দেওয়া হয়নি। প্রম্পটটি পুনরায় লিখুন।

safetyRatings[] object ( SafetyRating )

প্রম্পটের নিরাপত্তার জন্য রেটিং। প্রতিটি বিভাগে সর্বাধিক একটি রেটিং থাকতে হবে।

JSON উপস্থাপনা
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

ব্লকরিজন

প্রম্পটটি কেন ব্লক করা হয়েছিল তা উল্লেখ করে।

এনামস
BLOCK_REASON_UNSPECIFIED ডিফল্ট মান। এই মানটি অব্যবহৃত।
SAFETY নিরাপত্তার কারণে প্রম্পট ব্লক করা হয়েছে। কোন সুরক্ষা বিভাগ এটি ব্লক করেছে তা বুঝতে safetyRatings পরীক্ষা করুন।
OTHER অজানা কারণে প্রম্পট ব্লক করা হয়েছে।
BLOCKLIST পরিভাষা ব্লকলিস্ট থেকে অন্তর্ভুক্ত শর্তাবলীর কারণে প্রম্পট ব্লক করা হয়েছে।
PROHIBITED_CONTENT নিষিদ্ধ কন্টেন্টের কারণে প্রম্পটটি ব্লক করা হয়েছে।
IMAGE_SAFETY অনিরাপদ ছবি তৈরির সামগ্রীর কারণে প্রার্থীদের ব্লক করা হয়েছে।

ব্যবহারমেটাডেটা

জেনারেশন রিকোয়েস্টের টোকেন ব্যবহারের মেটাডেটা।

ক্ষেত্র
promptTokenCount integer

প্রম্পটে টোকেনের সংখ্যা। যখন cachedContent সেট করা থাকে, তখনও এটি মোট কার্যকর প্রম্পট আকার, অর্থাৎ এতে ক্যাশেড কন্টেন্টে থাকা টোকেনের সংখ্যা অন্তর্ভুক্ত থাকে।

cachedContentTokenCount integer

প্রম্পটের ক্যাশে করা অংশে (ক্যাশে করা কন্টেন্ট) টোকেনের সংখ্যা

candidatesTokenCount integer

সমস্ত জেনারেট করা প্রতিক্রিয়া প্রার্থীদের মধ্যে মোট টোকেনের সংখ্যা।

toolUsePromptTokenCount integer

শুধুমাত্র আউটপুট। টুল-ব্যবহার প্রম্পটে উপস্থিত টোকেনের সংখ্যা।

thoughtsTokenCount integer

শুধুমাত্র আউটপুট। চিন্তাভাবনা মডেলের জন্য চিন্তার টোকেনের সংখ্যা।

totalTokenCount integer

জেনারেশন রিকোয়েস্টের মোট টোকেন সংখ্যা (প্রম্পট + রেসপন্স ক্যান্ডিডেট)।

promptTokensDetails[] object ( ModalityTokenCount )

শুধুমাত্র আউটপুট। অনুরোধ ইনপুটে প্রক্রিয়া করা পদ্ধতিগুলির তালিকা।

cacheTokensDetails[] object ( ModalityTokenCount )

শুধুমাত্র আউটপুট। অনুরোধ ইনপুটে ক্যাশেড কন্টেন্টের পদ্ধতির তালিকা।

candidatesTokensDetails[] object ( ModalityTokenCount )

শুধুমাত্র আউটপুট। প্রতিক্রিয়ায় ফেরত পাঠানো পদ্ধতির তালিকা।

toolUsePromptTokensDetails[] object ( ModalityTokenCount )

শুধুমাত্র আউটপুট। টুল-ব্যবহারের অনুরোধ ইনপুটগুলির জন্য প্রক্রিয়াজাতকরণের পদ্ধতিগুলির তালিকা।

JSON উপস্থাপনা
{
  "promptTokenCount": integer,
  "cachedContentTokenCount": integer,
  "candidatesTokenCount": integer,
  "toolUsePromptTokenCount": integer,
  "thoughtsTokenCount": integer,
  "totalTokenCount": integer,
  "promptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "cacheTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "candidatesTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "toolUsePromptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ]
}

মডেলস্ট্যাটাস

অন্তর্নিহিত মডেলের অবস্থা। এটি অন্তর্নিহিত মডেলের পর্যায় এবং প্রযোজ্য ক্ষেত্রে অবসরের সময় নির্দেশ করতে ব্যবহৃত হয়।

ক্ষেত্র
modelStage enum ( ModelStage )

অন্তর্নিহিত মডেলের পর্যায়।

retirementTime string ( Timestamp format)

মডেলটি যে সময়ে অবসর গ্রহণ করবে।

RFC 3339 ব্যবহার করে, যেখানে উৎপন্ন আউটপুট সর্বদা Z-স্বাভাবিক হবে এবং 0, 3, 6 অথবা 9 ভগ্নাংশ সংখ্যা ব্যবহার করবে। "Z" ব্যতীত অন্যান্য অফসেটগুলিও গ্রহণযোগ্য। উদাহরণ: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" অথবা "2014-10-02T15:01:23+05:30"

message string

মডেলের অবস্থা ব্যাখ্যা করে একটি বার্তা।

JSON উপস্থাপনা
{
  "modelStage": enum (ModelStage),
  "retirementTime": string,
  "message": string
}

মডেলস্টেজ

অন্তর্নিহিত মডেলের পর্যায় নির্ধারণ করে।

এনামস
MODEL_STAGE_UNSPECIFIED অনির্দিষ্ট মডেল পর্যায়।
UNSTABLE_EXPERIMENTAL

অন্তর্নিহিত মডেলটি অনেক টিউনিংয়ের বিষয়।

EXPERIMENTAL এই পর্যায়ের মডেলগুলি শুধুমাত্র পরীক্ষামূলক উদ্দেশ্যে।
PREVIEW এই পর্যায়ের মডেলগুলি পরীক্ষামূলক মডেলগুলির তুলনায় বেশি পরিপক্ক।
STABLE এই পর্যায়ের মডেলগুলিকে স্থিতিশীল এবং উৎপাদন ব্যবহারের জন্য প্রস্তুত বলে মনে করা হয়।
LEGACY যদি মডেলটি এই পর্যায়ে থাকে, তাহলে এর অর্থ হল এই মডেলটি অদূর ভবিষ্যতে বন্ধ হয়ে যাওয়ার পথে। শুধুমাত্র বিদ্যমান গ্রাহকরা এই মডেলটি ব্যবহার করতে পারবেন।
DEPRECATED

এই পর্যায়ের মডেলগুলি অবচিত। এই মডেলগুলি ব্যবহার করা যাবে না।

RETIRED এই পর্যায়ের মডেলগুলি অবসরপ্রাপ্ত। এই মডেলগুলি ব্যবহার করা যাবে না।

প্রার্থী

মডেল থেকে তৈরি একটি প্রতিক্রিয়া প্রার্থী।

ক্ষেত্র
content object ( Content )

শুধুমাত্র আউটপুট। মডেল থেকে জেনারেট করা কন্টেন্ট ফেরত পাঠানো হয়েছে।

finishReason enum ( FinishReason )

ঐচ্ছিক। শুধুমাত্র আউটপুট। মডেলটি টোকেন তৈরি করা বন্ধ করার কারণ।

যদি খালি থাকে, তাহলে মডেলটি টোকেন তৈরি করা বন্ধ করেনি।

safetyRatings[] object ( SafetyRating )

একজন প্রতিক্রিয়া প্রার্থীর নিরাপত্তার জন্য রেটিংগুলির তালিকা।

প্রতিটি বিভাগে সর্বাধিক একটি রেটিং থাকতে পারে।

citationMetadata object ( CitationMetadata )

শুধুমাত্র আউটপুট। মডেল-উত্পাদিত প্রার্থীর জন্য উদ্ধৃতি তথ্য।

এই ক্ষেত্রটি content অন্তর্ভুক্ত যেকোনো লেখার জন্য আবৃত্তির তথ্য দিয়ে পূর্ণ হতে পারে। এগুলি হল এমন অনুচ্ছেদ যা ফাউন্ডেশনাল এলএলএম-এর প্রশিক্ষণ ডেটাতে কপিরাইটযুক্ত উপাদান থেকে "আবৃত্তি" করা হয়েছে।

tokenCount integer

শুধুমাত্র আউটপুট। এই প্রার্থীর জন্য টোকেন গণনা।

groundingAttributions[] object ( GroundingAttribution )

শুধুমাত্র আউটপুট। ভিত্তিগত উত্তরে অবদান রেখেছে এমন উৎসের জন্য অ্যাট্রিবিউশন তথ্য।

এই ক্ষেত্রটি GenerateAnswer কলের জন্য পূরণ করা হয়েছে।

groundingMetadata object ( GroundingMetadata )

শুধুমাত্র আউটপুট। প্রার্থীর জন্য গ্রাউন্ডিং মেটাডেটা।

এই ক্ষেত্রটি GenerateContent কলের জন্য পূরণ করা হয়েছে।

avgLogprobs number

শুধুমাত্র আউটপুট। প্রার্থীর গড় লগ সম্ভাব্যতা স্কোর।

logprobsResult object ( LogprobsResult )

শুধুমাত্র আউটপুট। রেসপন্স টোকেন এবং শীর্ষ টোকেনের জন্য লগ-সম্ভাবনার স্কোর

urlContextMetadata object ( UrlContextMetadata )

শুধুমাত্র আউটপুট। ইউআরএল প্রসঙ্গ পুনরুদ্ধার সরঞ্জাম সম্পর্কিত মেটাডেটা।

index integer

শুধুমাত্র আউটপুট। প্রতিক্রিয়া প্রার্থীদের তালিকায় প্রার্থীর সূচী।

finishMessage string

ঐচ্ছিক। শুধুমাত্র আউটপুট। মডেলটি কেন টোকেন তৈরি করা বন্ধ করেছে তার কারণ বিস্তারিতভাবে উল্লেখ করা হয়েছে। এটি শুধুমাত্র তখনই পূরণ করা হবে যখন finishReason সেট করা থাকে।

JSON উপস্থাপনা
{
  "content": {
    object (Content)
  },
  "finishReason": enum (FinishReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ],
  "citationMetadata": {
    object (CitationMetadata)
  },
  "tokenCount": integer,
  "groundingAttributions": [
    {
      object (GroundingAttribution)
    }
  ],
  "groundingMetadata": {
    object (GroundingMetadata)
  },
  "avgLogprobs": number,
  "logprobsResult": {
    object (LogprobsResult)
  },
  "urlContextMetadata": {
    object (UrlContextMetadata)
  },
  "index": integer,
  "finishMessage": string
}

কারণ শেষ করুন

মডেলটি কেন টোকেন তৈরি করা বন্ধ করেছে তার কারণ নির্ধারণ করে।

এনামস
FINISH_REASON_UNSPECIFIED ডিফল্ট মান। এই মানটি অব্যবহৃত।
STOP মডেলের প্রাকৃতিক স্টপ পয়েন্ট অথবা প্রদত্ত স্টপ সিকোয়েন্স।
MAX_TOKENS অনুরোধে উল্লেখিত টোকেনের সর্বাধিক সংখ্যা পৌঁছে গেছে।
SAFETY নিরাপত্তার কারণে প্রতিক্রিয়া প্রার্থীর বিষয়বস্তু চিহ্নিত করা হয়েছে।
RECITATION আবৃত্তির কারণে প্রতিক্রিয়া প্রার্থীর বিষয়বস্তু চিহ্নিত করা হয়েছিল।
LANGUAGE প্রতিক্রিয়া প্রার্থীর বিষয়বস্তুটি অসমর্থিত ভাষা ব্যবহারের জন্য চিহ্নিত করা হয়েছে।
OTHER অজানা কারণ।
BLOCKLIST টোকেন তৈরি বন্ধ করা হয়েছে কারণ কন্টেন্টে নিষিদ্ধ শব্দ রয়েছে।
PROHIBITED_CONTENT সম্ভাব্য নিষিদ্ধ কন্টেন্ট থাকার কারণে টোকেন তৈরি বন্ধ করা হয়েছে।
SPII টোকেন জেনারেশন বন্ধ করা হয়েছে কারণ কন্টেন্টটিতে সম্ভবত সংবেদনশীল ব্যক্তিগতভাবে শনাক্তযোগ্য তথ্য (SPII) থাকতে পারে।
MALFORMED_FUNCTION_CALL মডেল দ্বারা উত্পন্ন ফাংশন কলটি অবৈধ।
IMAGE_SAFETY টোকেন জেনারেশন বন্ধ করা হয়েছে কারণ জেনারেট করা ছবিতে নিরাপত্তা লঙ্ঘন রয়েছে।
IMAGE_PROHIBITED_CONTENT ছবি তৈরি বন্ধ করা হয়েছে কারণ তৈরি করা ছবিতে অন্যান্য নিষিদ্ধ কন্টেন্ট রয়েছে।
IMAGE_OTHER অন্যান্য বিবিধ সমস্যার কারণে ছবি তৈরি বন্ধ হয়ে গেছে।
NO_IMAGE মডেলটি একটি ছবি তৈরি করবে বলে আশা করা হয়েছিল, কিন্তু কোনও ছবি তৈরি হয়নি।
IMAGE_RECITATION আবৃত্তির কারণে ছবি তৈরি বন্ধ হয়ে গেছে।
UNEXPECTED_TOOL_CALL মডেল একটি টুল কল তৈরি করেছে কিন্তু অনুরোধে কোনও টুল সক্রিয় করা হয়নি।
TOO_MANY_TOOL_CALLS মডেল পরপর অনেকগুলি টুল কল করেছে, ফলে সিস্টেমটি এক্সিকিউশন থেকে বেরিয়ে এসেছে।
MISSING_THOUGHT_SIGNATURE অনুরোধে অন্তত একটি চিন্তার স্বাক্ষর অনুপস্থিত।

গ্রাউন্ডিংঅ্যাট্রিবিউশন

উত্তরে অবদান রেখেছে এমন একটি উৎসের জন্য কৃতিত্ব।

ক্ষেত্র
sourceId object ( AttributionSourceId )

শুধুমাত্র আউটপুট। এই বৈশিষ্ট্যে অবদানকারী উৎসের শনাক্তকারী।

content object ( Content )

এই বৈশিষ্ট্য তৈরি করে এমন উৎস কন্টেন্টের গ্রাউন্ডিং।

JSON উপস্থাপনা
{
  "sourceId": {
    object (AttributionSourceId)
  },
  "content": {
    object (Content)
  }
}

অ্যাট্রিবিউশনসোর্স আইডি

এই বৈশিষ্ট্যে অবদানকারী উৎসের শনাক্তকারী।

ক্ষেত্র
source Union type
source নিম্নলিখিতগুলির মধ্যে কেবল একটি হতে পারে:
groundingPassage object ( GroundingPassageId )

একটি ইনলাইন প্যাসেজের জন্য শনাক্তকারী।

semanticRetrieverChunk object ( SemanticRetrieverChunk )

সিমান্টিক রিট্রিভারের মাধ্যমে আনা একটি Chunk শনাক্তকারী।

JSON উপস্থাপনা
{

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

গ্রাউন্ডিংপ্যাসেজ আইডি

GroundingPassage এর মধ্যে একটি অংশের জন্য শনাক্তকারী।

ক্ষেত্র
passageId string

শুধুমাত্র আউটপুট। GenerateAnswerRequest এর GroundingPassage.id সাথে মিলে যাওয়া প্যাসেজের আইডি।

partIndex integer

শুধুমাত্র আউটপুট। GenerateAnswerRequest এর GroundingPassage.content এর মধ্যে অংশের সূচী।

JSON উপস্থাপনা
{
  "passageId": string,
  "partIndex": integer
}

সিমান্টিকরিট্রিভারচাঙ্ক

SemanticRetrieverConfig ব্যবহার করে GenerateAnswerRequest এ উল্লেখিত Semantic Retriever এর মাধ্যমে পুনরুদ্ধার করা একটি Chunk শনাক্তকারী।

ক্ষেত্র
source string

শুধুমাত্র আউটপুট। অনুরোধের SemanticRetrieverConfig.source এর সাথে মেলে এমন উৎসের নাম। উদাহরণ: corpora/123 অথবা corpora/123/documents/abc

chunk string

শুধুমাত্র আউটপুট। অ্যাট্রিবিউটেড টেক্সট সম্বলিত Chunk নাম। উদাহরণ: corpora/123/documents/abc/chunks/xyz

JSON উপস্থাপনা
{
  "source": string,
  "chunk": string
}

গ্রাউন্ডিংমেটাডেটা

গ্রাউন্ডিং সক্ষম করা হলে মেটাডেটা ক্লায়েন্টে ফিরে আসে।

ক্ষেত্র
groundingChunks[] object ( GroundingChunk )

নির্দিষ্ট গ্রাউন্ডিং সোর্স থেকে উদ্ধার করা সহায়ক রেফারেন্সের তালিকা। স্ট্রিমিং করার সময়, এতে কেবল সেই গ্রাউন্ডিং অংশগুলি থাকে যা পূর্ববর্তী প্রতিক্রিয়াগুলির গ্রাউন্ডিং মেটাডেটায় অন্তর্ভুক্ত করা হয়নি।

groundingSupports[] object ( GroundingSupport )

গ্রাউন্ডিং সাপোর্টের তালিকা।

webSearchQueries[] string

পরবর্তী ওয়েব অনুসন্ধানের জন্য ওয়েব অনুসন্ধান কোয়েরি।

searchEntryPoint object ( SearchEntryPoint )

ঐচ্ছিক। পরবর্তী ওয়েব অনুসন্ধানের জন্য গুগল অনুসন্ধান এন্ট্রি।

retrievalMetadata object ( RetrievalMetadata )

গ্রাউন্ডিং প্রবাহে পুনরুদ্ধার সম্পর্কিত মেটাডেটা।

googleMapsWidgetContextToken string

ঐচ্ছিক। Google Maps উইজেট কনটেক্সট টোকেনের রিসোর্স নাম যা PlacesContextElement উইজেটের সাথে প্রাসঙ্গিক ডেটা রেন্ডার করার জন্য ব্যবহার করা যেতে পারে। শুধুমাত্র তখনই পূরণ করা হবে যখন Google Maps এর সাথে গ্রাউন্ডিং সক্ষম করা থাকে।

JSON উপস্থাপনা
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  },
  "googleMapsWidgetContextToken": string
}

SearchEntryPoint সম্পর্কে

গুগল সার্চ এন্ট্রি পয়েন্ট।

ক্ষেত্র
renderedContent string

ঐচ্ছিক। ওয়েব কন্টেন্ট স্নিপেট যা একটি ওয়েব পৃষ্ঠা বা একটি অ্যাপ ওয়েবভিউতে এম্বেড করা যেতে পারে।

sdkBlob string ( bytes format)

ঐচ্ছিক। বেস৬৪ এনকোডেড JSON <সন্ধান শব্দ, অনুসন্ধান URL> টুপলের অ্যারে উপস্থাপন করে।

একটি base64-এনকোডেড স্ট্রিং।

JSON উপস্থাপনা
{
  "renderedContent": string,
  "sdkBlob": string
}

গ্রাউন্ডিংচাঙ্ক

গ্রাউন্ডিং চাঙ্ক।

ক্ষেত্র
chunk_type Union type
Chunk type. chunk_type নিম্নলিখিতগুলির মধ্যে কেবল একটি হতে পারে:
web object ( Web )

জাল থেকে গ্রাউন্ডিং অংশ।

retrievedContext object ( RetrievedContext )

ঐচ্ছিক। ফাইল অনুসন্ধান সরঞ্জাম দ্বারা প্রসঙ্গ থেকে গ্রাউন্ডিং অংশ পুনরুদ্ধার করা হয়েছে।

maps object ( Maps )

ঐচ্ছিক। গুগল ম্যাপ থেকে গ্রাউন্ডিং চাঙ্ক।

JSON উপস্থাপনা
{

  // chunk_type
  "web": {
    object (Web)
  },
  "retrievedContext": {
    object (RetrievedContext)
  },
  "maps": {
    object (Maps)
  }
  // Union type
}

ওয়েব

ওয়েব থেকে কিছু অংশ।

ক্ষেত্র
uri string

চাঙ্কের URI রেফারেন্স।

title string

খণ্ডের শিরোনাম।

JSON উপস্থাপনা
{
  "uri": string,
  "title": string
}

পুনরুদ্ধারকৃতপ্রসঙ্গ

ফাইল অনুসন্ধান টুল দ্বারা উদ্ধার করা প্রসঙ্গ থেকে অংশ।

ক্ষেত্র
uri string

ঐচ্ছিক। শব্দার্থিক পুনরুদ্ধার নথির URI রেফারেন্স।

title string

ঐচ্ছিক। নথির শিরোনাম।

text string

ঐচ্ছিক। খণ্ডের লেখা।

fileSearchStore string

ঐচ্ছিক। ডকুমেন্ট ধারণকারী FileSearchStore এর নাম। উদাহরণ: fileSearchStores/123

JSON উপস্থাপনা
{
  "uri": string,
  "title": string,
  "text": string,
  "fileSearchStore": string
}

মানচিত্র

গুগল ম্যাপস থেকে একটি গ্রাউন্ডিং চাঙ্ক। একটি ম্যাপস চাঙ্ক একটি একক স্থানের সাথে সম্পর্কিত।

ক্ষেত্র
uri string

স্থানের URI রেফারেন্স।

title string

স্থানের নাম।

text string

স্থানের উত্তরের টেক্সট বর্ণনা।

placeId string

স্থানটির এই আইডি, places/{placeId} ফর্ম্যাটে। ব্যবহারকারী এই আইডি ব্যবহার করে স্থানটি খুঁজে দেখতে পারেন।

placeAnswerSources object ( PlaceAnswerSources )

গুগল ম্যাপে কোনও নির্দিষ্ট স্থানের বৈশিষ্ট্য সম্পর্কে উত্তর প্রদানকারী উৎস।

JSON উপস্থাপনা
{
  "uri": string,
  "title": string,
  "text": string,
  "placeId": string,
  "placeAnswerSources": {
    object (PlaceAnswerSources)
  }
}

স্থান উত্তর সূত্র

গুগল ম্যাপে একটি নির্দিষ্ট স্থানের বৈশিষ্ট্য সম্পর্কে উত্তর প্রদানকারী উৎসের সংগ্রহ। প্রতিটি PlaceAnswerSources বার্তা গুগল ম্যাপে একটি নির্দিষ্ট স্থানের সাথে সম্পর্কিত। গুগল ম্যাপস টুলটি স্থানের বৈশিষ্ট্য সম্পর্কে প্রশ্নের উত্তর দেওয়ার জন্য এই উৎসগুলি ব্যবহার করেছে (যেমন: "বার ফুতে কি ওয়াইফাই আছে" অথবা "ফু বার হুইলচেয়ার কি অ্যাক্সেসযোগ্য?")। বর্তমানে আমরা শুধুমাত্র পর্যালোচনার স্নিপেটগুলিকে উৎস হিসেবে সমর্থন করি।

ক্ষেত্র
reviewSnippets[] object ( ReviewSnippet )

Google Maps-এ কোনও নির্দিষ্ট স্থানের বৈশিষ্ট্য সম্পর্কে উত্তর তৈরি করতে ব্যবহৃত পর্যালোচনার কিছু অংশ।

JSON উপস্থাপনা
{
  "reviewSnippets": [
    {
      object (ReviewSnippet)
    }
  ]
}

পর্যালোচনার অংশবিশেষ

Google Maps-এ একটি নির্দিষ্ট স্থানের বৈশিষ্ট্য সম্পর্কে একটি প্রশ্নের উত্তর দেয় এমন একটি ব্যবহারকারীর পর্যালোচনার স্নিপেটকে ধারণ করে।

ক্ষেত্র
reviewId string

পর্যালোচনা স্নিপেটের আইডি।

googleMapsUri string

গুগল ম্যাপে ব্যবহারকারীর পর্যালোচনার সাথে সঙ্গতিপূর্ণ একটি লিঙ্ক।

title string

পর্যালোচনার শিরোনাম।

JSON উপস্থাপনা
{
  "reviewId": string,
  "googleMapsUri": string,
  "title": string
}

গ্রাউন্ডিংসাপোর্ট

গ্রাউন্ডিং সাপোর্ট।

ক্ষেত্র
groundingChunkIndices[] integer

ঐচ্ছিক। দাবির সাথে সম্পর্কিত উদ্ধৃতিগুলি নির্দিষ্ট করে সূচকগুলির একটি তালিকা ( response.candidate.grounding_metadata তে 'grounding_chunk' তে)। উদাহরণস্বরূপ [1,3,4] এর অর্থ হল grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] হল দাবির সাথে সম্পর্কিত পুনরুদ্ধার করা সামগ্রী। যদি প্রতিক্রিয়াটি স্ট্রিমিং হয়, তাহলে groundingChunkIndices সমস্ত প্রতিক্রিয়ার সূচকগুলিকে নির্দেশ করে। সমস্ত প্রতিক্রিয়া থেকে গ্রাউন্ডিং অংশগুলি সংগ্রহ করা ক্লায়েন্টের দায়িত্ব (একই ক্রম বজায় রেখে)।

confidenceScores[] number

ঐচ্ছিক। সাপোর্ট রেফারেন্সের কনফিডেন্স স্কোর। ০ থেকে ১ এর মধ্যে। ১ হল সবচেয়ে কনফিডেন্ট। এই তালিকার আকার অবশ্যই গ্রাউন্ডিংচাঙ্কইন্ডিসের সমান হতে হবে।

segment object ( Segment )

এই সহায়তাটি যে কন্টেন্টের অন্তর্গত তার অংশ।

JSON উপস্থাপনা
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

অংশ

বিষয়বস্তুর অংশ।

ক্ষেত্র
partIndex integer

একটি Part অবজেক্টের প্যারেন্ট কন্টেন্ট অবজেক্টের মধ্যে তার ইনডেক্স।

startIndex integer

প্রদত্ত অংশে শুরুর সূচক, বাইটে পরিমাপ করা। অংশের শুরু থেকে অফসেট, অন্তর্ভুক্ত, শূন্য থেকে শুরু।

endIndex integer

প্রদত্ত অংশের শেষ সূচক, বাইটে পরিমাপ করা হয়েছে। অংশের শুরু থেকে অফসেট, একচেটিয়া, শূন্য থেকে শুরু।

text string

উত্তর থেকে অংশটির সাথে সম্পর্কিত টেক্সট।

JSON উপস্থাপনা
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

পুনরুদ্ধার মেটাডেটা

গ্রাউন্ডিং প্রবাহে পুনরুদ্ধার সম্পর্কিত মেটাডেটা।

ক্ষেত্র
googleSearchDynamicRetrievalScore number

ঐচ্ছিক। গুগল সার্চ থেকে পাওয়া তথ্য প্রম্পটের উত্তর দিতে কতটা সাহায্য করতে পারে তা নির্দেশ করে এমন স্কোর। স্কোরটি [0, 1] পরিসরে, যেখানে 0 হল সবচেয়ে কম সম্ভাবনা এবং 1 হল সবচেয়ে বেশি সম্ভাবনা। এই স্কোরটি কেবল তখনই পূরণ করা হয় যখন গুগল সার্চ গ্রাউন্ডিং এবং ডায়নামিক রিট্রিভাল সক্ষম করা থাকে। গুগল সার্চ ট্রিগার করা হবে কিনা তা নির্ধারণ করার জন্য এটি থ্রেশহোল্ডের সাথে তুলনা করা হবে।

JSON উপস্থাপনা
{
  "googleSearchDynamicRetrievalScore": number
}

লগপ্রবসফলাফল

লগপ্রব ফলাফল

ক্ষেত্র
topCandidates[] object ( TopCandidates )

দৈর্ঘ্য = ডিকোডিং ধাপের মোট সংখ্যা।

chosenCandidates[] object ( Candidate )

দৈর্ঘ্য = ডিকোডিং ধাপের মোট সংখ্যা। নির্বাচিত প্রার্থীরা শীর্ষ প্রার্থীদের মধ্যে থাকতেও পারেন, নাও থাকতে পারেন।

logProbabilitySum number

সমস্ত টোকেনের জন্য লগ সম্ভাব্যতার যোগফল।

JSON উপস্থাপনা
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ],
  "logProbabilitySum": number
}

শীর্ষ প্রার্থীরা

প্রতিটি ডিকোডিং ধাপে সর্বোচ্চ লগ সম্ভাব্যতা সম্পন্ন প্রার্থী।

ক্ষেত্র
candidates[] object ( Candidate )

লগ সম্ভাব্যতা অনুসারে অবরোহ ক্রমে সাজানো হয়েছে।

JSON উপস্থাপনা
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

প্রার্থী

লগপ্রবস টোকেন এবং স্কোরের জন্য প্রার্থী।

ক্ষেত্র
token string

প্রার্থীর টোকেন স্ট্রিং মান।

tokenId integer

প্রার্থীর টোকেন আইডি মান।

logProbability number

প্রার্থীর লগ সম্ভাব্যতা।

JSON উপস্থাপনা
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

UrlContextমেটাডেটা

ইউআরএল প্রসঙ্গ পুনরুদ্ধার টুলের সাথে সম্পর্কিত মেটাডেটা।

ক্ষেত্র
urlMetadata[] object ( UrlMetadata )

ইউআরএল প্রসঙ্গের তালিকা।

JSON উপস্থাপনা
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}

ইউআরএল মেটাডেটা

একটি একক URL পুনরুদ্ধারের প্রসঙ্গ।

ক্ষেত্র
retrievedUrl string

টুলটি দ্বারা url পুনরুদ্ধার করা হয়েছে।

urlRetrievalStatus enum ( UrlRetrievalStatus )

URL পুনরুদ্ধারের অবস্থা।

JSON উপস্থাপনা
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}

ইউআরএল পুনরুদ্ধারের অবস্থা

URL পুনরুদ্ধারের অবস্থা।

এনামস
URL_RETRIEVAL_STATUS_UNSPECIFIED ডিফল্ট মান। এই মানটি অব্যবহৃত।
URL_RETRIEVAL_STATUS_SUCCESS ইউআরএল পুনরুদ্ধার সফল হয়েছে।
URL_RETRIEVAL_STATUS_ERROR ত্রুটির কারণে URL পুনরুদ্ধার ব্যর্থ হয়েছে।
URL_RETRIEVAL_STATUS_PAYWALL কন্টেন্টটি পেওয়ালের পিছনে থাকায় ইউআরএল পুনরুদ্ধার করা যায়নি।
URL_RETRIEVAL_STATUS_UNSAFE ইউআরএল পুনরুদ্ধার ব্যর্থ হয়েছে কারণ সামগ্রীটি অনিরাপদ।

উদ্ধৃতি মেটাডেটা

কোনও কন্টেন্টের উৎস বৈশিষ্ট্যের সংগ্রহ।

ক্ষেত্র
citationSources[] object ( CitationSource )

নির্দিষ্ট উত্তরের জন্য উৎসের উদ্ধৃতি।

JSON উপস্থাপনা
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}

উদ্ধৃতি উৎস

একটি নির্দিষ্ট প্রতিক্রিয়ার একটি অংশের জন্য একটি উৎসের উদ্ধৃতি।

ক্ষেত্র
startIndex integer

ঐচ্ছিক। এই উৎসের সাথে সম্পর্কিত প্রতিক্রিয়ার অংশের শুরু।

সূচকটি সেগমেন্টের শুরু নির্দেশ করে, যা বাইটে পরিমাপ করা হয়।

endIndex integer

ঐচ্ছিক। অ্যাট্রিবিউটেড সেগমেন্টের শেষে, এক্সক্লুসিভ।

uri string

ঐচ্ছিক। টেক্সটের একটি অংশের উৎস হিসেবে চিহ্নিত URI।

license string

ঐচ্ছিক। গিটহাব প্রকল্পের লাইসেন্স যা সেগমেন্টের উৎস হিসেবে চিহ্নিত।

কোড উদ্ধৃতিগুলির জন্য লাইসেন্সের তথ্য প্রয়োজন।

JSON উপস্থাপনা
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}

জেনারেশন কনফিগ

মডেল জেনারেশন এবং আউটপুটগুলির জন্য কনফিগারেশন বিকল্পগুলি। প্রতিটি মডেলের জন্য সমস্ত প্যারামিটার কনফিগারযোগ্য নয়।

ক্ষেত্র
stopSequences[] string

ঐচ্ছিক। অক্ষরের ক্রমগুলির সেট (সর্বোচ্চ ৫) যা আউটপুট তৈরি বন্ধ করবে। যদি নির্দিষ্ট করা থাকে, তাহলে stop_sequence এর প্রথম উপস্থিতিতে API বন্ধ হয়ে যাবে। স্টপ ক্রমটি প্রতিক্রিয়ার অংশ হিসাবে অন্তর্ভুক্ত করা হবে না।

responseMimeType string

ঐচ্ছিক। জেনারেট করা ক্যান্ডিডেট টেক্সটের MIME টাইপ। সমর্থিত MIME টাইপগুলি হল: text/plain : (ডিফল্ট) টেক্সট আউটপুট। application/json : রেসপন্স ক্যান্ডিডেটগুলিতে JSON রেসপন্স। text/x.enum : রেসপন্স ক্যান্ডিডেটগুলিতে স্ট্রিং রেসপন্স হিসেবে ENUM। সমস্ত সমর্থিত টেক্সট MIME টাইপের তালিকার জন্য ডক্স দেখুন।

responseSchema object ( Schema )

ঐচ্ছিক। জেনারেট করা ক্যান্ডিডেট টেক্সটের আউটপুট স্কিমা। স্কিমাগুলিকে অবশ্যই OpenAPI স্কিমার একটি উপসেট হতে হবে এবং এটি অবজেক্ট, প্রিমিটিভ বা অ্যারে হতে পারে।

যদি সেট করা থাকে, তাহলে একটি সামঞ্জস্যপূর্ণ responseMimeType ও সেট করতে হবে। সামঞ্জস্যপূর্ণ MIME প্রকার: application/json : JSON প্রতিক্রিয়ার জন্য স্কিমা। আরও বিস্তারিত জানার জন্য JSON টেক্সট জেনারেশন গাইড দেখুন।

_responseJsonSchema value ( Value format)

ঐচ্ছিক। জেনারেট করা প্রতিক্রিয়ার আউটপুট স্কিমা। এটি responseSchema এর একটি বিকল্প যা JSON স্কিমা গ্রহণ করে।

যদি সেট করা থাকে, তাহলে responseSchema বাদ দিতে হবে, কিন্তু responseMimeType প্রয়োজন।

সম্পূর্ণ JSON স্কিমা পাঠানো যেতে পারে, তবে সমস্ত বৈশিষ্ট্য সমর্থিত নয়। বিশেষ করে, শুধুমাত্র নিম্নলিখিত বৈশিষ্ট্যগুলি সমর্থিত:

  • $id
  • $defs
  • $ref
  • $anchor
  • type
  • format
  • title
  • description
  • enum (স্ট্রিং এবং সংখ্যার জন্য)
  • items
  • prefixItems
  • minItems
  • maxItems
  • minimum
  • maximum
  • anyOf
  • oneOf ( anyOf মতোই ব্যাখ্যা করা হয়েছে)
  • properties
  • additionalProperties
  • required

অ-মানক propertyOrdering সম্পত্তিও সেট করা যেতে পারে।

চক্রীয় রেফারেন্সগুলি সীমিত পরিমাণে আনরোল করা হয় এবং তাই, শুধুমাত্র অ-প্রয়োজনীয় বৈশিষ্ট্যের মধ্যেই ব্যবহার করা যেতে পারে। (Nullable বৈশিষ্ট্য যথেষ্ট নয়।) যদি $ref একটি সাব-স্কিমাতে সেট করা থাকে, তাহলে $ হিসাবে শুরু হওয়া বৈশিষ্ট্যগুলি ছাড়া অন্য কোনও বৈশিষ্ট্য সেট করা যাবে না।

responseJsonSchema value ( Value format)

Optional. An internal detail. Use responseJsonSchema rather than this field.

responseModalities[] enum ( Modality )

Optional. The requested modalities of the response. Represents the set of modalities that the model can return, and should be expected in the response. This is an exact match to the modalities of the response.

A model may have multiple combinations of supported modalities. If the requested modalities do not match any of the supported combinations, an error will be returned.

An empty list is equivalent to requesting only text.

candidateCount integer

Optional. Number of generated responses to return. If unset, this will default to 1. Please note that this doesn't work for previous generation models (Gemini 1.0 family)

maxOutputTokens integer

Optional. The maximum number of tokens to include in a response candidate.

Note: The default value varies by model, see the Model.output_token_limit attribute of the Model returned from the getModel function.

temperature number

Optional. Controls the randomness of the output.

Note: The default value varies by model, see the Model.temperature attribute of the Model returned from the getModel function.

Values can range from [0.0, 2.0].

topP number

Optional. The maximum cumulative probability of tokens to consider when sampling.

The model uses combined Top-k and Top-p (nucleus) sampling.

Tokens are sorted based on their assigned probabilities so that only the most likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while Nucleus sampling limits the number of tokens based on the cumulative probability.

Note: The default value varies by Model and is specified by the Model.top_p attribute returned from the getModel function. An empty topK attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.

topK integer

Optional. The maximum number of tokens to consider when sampling.

Gemini models use Top-p (nucleus) sampling or a combination of Top-k and nucleus sampling. Top-k sampling considers the set of topK most probable tokens. Models running with nucleus sampling don't allow topK setting.

Note: The default value varies by Model and is specified by the Model.top_p attribute returned from the getModel function. An empty topK attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.

seed integer

Optional. Seed used in decoding. If not set, the request uses a randomly generated seed.

presencePenalty number

Optional. Presence penalty applied to the next token's logprobs if the token has already been seen in the response.

This penalty is binary on/off and not dependant on the number of times the token is used (after the first). Use frequencyPenalty for a penalty that increases with each use.

A positive penalty will discourage the use of tokens that have already been used in the response, increasing the vocabulary.

A negative penalty will encourage the use of tokens that have already been used in the response, decreasing the vocabulary.

frequencyPenalty number

Optional. Frequency penalty applied to the next token's logprobs, multiplied by the number of times each token has been seen in the respponse so far.

A positive penalty will discourage the use of tokens that have already been used, proportional to the number of times the token has been used: The more a token is used, the more difficult it is for the model to use that token again increasing the vocabulary of responses.

Caution: A negative penalty will encourage the model to reuse tokens proportional to the number of times the token has been used. Small negative values will reduce the vocabulary of a response. Larger negative values will cause the model to start repeating a common token until it hits the maxOutputTokens limit.

responseLogprobs boolean

Optional. If true, export the logprobs results in response.

logprobs integer

Optional. Only valid if responseLogprobs=True . This sets the number of top logprobs to return at each decoding step in the Candidate.logprobs_result . The number must be in the range of [0, 20].

enableEnhancedCivicAnswers boolean

Optional. Enables enhanced civic answers. It may not be available for all models.

speechConfig object ( SpeechConfig )

Optional. The speech generation config.

thinkingConfig object ( ThinkingConfig )

Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking.

imageConfig object ( ImageConfig )

Optional. Config for image generation. An error will be returned if this field is set for models that don't support these config options.

mediaResolution enum ( MediaResolution )

Optional. If specified, the media resolution specified will be used.

JSON উপস্থাপনা
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "_responseJsonSchema": value,
  "responseJsonSchema": value,
  "responseModalities": [
    enum (Modality)
  ],
  "candidateCount": integer,
  "maxOutputTokens": integer,
  "temperature": number,
  "topP": number,
  "topK": integer,
  "seed": integer,
  "presencePenalty": number,
  "frequencyPenalty": number,
  "responseLogprobs": boolean,
  "logprobs": integer,
  "enableEnhancedCivicAnswers": boolean,
  "speechConfig": {
    object (SpeechConfig)
  },
  "thinkingConfig": {
    object (ThinkingConfig)
  },
  "imageConfig": {
    object (ImageConfig)
  },
  "mediaResolution": enum (MediaResolution)
}

Modality

Supported modalities of the response.

এনামস
MODALITY_UNSPECIFIED ডিফল্ট মান।
TEXT Indicates the model should return text.
IMAGE Indicates the model should return images.
AUDIO Indicates the model should return audio.

SpeechConfig

The speech generation config.

ক্ষেত্র
voiceConfig object ( VoiceConfig )

The configuration in case of single-voice output.

multiSpeakerVoiceConfig object ( MultiSpeakerVoiceConfig )

Optional. The configuration for the multi-speaker setup. It is mutually exclusive with the voiceConfig field.

languageCode string

Optional. Language code (in BCP 47 format, eg "en-US") for speech synthesis.

Valid values are: 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, and th-TH.

JSON উপস্থাপনা
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}

VoiceConfig

The configuration for the voice to use.

ক্ষেত্র
voice_config Union type
The configuration for the speaker to use. voice_config can be only one of the following:
prebuiltVoiceConfig object ( PrebuiltVoiceConfig )

The configuration for the prebuilt voice to use.

JSON উপস্থাপনা
{

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

PrebuiltVoiceConfig

The configuration for the prebuilt speaker to use.

ক্ষেত্র
voiceName string

The name of the preset voice to use.

JSON উপস্থাপনা
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

The configuration for the multi-speaker setup.

ক্ষেত্র
speakerVoiceConfigs[] object ( SpeakerVoiceConfig )

Required. All the enabled speaker voices.

JSON উপস্থাপনা
{
  "speakerVoiceConfigs": [
    {
      object (SpeakerVoiceConfig)
    }
  ]
}

SpeakerVoiceConfig

The configuration for a single speaker in a multi speaker setup.

ক্ষেত্র
speaker string

Required. The name of the speaker to use. Should be the same as in the prompt.

voiceConfig object ( VoiceConfig )

Required. The configuration for the voice to use.

JSON উপস্থাপনা
{
  "speaker": string,
  "voiceConfig": {
    object (VoiceConfig)
  }
}

ThinkingConfig

Config for thinking features.

ক্ষেত্র
includeThoughts boolean

Indicates whether to include thoughts in the response. If true, thoughts are returned only when available.

thinkingBudget integer

The number of thoughts tokens that the model should generate.

thinkingLevel enum ( ThinkingLevel )

Optional. Controls the maximum depth of the model's internal reasoning process before it produces a response. If not specified, the default is HIGH. Recommended for Gemini 3 or later models. Use with earlier models results in an error.

JSON উপস্থাপনা
{
  "includeThoughts": boolean,
  "thinkingBudget": integer,
  "thinkingLevel": enum (ThinkingLevel)
}

ThinkingLevel

Allow user to specify how much to think using enum instead of integer budget.

এনামস
THINKING_LEVEL_UNSPECIFIED ডিফল্ট মান।
MINIMAL Little to no thinking.
LOW Low thinking level.
MEDIUM Medium thinking level.
HIGH High thinking level.

ImageConfig

Config for image generation features.

ক্ষেত্র
aspectRatio string

Optional. The aspect ratio of the image to generate. Supported aspect ratios: 1:1 , 2:3 , 3:2 , 3:4 , 4:3 , 4:5 , 5:4 , 9:16 , 16:9 , or 21:9 .

If not specified, the model will choose a default aspect ratio based on any reference images provided.

imageSize string

Optional. Specifies the size of generated images. Supported values are 1K , 2K , 4K . If not specified, the model will use default value 1K .

JSON উপস্থাপনা
{
  "aspectRatio": string,
  "imageSize": string
}

MediaResolution

Media resolution for the input media.

এনামস
MEDIA_RESOLUTION_UNSPECIFIED Media resolution has not been set.
MEDIA_RESOLUTION_LOW Media resolution set to low (64 tokens).
MEDIA_RESOLUTION_MEDIUM Media resolution set to medium (256 tokens).
MEDIA_RESOLUTION_HIGH Media resolution set to high (zoomed reframing with 256 tokens).

HarmCategory

The category of a rating.

These categories cover various kinds of harms that developers may wish to adjust.

এনামস
HARM_CATEGORY_UNSPECIFIED Category is unspecified.
HARM_CATEGORY_DEROGATORY PaLM - Negative or harmful comments targeting identity and/or protected attribute.
HARM_CATEGORY_TOXICITY PaLM - Content that is rude, disrespectful, or profane.
HARM_CATEGORY_VIOLENCE PaLM - Describes scenarios depicting violence against an individual or group, or general descriptions of gore.
HARM_CATEGORY_SEXUAL PaLM - Contains references to sexual acts or other lewd content.
HARM_CATEGORY_MEDICAL PaLM - Promotes unchecked medical advice.
HARM_CATEGORY_DANGEROUS PaLM - Dangerous content that promotes, facilitates, or encourages harmful acts.
HARM_CATEGORY_HARASSMENT Gemini - Harassment content.
HARM_CATEGORY_HATE_SPEECH Gemini - Hate speech and content.
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini - Sexually explicit content.
HARM_CATEGORY_DANGEROUS_CONTENT Gemini - Dangerous content.
HARM_CATEGORY_CIVIC_INTEGRITY

Gemini - Content that may be used to harm civic integrity. DEPRECATED: use enableEnhancedCivicAnswers instead.

ModalityTokenCount

Represents token counting info for a single modality.

ক্ষেত্র
modality enum ( Modality )

The modality associated with this token count.

tokenCount integer

Number of tokens.

JSON উপস্থাপনা
{
  "modality": enum (Modality),
  "tokenCount": integer
}

Modality

Content Part modality

এনামস
MODALITY_UNSPECIFIED Unspecified modality.
TEXT Plain text.
IMAGE ছবি।
VIDEO ভিডিও।
AUDIO অডিও।
DOCUMENT Document, eg PDF.

SafetyRating

Safety rating for a piece of content.

The safety rating contains the category of harm and the harm probability level in that category for a piece of content. Content is classified for safety across a number of harm categories and the probability of the harm classification is included here.

ক্ষেত্র
category enum ( HarmCategory )

Required. The category for this rating.

probability enum ( HarmProbability )

Required. The probability of harm for this content.

blocked boolean

Was this content blocked because of this rating?

JSON উপস্থাপনা
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}

HarmProbability

The probability that a piece of content is harmful.

The classification system gives the probability of the content being unsafe. This does not indicate the severity of harm for a piece of content.

এনামস
HARM_PROBABILITY_UNSPECIFIED Probability is unspecified.
NEGLIGIBLE Content has a negligible chance of being unsafe.
LOW Content has a low chance of being unsafe.
MEDIUM Content has a medium chance of being unsafe.
HIGH Content has a high chance of being unsafe.

SafetySetting

Safety setting, affecting the safety-blocking behavior.

Passing a safety setting for a category changes the allowed probability that content is blocked.

ক্ষেত্র
category enum ( HarmCategory )

Required. The category for this setting.

threshold enum ( HarmBlockThreshold )

Required. Controls the probability threshold at which harm is blocked.

JSON উপস্থাপনা
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

HarmBlockThreshold

Block at and beyond a specified harm probability.

এনামস
HARM_BLOCK_THRESHOLD_UNSPECIFIED Threshold is unspecified.
BLOCK_LOW_AND_ABOVE Content with NEGLIGIBLE will be allowed.
BLOCK_MEDIUM_AND_ABOVE Content with NEGLIGIBLE and LOW will be allowed.
BLOCK_ONLY_HIGH Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed.
BLOCK_NONE All content will be allowed.
OFF Turn off the safety filter.