Generating content

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

পদ্ধতি: models.generateContent

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

শেষবিন্দু

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

পাথ প্যারামিটার

model string

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

বিন্যাস: models/{model} । এটি ফর্ম models/{model} লাগে।

শরীরের অনুরোধ

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

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

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

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

tools[] object ( Tool )

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

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

toolConfig object ( ToolConfig )

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

safetySettings[] object ( SafetySetting )

ঐচ্ছিক। অনিরাপদ বিষয়বস্তু ব্লক করার জন্য অনন্য SafetySetting দৃষ্টান্তের একটি তালিকা।

এটি GenerateContentRequest.contents এবং GenerateContentResponse.candidates এ প্রয়োগ করা হবে। প্রতিটি SafetyCategory প্রকারের জন্য একাধিক সেটিং থাকা উচিত নয়৷ এপিআই এই সেটিংস দ্বারা নির্ধারিত থ্রেশহোল্ড পূরণ করতে ব্যর্থ যে কোনো বিষয়বস্তু এবং প্রতিক্রিয়া ব্লক করবে। এই তালিকাটি সেফটিসেটিংসে নির্দিষ্ট করা প্রতিটি 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);
model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[{"text": "Write a story about a magic backpack."}]
        }]
       }' 2> /dev/null
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

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

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

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

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

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

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

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

client = genai.Client()
organ = PIL.Image.open(media / "organ.jpg")
response = client.models.generate_content(
    model="gemini-2.0-flash", contents=["Tell me about this instrument", organ]
)
print(response.text)
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

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

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

imgData, err := os.ReadFile(filepath.Join(testDataDir, "organ.jpg"))
if err != nil {
	log.Fatal(err)
}

resp, err := model.GenerateContent(ctx,
	genai.Text("Tell me about this instrument"),
	genai.ImageData("jpeg", imgData))
if err != nil {
	log.Fatal(err)
}

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

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

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d "@$TEMP_JSON" 2> /dev/null
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

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

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

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

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

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

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

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

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

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

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

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

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

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

client = genai.Client()
sample_audio = client.files.upload(file=media / "sample.mp3")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
print(response.text)
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

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

const response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: [
    createUserContent([
      "Give me a summary of this audio file.",
      createPartFromUri(audio.uri, audio.mimeType),
    ]),
  ],
});
console.log(response.text);
# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json
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=}")

# Videos need to be processed before you can use them.
while myfile.state.name == "PROCESSING":
    print("processing video...")
    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);
model := client.GenerativeModel("gemini-1.5-flash")

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "earth.mp4"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

// Videos need to be processed before you can use them.
for file.State == genai.FileStateProcessing {
	log.Printf("processing %s", file.Name)
	time.Sleep(5 * time.Second)
	var err error
	if file, err = client.GetFile(ctx, file.Name); err != nil {
		log.Fatal(err)
	}
}
if file.State != genai.FileStateActive {
	log.Fatalf("uploaded file has state %s, not active", file.State)
}

resp, err := model.GenerateContent(ctx,
	genai.Text("Describe this video clip"),
	genai.FileData{URI: file.URI})
if err != nil {
	log.Fatal(err)
}

printResponse(resp)
# 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=}")
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);
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()

cs.History = []*genai.Content{
	{
		Parts: []genai.Part{
			genai.Text("Hello, I have 2 dogs in my house."),
		},
		Role: "user",
	},
	{
		Parts: []genai.Part{
			genai.Text("Great to meet you. What would you like to know?"),
		},
		Role: "model",
	},
}

res, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))
if err != nil {
	log.Fatal(err)
}
printResponse(res)
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role":"user",
         "parts":[{
           "text": "Hello"}]},
        {"role": "model",
         "parts":[{
           "text": "Great to meet you. What would you like to know?"}]},
        {"role":"user",
         "parts":[{
           "text": "I have two dogs in my house. How many paws are in my house?"}]},
      ]
    }' 2> /dev/null | grep "text"
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

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

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

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

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

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

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

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

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

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

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

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

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

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

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);
পাইথন Node.js
from google import genai
from google.genai import types

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

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

response = client.models.generate_content(
    model=model_name,
    contents="Please summarize this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-1.5-flash-001";

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

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

const response = await ai.models.generateContent({
  model: modelName,
  contents: "Please summarize this transcript",
  config: { cachedContent: cache.name },
});
console.log("Response text:", response.text);
পাইথন
# With Gemini 2 we're launching a new SDK. See the following doc for details.
# https://ai.google.dev/gemini-api/docs/migrate
from google import genai
from google.genai import types
from typing_extensions import TypedDict

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

client = genai.Client()
result = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="List a few popular cookie recipes.",
    config=types.GenerateContentConfig(
        response_mime_type="application/json", response_schema=list[Recipe]
    ),
)
print(result)
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: "List a few popular cookie recipes.",
  config: {
    responseMimeType: "application/json",
    responseSchema: {
      type: "array",
      items: {
        type: "object",
        properties: {
          recipeName: { type: "string" },
          ingredients: { type: "array", items: { type: "string" } },
        },
        required: ["recipeName", "ingredients"],
      },
    },
  },
});
console.log(response.text);
model := client.GenerativeModel("gemini-1.5-pro-latest")
// Ask the model to respond with JSON.
model.ResponseMIMEType = "application/json"
// Specify the schema.
model.ResponseSchema = &genai.Schema{
	Type:  genai.TypeArray,
	Items: &genai.Schema{Type: genai.TypeString},
}
resp, err := model.GenerateContent(ctx, genai.Text("List a few popular cookie recipes using this JSON schema."))
if err != nil {
	log.Fatal(err)
}
for _, part := range resp.Candidates[0].Content.Parts {
	if txt, ok := part.(genai.Text); ok {
		var recipes []string
		if err := json.Unmarshal([]byte(txt), &recipes); err != nil {
			log.Fatal(err)
		}
		fmt.Println(recipes)
	}
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "contents": [{
      "parts":[
        {"text": "List 5 popular cookie recipes"}
        ]
    }],
    "generationConfig": {
        "response_mime_type": "application/json",
        "response_schema": {
          "type": "ARRAY",
          "items": {
            "type": "OBJECT",
            "properties": {
              "recipe_name": {"type":"STRING"},
            }
          }
        }
    }
}' 2> /dev/null | head
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-pro",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey,
        generationConfig = generationConfig {
            responseMimeType = "application/json"
            responseSchema = Schema(
                name = "recipes",
                description = "List of recipes",
                type = FunctionType.ARRAY,
                items = Schema(
                    name = "recipe",
                    description = "A recipe",
                    type = FunctionType.OBJECT,
                    properties = mapOf(
                        "recipeName" to Schema(
                            name = "recipeName",
                            description = "Name of the recipe",
                            type = FunctionType.STRING,
                            nullable = false
                        ),
                    ),
                    required = listOf("recipeName")
                ),
            )
        })

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

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

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

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

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

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

GenerationConfig generationConfig = configBuilder.build();

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

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

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

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

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

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-pro-exp-02-05",
    contents=(
        "Write and execute code that calculates the sum of the first 50 prime numbers. "
        "Ensure that only the executable code and its resulting output are generated."
    ),
)
# Each part may contain text, executable code, or an execution result.
for part in response.candidates[0].content.parts:
    print(part, "\n")

print("-" * 80)
# The .text accessor concatenates the parts into a markdown-formatted text.
print("\n", response.text)

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

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

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

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

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

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

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

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

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

client = genai.Client()

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

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

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

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

# Create a chat session; function calling (via tools) is enabled in the config.
chat = client.chats.create(
    model="gemini-2.0-flash",
    config=types.GenerateContentConfig(tools=[add, subtract, multiply, divide]),
)
response = chat.send_message(
    message="I have 57 cats, each owns 44 mittens, how many mittens is that in total?"
)
print(response.text)
  // Make sure to include the following import:
  // import {GoogleGenAI} from '@google/genai';
  const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    "contents": {
      "role": "user",
      "parts": {
        "text": "Turn on the lights please."
      }
    }
  }
') 2>/dev/null |sed -n '/"content"/,/"finishReason"/p'
fun multiply(a: Double, b: Double) = a * b

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

val usableFunctions = listOf(multiplyDefinition)

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

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

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

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

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

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

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

let chat = generativeModel.startChat()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Tell me a story about a magic backpack.",
    config=types.GenerateContentConfig(
        candidate_count=1,
        stop_sequences=["x"],
        max_output_tokens=20,
        temperature=1.0,
    ),
)
print(response.text)
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

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

console.log(response.text);
model := client.GenerativeModel("gemini-1.5-pro-latest")
model.SetTemperature(0.9)
model.SetTopP(0.5)
model.SetTopK(20)
model.SetMaxOutputTokens(100)
model.SystemInstruction = genai.NewUserContent(genai.Text("You are Yoda from Star Wars."))
model.ResponseMIMEType = "application/json"
resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
if err != nil {
	log.Fatal(err)
}
printResponse(resp)
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
        "contents": [{
            "parts":[
                {"text": "Explain how AI works"}
            ]
        }],
        "generationConfig": {
            "stopSequences": [
                "Title"
            ],
            "temperature": 1.0,
            "maxOutputTokens": 800,
            "topP": 0.8,
            "topK": 10
        }
    }'  2> /dev/null | grep "text"
val config = generationConfig {
  temperature = 0.9f
  topK = 16
  topP = 0.1f
  maxOutputTokens = 200
  stopSequences = listOf("red")
}

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

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

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

GenerationConfig generationConfig = configBuilder.build();

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

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

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

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

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

  try {
    console.log("Generated text:", response.text);
  } catch (error) {
    console.log("No information generated by the model.");
  }
  console.log("Safety ratings:", response.candidates[0].safetyRatings);
  return response;
}
model := client.GenerativeModel("gemini-1.5-flash")
model.SafetySettings = []*genai.SafetySetting{
	{
		Category:  genai.HarmCategoryDangerousContent,
		Threshold: genai.HarmBlockLowAndAbove,
	},
	{
		Category:  genai.HarmCategoryHarassment,
		Threshold: genai.HarmBlockMediumAndAbove,
	},
}
resp, err := model.GenerateContent(ctx, genai.Text("I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them."))
if err != nil {
	log.Fatal(err)
}
printResponse(resp)
echo '{
    "safetySettings": [
        {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"},
        {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}
    ],
    "contents": [{
        "parts":[{
            "text": "'I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them.'"}]}]}' > request.json

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d @request.json 2> /dev/null
val harassmentSafety = SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH)

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

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

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

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

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

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

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

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Good morning! How are you?",
    config=types.GenerateContentConfig(
        system_instruction="You are a cat. Your name is Neko."
    ),
)
print(response.text)
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: "Good morning! How are you?",
  config: {
    systemInstruction: "You are a cat. Your name is Neko.",
  },
});
console.log(response.text);
model := client.GenerativeModel("gemini-1.5-flash")
model.SystemInstruction = genai.NewUserContent(genai.Text("You are a cat. Your name is Neko."))
resp, err := model.GenerateContent(ctx, genai.Text("Good morning! How are you?"))
if err != nil {
	log.Fatal(err)
}
printResponse(resp)
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "system_instruction": {
    "parts":
      { "text": "You are a cat. Your name is Neko."}},
    "contents": {
      "parts": {
        "text": "Hello there"}}}'
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        systemInstruction = content { text("You are a cat. Your name is Neko.") },
    )
let generativeModel =
  GenerativeModel(
    // Specify a model that supports system instructions, like a Gemini 1.5 model
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    systemInstruction: ModelContent(role: "system", parts: "You are a cat. Your name is Neko.")
  )
// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
  systemInstruction: Content.system('You are a cat. Your name is Neko.'),
);
final prompt = 'Good morning! How are you?';

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

প্রতিক্রিয়া শরীর

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

পদ্ধতি: models.streamGenerateContent

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

শেষবিন্দু

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

পাথ প্যারামিটার

model string

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

বিন্যাস: models/{model} । এটি ফর্ম models/{model} লাগে।

শরীরের অনুরোধ

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

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

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

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

tools[] object ( Tool )

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

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

toolConfig object ( ToolConfig )

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

safetySettings[] object ( SafetySetting )

ঐচ্ছিক। অনিরাপদ বিষয়বস্তু ব্লক করার জন্য অনন্য SafetySetting দৃষ্টান্তের একটি তালিকা।

এটি GenerateContentRequest.contents এবং GenerateContentResponse.candidates এ প্রয়োগ করা হবে। প্রতিটি SafetyCategory প্রকারের জন্য একাধিক সেটিং থাকা উচিত নয়৷ এপিআই এই সেটিংস দ্বারা নির্ধারিত থ্রেশহোল্ড পূরণ করতে ব্যর্থ যে কোনো বিষয়বস্তু এবং প্রতিক্রিয়া ব্লক করবে। এই তালিকাটি সেফটিসেটিংসে নির্দিষ্ট করা প্রতিটি 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;
}
model := client.GenerativeModel("gemini-1.5-flash")
iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
	resp, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	printResponse(resp)
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \
        -H 'Content-Type: application/json' \
        --no-buffer \
        -d '{ "contents":[{"parts":[{"text": "Write a story about a magic backpack."}]}]}'
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

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

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

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

      @Override
      public void onSubscribe(Subscription s) {
        s.request(Long.MAX_VALUE);
      }
    });
from google import genai
import PIL.Image

client = genai.Client()
organ = PIL.Image.open(media / "organ.jpg")
response = client.models.generate_content_stream(
    model="gemini-2.0-flash", contents=["Tell me about this instrument", organ]
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

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

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

imgData, err := os.ReadFile(filepath.Join(testDataDir, "organ.jpg"))
if err != nil {
	log.Fatal(err)
}
iter := model.GenerateContentStream(ctx,
	genai.Text("Tell me about this instrument"),
	genai.ImageData("jpeg", imgData))
for {
	resp, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	printResponse(resp)
}
cat > "$TEMP_JSON" << EOF
{
  "contents": [{
    "parts":[
      {"text": "Tell me about this instrument"},
      {
        "inline_data": {
          "mime_type":"image/jpeg",
          "data": "$(cat "$TEMP_B64")"
        }
      }
    ]
  }]
}
EOF

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d "@$TEMP_JSON" 2> /dev/null
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

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

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

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

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

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

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

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

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

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

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

      @Override
      public void onSubscribe(Subscription s) {
        s.request(Long.MAX_VALUE);
      }
    });
পাইথন শেল
from google import genai

client = genai.Client()
sample_audio = client.files.upload(file=media / "sample.mp3")
response = client.models.generate_content_stream(
    model="gemini-2.0-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo
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=}")

# Videos need to be processed before you can use them.
while myfile.state.name == "PROCESSING":
    print("processing video...")
    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;
}
model := client.GenerativeModel("gemini-1.5-flash")

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "earth.mp4"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

iter := model.GenerateContentStream(ctx,
	genai.Text("Describe this video clip"),
	genai.FileData{URI: file.URI})
for {
	resp, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	printResponse(resp)
}
# 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)
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());
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()

cs.History = []*genai.Content{
	{
		Parts: []genai.Part{
			genai.Text("Hello, I have 2 dogs in my house."),
		},
		Role: "user",
	},
	{
		Parts: []genai.Part{
			genai.Text("Great to meet you. What would you like to know?"),
		},
		Role: "model",
	},
}

iter := cs.SendMessageStream(ctx, genai.Text("How many paws are in my house?"))
for {
	resp, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	printResponse(resp)
}
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role":"user",
         "parts":[{
           "text": "Hello"}]},
        {"role": "model",
         "parts":[{
           "text": "Great to meet you. What would you like to know?"}]},
        {"role":"user",
         "parts":[{
           "text": "I have two dogs in my house. How many paws are in my house?"}]},
      ]
    }' 2> /dev/null | grep "text"
// Use streaming with multi-turn conversations (like chat)
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

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

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

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

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

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

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

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

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

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

      @Override
      public void onError(Throwable t) {}

    });

প্রতিক্রিয়া শরীর

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

কন্টেন্ট রেসপন্স তৈরি করুন

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

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

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

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

promptFeedback object ( PromptFeedback )

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

usageMetadata object ( UsageMetadata )

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

modelVersion string

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

JSON প্রতিনিধিত্ব
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string
}

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

GenerateContentRequest.content এ নির্দিষ্ট করা প্রম্পট ফিডব্যাক মেটাডেটার একটি সেট।

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

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

safetyRatings[] object ( SafetyRating )

প্রম্পটের নিরাপত্তার জন্য রেটিং। প্রতি বিভাগে সর্বোচ্চ একটি রেটিং আছে।

JSON প্রতিনিধিত্ব
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

ব্লকরিজন

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

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

প্রার্থী

মডেল থেকে উত্পন্ন একটি প্রতিক্রিয়া প্রার্থী.

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

শুধুমাত্র আউটপুট। উত্পন্ন সামগ্রী মডেল থেকে ফিরে.

finishReason enum ( FinishReason )

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

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

safetyRatings[] object ( SafetyRating )

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

প্রতি বিভাগে সর্বোচ্চ একটি রেটিং আছে।

citationMetadata object ( CitationMetadata )

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

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

tokenCount integer

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

groundingAttributions[] object ( GroundingAttribution )

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

এই ক্ষেত্রটি GenerateAnswer কলের জন্য জনবহুল।

groundingMetadata object ( GroundingMetadata )

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

এই ক্ষেত্রটি GenerateContent কলের জন্য জনবহুল।

avgLogprobs number

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

logprobsResult object ( LogprobsResult )

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

index integer

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

JSON প্রতিনিধিত্ব
{
  "content": {
    object (Content)
  },
  "finishReason": enum (FinishReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ],
  "citationMetadata": {
    object (CitationMetadata)
  },
  "tokenCount": integer,
  "groundingAttributions": [
    {
      object (GroundingAttribution)
    }
  ],
  "groundingMetadata": {
    object (GroundingMetadata)
  },
  "avgLogprobs": number,
  "logprobsResult": {
    object (LogprobsResult)
  },
  "index": integer
}

ফিনিশ রিজন

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

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

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

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

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

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

content object ( Content )

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

JSON প্রতিনিধিত্ব
{
  "sourceId": {
    object (AttributionSourceId)
  },
  "content": {
    object (Content)
  }
}

AttributionSourceId

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

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

একটি ইনলাইন উত্তরণ জন্য শনাক্তকারী.

semanticRetrieverChunk object ( SemanticRetrieverChunk )

শব্দার্থক পুনরুদ্ধারের মাধ্যমে আনা Chunk জন্য শনাক্তকারী।

JSON প্রতিনিধিত্ব
{

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

GroundingPassageId

একটি 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 )

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

retrievalMetadata object ( RetrievalMetadata )

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

JSON প্রতিনিধিত্ব
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  }
}

অনুসন্ধান এন্ট্রিপয়েন্ট

গুগল অনুসন্ধান এন্ট্রি পয়েন্ট.

ক্ষেত্র
renderedContent string

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

sdkBlob string ( bytes format)

ঐচ্ছিক। বেস64 এনকোড করা JSON <সার্চ টার্ম, সার্চ ইউআরএল> টিপলের অ্যারের প্রতিনিধিত্ব করে।

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

JSON প্রতিনিধিত্ব
{
  "renderedContent": string,
  "sdkBlob": string
}

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

গ্রাউন্ডিং খণ্ড.

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

ওয়েব থেকে গ্রাউন্ডিং খণ্ড.

JSON প্রতিনিধিত্ব
{

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

ওয়েব

ওয়েব থেকে খণ্ড.

ক্ষেত্র
uri string

খণ্ডের URI রেফারেন্স।

title string

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

JSON প্রতিনিধিত্ব
{
  "uri": string,
  "title": string
}

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

গ্রাউন্ডিং সমর্থন।

ক্ষেত্র
groundingChunkIndices[] integer

সূচকগুলির একটি তালিকা ('গ্রাউন্ডিং_চঙ্ক'-এ) দাবির সাথে সম্পর্কিত উদ্ধৃতিগুলি নির্দিষ্ট করে৷ উদাহরণস্বরূপ [1,3,4] মানে হল যে গ্রাউন্ডিং_চঙ্ক[1], গ্রাউন্ডিং_চাঙ্ক[3], গ্রাউন্ডিং_চঙ্ক[4] হল দাবির জন্য দায়ী করা পুনরুদ্ধার করা সামগ্রী।

confidenceScores[] number

সমর্থন রেফারেন্সের আত্মবিশ্বাস স্কোর. 0 থেকে 1 পর্যন্ত রেঞ্জ। 1 হল সবচেয়ে আত্মবিশ্বাসী। এই তালিকাটি অবশ্যই গ্রাউন্ডিংচাঙ্ক ইনডিসেসের মতো একই আকারের হতে হবে।

segment object ( Segment )

এই সমর্থনের অন্তর্গত বিষয়বস্তুর সেগমেন্ট।

JSON প্রতিনিধিত্ব
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

সেগমেন্ট

বিষয়বস্তুর সেগমেন্ট।

ক্ষেত্র
partIndex integer

শুধুমাত্র আউটপুট। একটি অংশ বস্তুর সূচী তার মূল বিষয়বস্তু বস্তুর মধ্যে।

startIndex integer

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

endIndex integer

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

text string

শুধুমাত্র আউটপুট। প্রতিক্রিয়া থেকে অংশের সাথে সংশ্লিষ্ট পাঠ্য।

JSON প্রতিনিধিত্ব
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

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

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

ক্ষেত্র
googleSearchDynamicRetrievalScore number

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

JSON প্রতিনিধিত্ব
{
  "googleSearchDynamicRetrievalScore": number
}

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

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

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

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

chosenCandidates[] object ( Candidate )

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

JSON প্রতিনিধিত্ব
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ]
}

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

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

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

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

JSON প্রতিনিধিত্ব
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

প্রার্থী

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

ক্ষেত্র
token string

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

tokenId integer

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

logProbability number

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

JSON প্রতিনিধিত্ব
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

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

বিষয়বস্তুর একটি অংশের জন্য উত্স বৈশিষ্ট্যগুলির একটি সংগ্রহ৷

ক্ষেত্র
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

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

responseMimeType string

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

responseSchema object ( Schema )

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

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

responseModalities[] enum ( Modality )

ঐচ্ছিক। প্রতিক্রিয়ার অনুরোধকৃত পদ্ধতি। মডেলটি ফেরত দিতে পারে এমন পদ্ধতির সেটকে প্রতিনিধিত্ব করে এবং প্রতিক্রিয়ায় আশা করা উচিত। এটি প্রতিক্রিয়ার পদ্ধতির সাথে একটি সঠিক মিল।

একটি মডেলে সমর্থিত পদ্ধতির একাধিক সমন্বয় থাকতে পারে। যদি অনুরোধ করা পদ্ধতিগুলি সমর্থিত সংমিশ্রণগুলির কোনওটির সাথে মেলে না, তবে একটি ত্রুটি ফেরত দেওয়া হবে৷

একটি খালি তালিকা শুধুমাত্র পাঠ্য অনুরোধের সমতুল্য।

candidateCount integer

ঐচ্ছিক। ফিরে আসার জন্য উত্পন্ন প্রতিক্রিয়ার সংখ্যা। সেট না থাকলে, এটি ডিফল্ট 1 হবে। অনুগ্রহ করে মনে রাখবেন যে এটি পূর্ববর্তী প্রজন্মের মডেলগুলির জন্য কাজ করে না (জেমিনি 1.0 পরিবার)

maxOutputTokens integer

ঐচ্ছিক। একটি প্রতিক্রিয়া প্রার্থীর মধ্যে অন্তর্ভুক্ত করার জন্য সর্বাধিক সংখ্যক টোকেন।

দ্রষ্টব্য: মডেল অনুসারে ডিফল্ট মান পরিবর্তিত হয়, getModel ফাংশন থেকে ফিরে আসা Model Model.output_token_limit বৈশিষ্ট্য দেখুন।

temperature number

ঐচ্ছিক। আউটপুটের এলোমেলোতা নিয়ন্ত্রণ করে।

দ্রষ্টব্য: মডেল অনুসারে ডিফল্ট মান পরিবর্তিত হয়, getModel ফাংশন থেকে ফিরে আসা Model Model.temperature বৈশিষ্ট্য দেখুন।

মান [0.0, 2.0] থেকে পরিসীমা হতে পারে।

topP number

ঐচ্ছিক। নমুনা নেওয়ার সময় বিবেচনা করতে টোকেনগুলির সর্বাধিক ক্রমবর্ধমান সম্ভাবনা৷

মডেলটি সম্মিলিত টপ-কে এবং টপ-পি (নিউক্লিয়াস) স্যাম্পলিং ব্যবহার করে।

টোকেনগুলি তাদের নির্ধারিত সম্ভাব্যতার উপর ভিত্তি করে সাজানো হয় যাতে শুধুমাত্র সবচেয়ে সম্ভাব্য টোকেনগুলিকে বিবেচনা করা হয়। টপ-কে নমুনা সরাসরি বিবেচনা করার জন্য সর্বাধিক টোকেন সীমিত করে, যখন নিউক্লিয়াস স্যাম্পলিং ক্রমবর্ধমান সম্ভাব্যতার উপর ভিত্তি করে টোকেনের সংখ্যা সীমিত করে।

দ্রষ্টব্য: ডিফল্ট মান Model অনুসারে পরিবর্তিত হয় এবং getModel ফাংশন থেকে ফেরত Model.top_p বৈশিষ্ট্য দ্বারা নির্দিষ্ট করা হয়। একটি খালি topK বৈশিষ্ট্য নির্দেশ করে যে মডেলটি টপ-কে স্যাম্পলিং প্রয়োগ করে না এবং অনুরোধে topK সেট করার অনুমতি দেয় না।

topK integer

ঐচ্ছিক। নমুনা নেওয়ার সময় সর্বাধিক সংখ্যক টোকেন বিবেচনা করতে হবে।

মিথুন মডেল টপ-পি (নিউক্লিয়াস) স্যাম্পলিং বা টপ-কে এবং নিউক্লিয়াস স্যাম্পলিং এর সংমিশ্রণ ব্যবহার করে। Top-k স্যাম্পলিং topK সবচেয়ে সম্ভাব্য টোকেনের সেট বিবেচনা করে। নিউক্লিয়াস স্যাম্পলিং সহ চলমান মডেলগুলি topK সেটিং অনুমোদন করে না।

দ্রষ্টব্য: ডিফল্ট মান Model অনুসারে পরিবর্তিত হয় এবং getModel ফাংশন থেকে ফেরত Model.top_p বৈশিষ্ট্য দ্বারা নির্দিষ্ট করা হয়। একটি খালি topK বৈশিষ্ট্য নির্দেশ করে যে মডেলটি টপ-কে স্যাম্পলিং প্রয়োগ করে না এবং অনুরোধে topK সেট করার অনুমতি দেয় না।

seed integer

ঐচ্ছিক। ডিকোডিং এ ব্যবহৃত বীজ। যদি সেট না করা থাকে, অনুরোধটি এলোমেলোভাবে উৎপন্ন বীজ ব্যবহার করে।

presencePenalty number

ঐচ্ছিক। উপস্থিতি জরিমানা পরবর্তী টোকেনের লগপ্রবগুলিতে প্রয়োগ করা হয় যদি টোকেনটি ইতিমধ্যে প্রতিক্রিয়াতে দেখা যায়।

এই জরিমানাটি বাইনারি চালু/বন্ধ এবং টোকেনটি কতবার ব্যবহার করা হয়েছে তার উপর নির্ভর করে না (প্রথমটির পরে)। একটি পেনাল্টির জন্য frequencyPenalty ব্যবহার করুন যা প্রতিটি ব্যবহারের সাথে বৃদ্ধি পায়।

একটি ইতিবাচক শাস্তি টোকেনগুলির ব্যবহারকে নিরুৎসাহিত করবে যা ইতিমধ্যে প্রতিক্রিয়াতে ব্যবহৃত হয়েছে, শব্দভাণ্ডার বৃদ্ধি করবে।

একটি নেতিবাচক জরিমানা টোকেন ব্যবহারে উৎসাহিত করবে যা ইতিমধ্যে প্রতিক্রিয়াতে ব্যবহৃত হয়েছে, শব্দভান্ডার হ্রাস করবে।

frequencyPenalty number

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

একটি ইতিবাচক শাস্তি টোকেন ব্যবহারকে নিরুৎসাহিত করবে যা ইতিমধ্যেই ব্যবহৃত হয়েছে, টোকেনটি যতবার ব্যবহার করা হয়েছে তার সমানুপাতিক: একটি টোকেন যত বেশি ব্যবহার করা হবে, মডেলটির পক্ষে সেই টোকেনটি পুনরায় ব্যবহার করা তত বেশি কঠিন প্রতিক্রিয়াগুলির শব্দভাণ্ডার বৃদ্ধি করে৷

সতর্কতা: একটি নেতিবাচক জরিমানা মডেলটিকে টোকেনটি যতবার ব্যবহার করা হয়েছে তার সমানুপাতিক টোকেনগুলি পুনরায় ব্যবহার করতে উত্সাহিত করবে৷ ছোট নেতিবাচক মান প্রতিক্রিয়ার শব্দভাণ্ডার হ্রাস করবে। বৃহত্তর নেতিবাচক মানগুলি মডেলটিকে একটি সাধারণ টোকেন পুনরাবৃত্তি করা শুরু করবে যতক্ষণ না এটি maxOutputTokens সীমাতে আঘাত করে।

responseLogprobs boolean

ঐচ্ছিক। সত্য হলে, প্রতিক্রিয়া হিসাবে logprobs রপ্তানি করুন।

logprobs integer

ঐচ্ছিক। শুধুমাত্র বৈধ যদি responseLogprobs=True । এটি Candidate.logprobs_result এ প্রতিটি ডিকোডিং ধাপে ফিরে আসার জন্য শীর্ষ লগপ্রবগুলির সংখ্যা সেট করে।

enableEnhancedCivicAnswers boolean

ঐচ্ছিক। উন্নত নাগরিক উত্তর সক্ষম করে। এটা সব মডেলের জন্য উপলব্ধ নাও হতে পারে.

speechConfig object ( SpeechConfig )

ঐচ্ছিক। স্পিচ জেনারেশন কনফিগারেশন।

mediaResolution enum ( MediaResolution )

ঐচ্ছিক। নির্দিষ্ট করা হলে, নির্দিষ্ট মিডিয়া রেজোলিউশন ব্যবহার করা হবে।

JSON প্রতিনিধিত্ব
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "responseModalities": [
    enum (Modality)
  ],
  "candidateCount": integer,
  "maxOutputTokens": integer,
  "temperature": number,
  "topP": number,
  "topK": integer,
  "seed": integer,
  "presencePenalty": number,
  "frequencyPenalty": number,
  "responseLogprobs": boolean,
  "logprobs": integer,
  "enableEnhancedCivicAnswers": boolean,
  "speechConfig": {
    object (SpeechConfig)
  },
  "mediaResolution": enum (MediaResolution)
}

মোডালিটি

প্রতিক্রিয়া সমর্থিত পদ্ধতি.

Enums
MODALITY_UNSPECIFIED ডিফল্ট মান।
TEXT নির্দেশ করে যে মডেলটি পাঠ্য ফেরত দেবে।
IMAGE ইঙ্গিত দেয় যে মডেলটি ছবিগুলি ফেরত দেবে৷
AUDIO নির্দেশ করে যে মডেলটি অডিও ফেরত দেবে।

স্পিচ কনফিগ

স্পিচ জেনারেশন কনফিগারেশন।

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

স্পিকার ব্যবহারের জন্য কনফিগারেশন।

JSON প্রতিনিধিত্ব
{
  "voiceConfig": {
    object (VoiceConfig)
  }
}

ভয়েস কনফিগারেশন

ভয়েস ব্যবহার করার জন্য কনফিগারেশন।

ক্ষেত্র
voice_config Union type
স্পিকার ব্যবহারের জন্য কনফিগারেশন। voice_config নিম্নলিখিতগুলির মধ্যে একটি হতে পারে:
prebuiltVoiceConfig object ( PrebuiltVoiceConfig )

প্রি-বিল্ট ভয়েস ব্যবহারের জন্য কনফিগারেশন।

JSON প্রতিনিধিত্ব
{

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

PrebuiltVoiceConfig

প্রি-বিল্ট স্পিকার ব্যবহারের জন্য কনফিগারেশন।

ক্ষেত্র
voiceName string

ব্যবহার করার জন্য প্রিসেট ভয়েসের নাম।

JSON প্রতিনিধিত্ব
{
  "voiceName": string
}

মিডিয়া রেজোলিউশন

ইনপুট মিডিয়ার জন্য মিডিয়া রেজোলিউশন।

Enums
MEDIA_RESOLUTION_UNSPECIFIED মিডিয়া রেজোলিউশন সেট করা হয়নি.
MEDIA_RESOLUTION_LOW মিডিয়া রেজোলিউশন কম সেট করা হয়েছে (64 টোকেন)।
MEDIA_RESOLUTION_MEDIUM মিডিয়া রেজোলিউশন মাঝারিতে সেট করা হয়েছে (256 টোকেন)।
MEDIA_RESOLUTION_HIGH মিডিয়া রেজোলিউশন উচ্চ সেট করা হয়েছে (256 টোকেন সহ জুম রিফ্রেমিং)।

হার্ম ক্যাটাগরি

একটি রেটিং এর বিভাগ।

এই বিভাগগুলি বিভিন্ন ধরণের ক্ষতি কভার করে যা বিকাশকারীরা সামঞ্জস্য করতে চাইতে পারে৷

Enums
HARM_CATEGORY_UNSPECIFIED বিভাগ অনির্দিষ্ট.
HARM_CATEGORY_DEROGATORY PaLM - পরিচয় এবং/অথবা সুরক্ষিত বৈশিষ্ট্যকে লক্ষ্য করে নেতিবাচক বা ক্ষতিকর মন্তব্য।
HARM_CATEGORY_TOXICITY PaLM - এমন সামগ্রী যা অভদ্র, অসম্মানজনক বা অপবিত্র।
HARM_CATEGORY_VIOLENCE PaLM - একটি ব্যক্তি বা গোষ্ঠীর বিরুদ্ধে সহিংসতা, বা গোরের সাধারণ বর্ণনার চিত্রিত পরিস্থিতি বর্ণনা করে।
HARM_CATEGORY_SEXUAL PaLM - যৌন ক্রিয়াকলাপ বা অন্যান্য অশ্লীল বিষয়বস্তুর উল্লেখ রয়েছে৷
HARM_CATEGORY_MEDICAL PaLM - অচেক করা চিকিৎসা পরামর্শ প্রচার করে।
HARM_CATEGORY_DANGEROUS PaLM - বিপজ্জনক বিষয়বস্তু যা ক্ষতিকারক কাজকে প্রচার করে, সুবিধা দেয় বা উৎসাহিত করে।
HARM_CATEGORY_HARASSMENT মিথুন - হয়রানির বিষয়বস্তু।
HARM_CATEGORY_HATE_SPEECH মিথুন - বিদ্বেষপূর্ণ বক্তব্য এবং বিষয়বস্তু।
HARM_CATEGORY_SEXUALLY_EXPLICIT মিথুন - যৌনতাপূর্ণ বিষয়বস্তু।
HARM_CATEGORY_DANGEROUS_CONTENT মিথুন - বিপজ্জনক বিষয়বস্তু।
HARM_CATEGORY_CIVIC_INTEGRITY মিথুন - এমন সামগ্রী যা নাগরিক অখণ্ডতার ক্ষতি করতে ব্যবহৃত হতে পারে।

ModalityTokenCount

একটি একক পদ্ধতির জন্য টোকেন গণনা তথ্য প্রতিনিধিত্ব করে।

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

এই টোকেন গণনার সাথে যুক্ত পদ্ধতি।

tokenCount integer

টোকেনের সংখ্যা।

JSON প্রতিনিধিত্ব
{
  "modality": enum (Modality),
  "tokenCount": integer
}

মোডালিটি

বিষয়বস্তু অংশ মোডালিটি

Enums
MODALITY_UNSPECIFIED অনির্দিষ্ট পদ্ধতি।
TEXT সরল পাঠ্য।
IMAGE ছবি।
VIDEO ভিডিও।
AUDIO অডিও।
DOCUMENT নথি, যেমন পিডিএফ।

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

সামগ্রীর একটি অংশের জন্য নিরাপত্তা রেটিং।

নিরাপত্তা রেটিংয়ে ক্ষতির বিভাগ এবং বিষয়বস্তুর একটি অংশের জন্য সেই বিভাগে ক্ষতির সম্ভাবনার স্তর রয়েছে। বিষয়বস্তু নিরাপত্তার জন্য বিভিন্ন ক্ষতির শ্রেণীতে শ্রেণীবদ্ধ করা হয়েছে এবং ক্ষতির শ্রেণীবিভাগের সম্ভাবনা এখানে অন্তর্ভুক্ত করা হয়েছে।

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

প্রয়োজন। এই রেটিং জন্য বিভাগ.

probability enum ( HarmProbability )

প্রয়োজন। এই বিষয়বস্তুর জন্য ক্ষতির সম্ভাবনা।

blocked boolean

এই রেটিং এর কারণে কি এই কন্টেন্ট ব্লক করা হয়েছিল?

JSON প্রতিনিধিত্ব
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}

ক্ষতির সম্ভাবনা

বিষয়বস্তুর একটি অংশ ক্ষতিকারক হওয়ার সম্ভাবনা।

শ্রেণীবিভাগ পদ্ধতি বিষয়বস্তু অনিরাপদ হওয়ার সম্ভাবনা দেয়। এটি সামগ্রীর একটি অংশের জন্য ক্ষতির তীব্রতা নির্দেশ করে না।

Enums
HARM_PROBABILITY_UNSPECIFIED সম্ভাবনা অনির্দিষ্ট।
NEGLIGIBLE বিষয়বস্তু অনিরাপদ হওয়ার সম্ভাবনা খুবই কম।
LOW বিষয়বস্তু অনিরাপদ হওয়ার সম্ভাবনা কম।
MEDIUM বিষয়বস্তু অনিরাপদ হওয়ার মাঝারি সম্ভাবনা রয়েছে।
HIGH বিষয়বস্তু অনিরাপদ হওয়ার উচ্চ সম্ভাবনা রয়েছে।

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

নিরাপত্তা সেটিং, নিরাপত্তা-অবরুদ্ধ আচরণকে প্রভাবিত করে।

একটি বিভাগের জন্য একটি নিরাপত্তা সেটিং পাস করা বিষয়বস্তু ব্লক করা অনুমোদিত সম্ভাবনা পরিবর্তন করে।

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

প্রয়োজন। এই সেটিং এর জন্য বিভাগ.

threshold enum ( HarmBlockThreshold )

প্রয়োজন। সম্ভাব্যতা থ্রেশহোল্ড নিয়ন্ত্রণ করে যেখানে ক্ষতি ব্লক করা হয়।

JSON প্রতিনিধিত্ব
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

হার্মব্লক থ্রেশহোল্ড

একটি নির্দিষ্ট ক্ষতির সম্ভাবনা এ এবং তার পরেও ব্লক করুন।

Enums
HARM_BLOCK_THRESHOLD_UNSPECIFIED থ্রেশহোল্ড অনির্দিষ্ট।
BLOCK_LOW_AND_ABOVE NEGLIGIBLE সহ সামগ্রী অনুমোদিত হবে।
BLOCK_MEDIUM_AND_ABOVE নগণ্য এবং কম সহ সামগ্রী অনুমোদিত হবে।
BLOCK_ONLY_HIGH নগণ্য, নিম্ন এবং মাঝারি সহ সামগ্রী অনুমোদিত হবে৷
BLOCK_NONE সমস্ত বিষয়বস্তু অনুমোদিত হবে.
OFF নিরাপত্তা ফিল্টার বন্ধ করুন।