Generating content

Gemini API की मदद से, इमेज, ऑडियो, कोड, टूल वगैरह का इस्तेमाल करके कॉन्टेंट जनरेट किया जा सकता है. इनमें से हर सुविधा के बारे में जानने के लिए, आगे पढ़ें. साथ ही, टास्क पर फ़ोकस करने वाला सैंपल कोड देखें या पूरी गाइड पढ़ें.

तरीका: models.generateContent

यह फ़ंक्शन, इनपुट GenerateContentRequest के आधार पर मॉडल का जवाब जनरेट करता है. इस्तेमाल से जुड़ी ज़्यादा जानकारी के लिए, टेक्स्ट जनरेट करने से जुड़ी गाइड देखें. ट्यून किए गए मॉडल के साथ-साथ अन्य मॉडल के लिए, इनपुट देने की सुविधाएं अलग-अलग होती हैं. ज़्यादा जानकारी के लिए, मॉडल गाइड और ट्यूनिंग गाइड देखें.

एंडपॉइंट

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

पाथ पैरामीटर

model string

ज़रूरी है. Model का नाम, जिसका इस्तेमाल जवाब जनरेट करने के लिए किया जाना है.

फ़ॉर्मैट: models/{model}. यह models/{model} के फ़ॉर्मैट में होता है.

अनुरोध का मुख्य भाग

अनुरोध के मुख्य हिस्से में, इस स्ट्रक्चर का डेटा शामिल होता है:

फ़ील्ड
contents[] object (Content)

ज़रूरी है. मॉडल के साथ मौजूदा बातचीत का कॉन्टेंट.

सिंगल-टर्न क्वेरी के लिए, यह एक इंस्टेंस होता है. चैट जैसी एक से ज़्यादा बार की जाने वाली क्वेरी के लिए, यह एक दोहराया गया फ़ील्ड है. इसमें बातचीत का इतिहास और हाल ही का अनुरोध शामिल होता है.

tools[] object (Tool)

ज़रूरी नहीं. Tools की एक सूची, जिसका इस्तेमाल Model अगले जवाब को जनरेट करने के लिए कर सकता है.

Tool एक कोड होता है. इसकी मदद से सिस्टम, बाहरी सिस्टम के साथ इंटरैक्ट कर पाता है. इससे Model के दायरे से बाहर कोई कार्रवाई या कार्रवाइयों का सेट किया जा सकता है. Function और codeExecution Tool के साथ काम करते हैं. ज़्यादा जानने के लिए, फ़ंक्शन कॉलिंग और कोड एक्ज़ीक्यूशन गाइड देखें.

toolConfig object (ToolConfig)

ज़रूरी नहीं. अनुरोध में बताए गए किसी भी Tool के लिए टूल कॉन्फ़िगरेशन. इस्तेमाल का उदाहरण देखने के लिए, फ़ंक्शन कॉलिंग गाइड देखें.

safetySettings[] object (SafetySetting)

ज़रूरी नहीं. असुरक्षित कॉन्टेंट को ब्लॉक करने के लिए, यूनीक SafetySetting इंस्टेंस की सूची.

यह GenerateContentRequest.contents और GenerateContentResponse.candidates पर लागू होगा. हर SafetyCategory टाइप के लिए, एक से ज़्यादा सेटिंग नहीं होनी चाहिए. एपीआई, उन सभी कॉन्टेंट और जवाबों को ब्लॉक कर देगा जो इन सेटिंग के ज़रिए तय की गई थ्रेशोल्ड को पूरा नहीं करते. इस सूची में, safetySettings में बताए गए हर SafetyCategory के लिए डिफ़ॉल्ट सेटिंग को ओवरराइड किया जाता है. अगर सूची में दिए गए किसी SafetyCategory के लिए कोई SafetySetting नहीं है, तो एपीआई उस कैटगरी के लिए डिफ़ॉल्ट सुरक्षा सेटिंग का इस्तेमाल करेगा. इन कैटगरी में आने वाले कॉन्टेंट की पहचान की जा सकती है: HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY. सुरक्षा से जुड़ी उपलब्ध सेटिंग के बारे में ज़्यादा जानकारी के लिए, गाइड देखें. एआई ऐप्लिकेशन में सुरक्षा से जुड़ी बातों को शामिल करने का तरीका जानने के लिए, सुरक्षा से जुड़े दिशा-निर्देश भी पढ़ें.

systemInstruction object (Content)

ज़रूरी नहीं. डेवलपर ने सिस्टम के लिए निर्देश सेट किए हैं. फ़िलहाल, सिर्फ़ टेक्स्ट.

generationConfig object (GenerationConfig)

ज़रूरी नहीं. मॉडल जनरेट करने और आउटपुट के लिए कॉन्फ़िगरेशन के विकल्प.

cachedContent string

ज़रूरी नहीं. कॉन्टेंट का वह नाम जिसे कैश मेमोरी में सेव किया गया है, ताकि अनुमान लगाने के लिए कॉन्टेक्स्ट के तौर पर उसका इस्तेमाल किया जा सके. फ़ॉर्मैट: cachedContents/{cachedContent}

अनुरोध का उदाहरण

टेक्स्ट

Python

from google import genai

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

Node.js

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

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

ऐप पर जाएं

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

शेल

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

Java

Client client = new Client();

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

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

इमेज

Python

from google import genai
import PIL.Image

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

Node.js

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

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

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

ऐप पर जाएं

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

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

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

शेल

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

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

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

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

Java

Client client = new Client();

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

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

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

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

ऑडियो

Python

from google import genai

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

Node.js

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

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

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

ऐप पर जाएं

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

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

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

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

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

शेल

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

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

वीडियो

Python

from google import genai
import time

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

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

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

Node.js

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

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

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

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

ऐप पर जाएं

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

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

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

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

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

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

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

शेल

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

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

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

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

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

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

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

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

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

cat response.json
echo

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

PDF

Python

from google import genai

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

ऐप पर जाएं

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

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

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

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

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

शेल

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

चैट करें

Python

from google import genai
from google.genai import types

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

Node.js

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

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

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

ऐप पर जाएं

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

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

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

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

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

शेल

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

Java

Client client = new Client();

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

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

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

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

कैश मेमोरी

Python

from google import genai
from google.genai import types

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

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

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

Node.js

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

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

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

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

ऐप पर जाएं

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

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

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

फ़ाइन-ट्यून किया गया मॉडल

Python

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

JSON मोड

Python

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

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

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

Node.js

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

ऐप पर जाएं

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

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

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

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

शेल

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

Java

Client client = new Client();

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

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

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

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

कोड को एक्ज़ीक्यूट करना

Python

from google import genai
from google.genai import types

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

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

ऐप पर जाएं

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

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

// Print the response.
printResponse(response)

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

Java

Client client = new Client();

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

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

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

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

फ़ंक्शन कॉलिंग

Python

from google import genai
from google.genai import types

client = genai.Client()

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

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

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

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

# Create a chat session; function calling (via tools) is enabled in the config.
chat = client.chats.create(
    model="gemini-2.0-flash",
    config=types.GenerateContentConfig(tools=[add, subtract, multiply, divide]),
)
response = chat.send_message(
    message="I have 57 cats, each owns 44 mittens, how many mittens is that in total?"
)
print(response.text)

ऐप पर जाएं

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

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

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

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

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

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

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

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

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

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

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

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

printResponse(finalResponse)

Node.js

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

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

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

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

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

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

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

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

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

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

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

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

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

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

शेल


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

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

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

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

Java

Client client = new Client();

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

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

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

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

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

                )
        )
        .build();

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


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

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

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

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

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

System.out.println(result);

जनरेशन कॉन्फ़िगरेशन

Python

from google import genai
from google.genai import types

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

Node.js

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

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

console.log(response.text);

ऐप पर जाएं

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

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

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

printResponse(response)

शेल

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

Java

Client client = new Client();

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

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

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

सुरक्षा सेटिंग

Python

from google import genai
from google.genai import types

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

print(response.candidates[0].safety_ratings)

Node.js

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

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

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

ऐप पर जाएं

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

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

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

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

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

शेल

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

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

Java

Client client = new Client();

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

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

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

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

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

सिस्टम के निर्देश

Python

from google import genai
from google.genai import types

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

Node.js

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

ऐप पर जाएं

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

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

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

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

शेल

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

Java

Client client = new Client();

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

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

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

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

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

जवाब का मुख्य भाग

कामयाब रहने पर, जवाब के मुख्य हिस्से में GenerateContentResponse का एक इंस्टेंस शामिल किया जाता है.

तरीका: models.streamGenerateContent

यह फ़ंक्शन, इनपुट GenerateContentRequest के आधार पर मॉडल से स्ट्रीम किया गया जवाब जनरेट करता है.

एंडपॉइंट

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

पाथ पैरामीटर

model string

ज़रूरी है. Model का नाम, जिसका इस्तेमाल जवाब जनरेट करने के लिए किया जाना है.

फ़ॉर्मैट: models/{model}. यह models/{model} के फ़ॉर्मैट में होता है.

अनुरोध का मुख्य भाग

अनुरोध के मुख्य हिस्से में, इस स्ट्रक्चर का डेटा शामिल होता है:

फ़ील्ड
contents[] object (Content)

ज़रूरी है. मॉडल के साथ मौजूदा बातचीत का कॉन्टेंट.

सिंगल-टर्न क्वेरी के लिए, यह एक इंस्टेंस होता है. चैट जैसी एक से ज़्यादा बार की जाने वाली क्वेरी के लिए, यह एक दोहराया गया फ़ील्ड है. इसमें बातचीत का इतिहास और हाल ही का अनुरोध शामिल होता है.

tools[] object (Tool)

ज़रूरी नहीं. Tools की एक सूची, जिसका इस्तेमाल Model अगले जवाब को जनरेट करने के लिए कर सकता है.

Tool एक कोड होता है. इसकी मदद से सिस्टम, बाहरी सिस्टम के साथ इंटरैक्ट कर पाता है. इससे Model के दायरे से बाहर कोई कार्रवाई या कार्रवाइयों का सेट किया जा सकता है. Function और codeExecution Tool के साथ काम करते हैं. ज़्यादा जानने के लिए, फ़ंक्शन कॉलिंग और कोड एक्ज़ीक्यूशन गाइड देखें.

toolConfig object (ToolConfig)

ज़रूरी नहीं. अनुरोध में बताए गए किसी भी Tool के लिए टूल कॉन्फ़िगरेशन. इस्तेमाल का उदाहरण देखने के लिए, फ़ंक्शन कॉलिंग गाइड देखें.

safetySettings[] object (SafetySetting)

ज़रूरी नहीं. असुरक्षित कॉन्टेंट को ब्लॉक करने के लिए, यूनीक SafetySetting इंस्टेंस की सूची.

यह GenerateContentRequest.contents और GenerateContentResponse.candidates पर लागू होगा. हर SafetyCategory टाइप के लिए, एक से ज़्यादा सेटिंग नहीं होनी चाहिए. एपीआई, उन सभी कॉन्टेंट और जवाबों को ब्लॉक कर देगा जो इन सेटिंग के ज़रिए तय की गई थ्रेशोल्ड को पूरा नहीं करते. इस सूची में, safetySettings में बताए गए हर SafetyCategory के लिए डिफ़ॉल्ट सेटिंग को ओवरराइड किया जाता है. अगर सूची में दिए गए किसी SafetyCategory के लिए कोई SafetySetting नहीं है, तो एपीआई उस कैटगरी के लिए डिफ़ॉल्ट सुरक्षा सेटिंग का इस्तेमाल करेगा. इन कैटगरी में आने वाले कॉन्टेंट की पहचान की जा सकती है: HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY. सुरक्षा से जुड़ी उपलब्ध सेटिंग के बारे में ज़्यादा जानकारी के लिए, गाइड देखें. एआई ऐप्लिकेशन में सुरक्षा से जुड़ी बातों को शामिल करने का तरीका जानने के लिए, सुरक्षा से जुड़े दिशा-निर्देश भी पढ़ें.

systemInstruction object (Content)

ज़रूरी नहीं. डेवलपर ने सिस्टम के लिए निर्देश सेट किए हैं. फ़िलहाल, सिर्फ़ टेक्स्ट.

generationConfig object (GenerationConfig)

ज़रूरी नहीं. मॉडल जनरेट करने और आउटपुट के लिए कॉन्फ़िगरेशन के विकल्प.

cachedContent string

ज़रूरी नहीं. कॉन्टेंट का वह नाम जिसे कैश मेमोरी में सेव किया गया है, ताकि अनुमान लगाने के लिए कॉन्टेक्स्ट के तौर पर उसका इस्तेमाल किया जा सके. फ़ॉर्मैट: cachedContents/{cachedContent}

अनुरोध का उदाहरण

टेक्स्ट

Python

from google import genai

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

Node.js

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

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

ऐप पर जाएं

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

शेल

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

Java

Client client = new Client();

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

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

responseStream.close();

इमेज

Python

from google import genai
import PIL.Image

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

Node.js

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

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

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

ऐप पर जाएं

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

शेल

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

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

Java

Client client = new Client();

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

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


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

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

responseStream.close();

ऑडियो

Python

from google import genai

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

ऐप पर जाएं

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

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

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

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

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

शेल

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

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

वीडियो

Python

from google import genai
import time

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

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

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

Node.js

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

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

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

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

ऐप पर जाएं

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

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

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

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

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

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

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

शेल

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

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

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

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

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

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

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

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

cat response.json
echo

PDF

Python

from google import genai

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

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

ऐप पर जाएं

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

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

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

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

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

शेल

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

चैट करें

Python

from google import genai
from google.genai import types

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

print(chat.get_history())

Node.js

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

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

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

console.log(chat.getHistory());

ऐप पर जाएं

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

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

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

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

fmt.Println(chat.History(false))

शेल

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

जवाब का मुख्य भाग

अगर एपीआई सही से जुड़ जाता है, तो जवाब के मुख्य हिस्से में GenerateContentResponse इंस्टेंस की स्ट्रीम शामिल होती है.

GenerateContentResponse

मॉडल से मिला जवाब, जिसमें कई संभावित जवाब शामिल हैं.

सुरक्षा रेटिंग और कॉन्टेंट फ़िल्टर करने की सुविधा के बारे में जानकारी, GenerateContentResponse.prompt_feedback में दिए गए प्रॉम्प्ट और finishReason और safetyRatings में दिए गए हर जवाब के लिए दी जाती है. एपीआई: - अनुरोध किए गए सभी उम्मीदवारों या किसी भी उम्मीदवार की जानकारी नहीं दिखाता है - किसी भी उम्मीदवार की जानकारी तब नहीं दिखाता है, जब प्रॉम्प्ट में कोई गड़बड़ी हो (promptFeedback देखें) - finishReason और safetyRatings में हर उम्मीदवार के बारे में सुझाव/राय देता है या शिकायत करता है.

Fields
candidates[] object (Candidate)

मॉडल से मिले उम्मीदवार के जवाब.

promptFeedback object (PromptFeedback)

कॉन्टेंट फ़िल्टर से जुड़े प्रॉम्प्ट के सुझाव/राय या शिकायत दिखाता है.

usageMetadata object (UsageMetadata)

सिर्फ़ आउटपुट के लिए. जनरेट करने के अनुरोधों में टोकन के इस्तेमाल से जुड़ा मेटाडेटा.

modelVersion string

सिर्फ़ आउटपुट के लिए. जवाब जनरेट करने के लिए इस्तेमाल किए गए मॉडल का वर्शन.

responseId string

सिर्फ़ आउटपुट. responseId का इस्तेमाल, हर जवाब की पहचान करने के लिए किया जाता है.

JSON के काेड में दिखाना
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string,
  "responseId": string
}

PromptFeedback

यह फ़ीडबैक मेटाडेटा का एक सेट है. इसे प्रॉम्प्ट में GenerateContentRequest.content के तौर पर तय किया गया है.

Fields
blockReason enum (BlockReason)

ज़रूरी नहीं. अगर इसे सेट किया जाता है, तो प्रॉम्प्ट को ब्लॉक कर दिया जाता है और कोई भी जवाब नहीं मिलता है. प्रॉम्प्ट को फिर से लिखें.

safetyRatings[] object (SafetyRating)

प्रॉम्प्ट की सुरक्षा के लिए रेटिंग. हर कैटगरी के लिए ज़्यादा से ज़्यादा एक रेटिंग होती है.

JSON के काेड में दिखाना
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

BlockReason

इस फ़ील्ड में, प्रॉम्प्ट को ब्लॉक करने की वजह बताई जाती है.

Enums
BLOCK_REASON_UNSPECIFIED डिफ़ॉल्ट मान. इस वैल्यू का इस्तेमाल नहीं किया गया है.
SAFETY सुरक्षा से जुड़ी वजहों से प्रॉम्प्ट को ब्लॉक कर दिया गया है. safetyRatings की जांच करके जानें कि किस सुरक्षा कैटगरी ने इसे ब्लॉक किया है.
OTHER किसी वजह से प्रॉम्प्ट को ब्लॉक कर दिया गया है.
BLOCKLIST ब्लॉक किए गए शब्दों की सूची में शामिल शब्दों की वजह से, प्रॉम्प्ट को ब्लॉक कर दिया गया है.
PROHIBITED_CONTENT पाबंदी वाले कॉन्टेंट की वजह से प्रॉम्प्ट को ब्लॉक कर दिया गया है.
IMAGE_SAFETY असुरक्षित इमेज जनरेट करने वाले कॉन्टेंट की वजह से, उम्मीदवारों को ब्लॉक कर दिया गया है.

UsageMetadata

जनरेट करने के अनुरोध के टोकन के इस्तेमाल से जुड़ा मेटाडेटा.

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

उम्मीदवार

मॉडल से जनरेट किया गया जवाब.

Fields
content object (Content)

सिर्फ़ आउटपुट के लिए. मॉडल से मिला जनरेट किया गया कॉन्टेंट.

finishReason enum (FinishReason)

ज़रूरी नहीं. सिर्फ़ आउटपुट के लिए. मॉडल ने टोकन जनरेट करना क्यों बंद कर दिया.

अगर यह फ़ील्ड खाली है, तो इसका मतलब है कि मॉडल ने टोकन जनरेट करना बंद नहीं किया है.

safetyRatings[] object (SafetyRating)

जवाब के तौर पर सुझाए गए किसी कॉन्टेंट की सुरक्षा के लिए रेटिंग की सूची.

हर कैटगरी के लिए ज़्यादा से ज़्यादा एक रेटिंग होती है.

citationMetadata object (CitationMetadata)

सिर्फ़ आउटपुट के लिए. मॉडल से जनरेट किए गए जवाब के लिए उद्धरण की जानकारी.

इस फ़ील्ड में, content में शामिल किसी भी टेक्स्ट के लिए, पढ़ने से जुड़ी जानकारी भरी जा सकती है. ये ऐसे पैसेज होते हैं जिन्हें बुनियादी एलएलएम के ट्रेनिंग डेटा में मौजूद कॉपीराइट वाले कॉन्टेंट से "रीसाइट" किया जाता है.

tokenCount integer

सिर्फ़ आउटपुट के लिए. इस उम्मीदवार के लिए टोकन की संख्या.

groundingAttributions[] object (GroundingAttribution)

सिर्फ़ आउटपुट के लिए. जवाब में शामिल जानकारी के लिए एट्रिब्यूशन की जानकारी.

यह फ़ील्ड, GenerateAnswer कॉल के लिए भरा जाता है.

groundingMetadata object (GroundingMetadata)

सिर्फ़ आउटपुट के लिए. जवाब के लिए, उम्मीदवार के बारे में जानकारी देने वाला मेटाडेटा.

यह फ़ील्ड, GenerateContent कॉल के लिए भरा जाता है.

avgLogprobs number

सिर्फ़ आउटपुट के लिए. उम्मीदवार का औसत लॉग प्रॉबबिलिटी स्कोर.

logprobsResult object (LogprobsResult)

सिर्फ़ आउटपुट के लिए. जवाब के टोकन और टॉप टोकन के लिए लॉग-लाइकलीहुड स्कोर

urlContextMetadata object (UrlContextMetadata)

सिर्फ़ आउटपुट के लिए. यूआरएल के कॉन्टेक्स्ट को वापस पाने वाले टूल से जुड़ा मेटाडेटा.

index integer

सिर्फ़ आउटपुट के लिए. जवाब के तौर पर सुझाए गए विकल्पों की सूची में उम्मीदवार का इंडेक्स.

JSON के काेड में दिखाना
{
  "content": {
    object (Content)
  },
  "finishReason": enum (FinishReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ],
  "citationMetadata": {
    object (CitationMetadata)
  },
  "tokenCount": integer,
  "groundingAttributions": [
    {
      object (GroundingAttribution)
    }
  ],
  "groundingMetadata": {
    object (GroundingMetadata)
  },
  "avgLogprobs": number,
  "logprobsResult": {
    object (LogprobsResult)
  },
  "urlContextMetadata": {
    object (UrlContextMetadata)
  },
  "index": integer
}

FinishReason

इस फ़ील्ड से यह पता चलता है कि मॉडल ने टोकन जनरेट करना क्यों बंद कर दिया.

Enums
FINISH_REASON_UNSPECIFIED डिफ़ॉल्ट मान. इस वैल्यू का इस्तेमाल नहीं किया गया है.
STOP मॉडल का नैचुरल स्टॉप पॉइंट या दिया गया स्टॉप सीक्वेंस.
MAX_TOKENS अनुरोध में बताए गए टोकन की ज़्यादा से ज़्यादा संख्या तक पहुंच गया है.
SAFETY जवाब के तौर पर दिए गए कॉन्टेंट को सुरक्षा से जुड़ी वजहों से फ़्लैग किया गया है.
RECITATION जवाब के तौर पर दिए गए कॉन्टेंट को, पढ़ने से जुड़ी समस्याओं की वजह से फ़्लैग किया गया है.
LANGUAGE जवाब के तौर पर सुझाए गए कॉन्टेंट को, ऐसी भाषा का इस्तेमाल करने के लिए फ़्लैग किया गया है जो उपलब्ध नहीं है.
OTHER वजह की जानकारी नहीं है.
BLOCKLIST टोकन जनरेट करने की प्रोसेस रोक दी गई है, क्योंकि कॉन्टेंट में पाबंदी वाले शब्द शामिल हैं.
PROHIBITED_CONTENT पाबंदी वाला कॉन्टेंट शामिल होने की वजह से, टोकन जनरेट करने की सुविधा बंद कर दी गई है.
SPII टोकन जनरेट करने की प्रोसेस रोक दी गई है, क्योंकि कॉन्टेंट में व्यक्तिगत पहचान ज़ाहिर करने वाली संवेदनशील जानकारी (एसपीआईआई) शामिल हो सकती है.
MALFORMED_FUNCTION_CALL मॉडल ने जो फ़ंक्शन कॉल जनरेट किया है वह अमान्य है.
IMAGE_SAFETY टोकन जनरेट करने की प्रोसेस रोक दी गई है, क्योंकि जनरेट की गई इमेज में सुरक्षा से जुड़े उल्लंघन शामिल हैं.
UNEXPECTED_TOOL_CALL मॉडल ने टूल कॉल जनरेट किया है, लेकिन अनुरोध में कोई टूल चालू नहीं किया गया है.
TOO_MANY_TOOL_CALLS मॉडल ने एक के बाद एक कई टूल इस्तेमाल किए. इसलिए, सिस्टम ने कार्रवाई बंद कर दी.

GroundingAttribution

जवाब में योगदान देने वाले सोर्स के लिए एट्रिब्यूशन.

Fields
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 में मौजूद किसी हिस्से के लिए आइडेंटिफ़ायर.

Fields
passageId string

सिर्फ़ आउटपुट के लिए. GenerateAnswerRequest के GroundingPassage.id से मेल खाने वाले पैसेज का आईडी.

partIndex integer

सिर्फ़ आउटपुट के लिए. GenerateAnswerRequest के GroundingPassage.content में मौजूद हिस्से का इंडेक्स.

JSON के काेड में दिखाना
{
  "passageId": string,
  "partIndex": integer
}

SemanticRetrieverChunk

SemanticRetrieverConfig का इस्तेमाल करके GenerateAnswerRequest में बताए गए Semantic Retriever के ज़रिए Chunk के लिए आइडेंटिफ़ायर.

Fields
source string

सिर्फ़ आउटपुट के लिए. अनुरोध के SemanticRetrieverConfig.source से मेल खाने वाले सोर्स का नाम. उदाहरण: corpora/123 या corpora/123/documents/abc

chunk string

सिर्फ़ आउटपुट के लिए. Chunk का नाम, जिसमें एट्रिब्यूट किया गया टेक्स्ट शामिल है. उदाहरण: corpora/123/documents/abc/chunks/xyz

JSON के काेड में दिखाना
{
  "source": string,
  "chunk": string
}

GroundingMetadata

ग्राउंडिंग की सुविधा चालू होने पर, क्लाइंट को लौटाया गया मेटाडेटा.

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

SearchEntryPoint

Google Search का एंट्री पॉइंट.

Fields
renderedContent string

ज़रूरी नहीं. यह वेब कॉन्टेंट स्निपेट होता है. इसे किसी वेब पेज या ऐप्लिकेशन के वेबव्यू में एम्बेड किया जा सकता है.

sdkBlob string (bytes format)

ज़रूरी नहीं. Base64 कोड में बदला गया JSON, <खोज के लिए इस्तेमाल हुआ शब्द, खोज का यूआरएल> टपल के कलेक्शन को दिखाता है.

base64 कोड में बदली गई स्ट्रिंग.

JSON के काेड में दिखाना
{
  "renderedContent": string,
  "sdkBlob": string
}

GroundingChunk

जवाब के आधार के तौर पर इस्तेमाल किया गया टेक्स्ट.

फ़ील्ड
chunk_type Union type
यह चंक का टाइप है. chunk_type इनमें से सिर्फ़ एक हो सकता है:
web object (Web)

वेब से लिया गया भरोसेमंद जानकारी वाला हिस्सा.

JSON के काेड में दिखाना
{

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

वेब

वेब से मिला जवाब.

Fields
uri string

यह चंक का यूआरआई रेफ़रंस होता है.

title string

चंक का टाइटल.

JSON के काेड में दिखाना
{
  "uri": string,
  "title": string
}

GroundingSupport

ग्राउंडिंग की सुविधा.

Fields
groundingChunkIndices[] integer

इंडेक्स की सूची ('grounding_chunk' में), जिसमें दावे से जुड़े उद्धरणों की जानकारी दी गई है. उदाहरण के लिए, [1,3,4] का मतलब है कि grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] वे कॉन्टेंट हैं जिन्हें दावे के लिए खोजा गया है.

confidenceScores[] number

सहायता से जुड़े रेफ़रंस का कॉन्फ़िडेंस स्कोर. इसकी वैल्यू 0 से 1 तक होती है. 1 का मतलब है कि हमें सबसे ज़्यादा भरोसा है. इस सूची का साइज़, groundingChunkIndices के साइज़ के बराबर होना चाहिए.

segment object (Segment)

कॉन्टेंट का वह सेगमेंट जिससे यह सहायता जुड़ी है.

JSON के काेड में दिखाना
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

सेगमेंट

कॉन्टेंट का सेगमेंट.

Fields
partIndex integer

सिर्फ़ आउटपुट के लिए. यह अपने पैरंट कॉन्टेंट ऑब्जेक्ट में मौजूद पार्ट ऑब्जेक्ट का इंडेक्स होता है.

startIndex integer

सिर्फ़ आउटपुट के लिए. दिए गए पार्ट में स्टार्ट इंडेक्स, जिसे बाइट में मेज़र किया जाता है. यह पार्ट की शुरुआत से ऑफ़सेट होता है. इसमें पार्ट की शुरुआत भी शामिल होती है. इसकी शुरुआत शून्य से होती है.

endIndex integer

सिर्फ़ आउटपुट के लिए. दिए गए पार्ट में आखिरी इंडेक्स, जिसे बाइट में मापा जाता है. यह पार्ट की शुरुआत से ऑफ़सेट होता है. यह एक्सक्लूसिव होता है और इसकी शुरुआत शून्य से होती है.

text string

सिर्फ़ आउटपुट के लिए. जवाब में मौजूद सेगमेंट से जुड़ा टेक्स्ट.

JSON के काेड में दिखाना
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

RetrievalMetadata

ग्राउंडिंग फ़्लो में जानकारी पाने से जुड़ा मेटाडेटा.

Fields
googleSearchDynamicRetrievalScore number

ज़रूरी नहीं. यह स्कोर बताता है कि Google Search से मिली जानकारी, प्रॉम्प्ट का जवाब देने में कितनी मददगार हो सकती है. स्कोर [0, 1] की रेंज में होता है. इसमें 0 का मतलब है कि संभावना सबसे कम है और 1 का मतलब है कि संभावना सबसे ज़्यादा है. यह स्कोर सिर्फ़ तब दिखता है, जब Google Search के डेटा का इस्तेमाल करके जवाब जनरेट करने और डाइनैमिक तरीके से जानकारी पाने की सुविधा चालू हो. इसकी तुलना थ्रेशोल्ड से की जाएगी, ताकि यह तय किया जा सके कि Google Search को ट्रिगर करना है या नहीं.

JSON के काेड में दिखाना
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

Logprobs Result

Fields
topCandidates[] object (TopCandidates)

लंबाई = डिकोडिंग के चरणों की कुल संख्या.

chosenCandidates[] object (Candidate)

लंबाई = डिकोडिंग के चरणों की कुल संख्या. चुने गए उम्मीदवार, topCandidates में शामिल हो भी सकते हैं और नहीं भी.

JSON के काेड में दिखाना
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ]
}

TopCandidates

हर डिकोडिंग चरण में, सबसे ज़्यादा लॉग प्रॉबेबिलिटी वाले उम्मीदवार.

Fields
candidates[] object (Candidate)

लॉग प्रॉबबिलिटी के हिसाब से घटते क्रम में लगाया गया है.

JSON के काेड में दिखाना
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

उम्मीदवार

logprobs टोकन और स्कोर के लिए उम्मीदवार.

Fields
token string

उम्मीदवार के टोकन की स्ट्रिंग वैल्यू.

tokenId integer

उम्मीदवार के टोकन आईडी की वैल्यू.

logProbability number

उम्मीदवार की लॉग प्रॉबबिलिटी.

JSON के काेड में दिखाना
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

UrlContextMetadata

यूआरएल के कॉन्टेक्स्ट को वापस पाने वाले टूल से जुड़ा मेटाडेटा.

Fields
urlMetadata[] object (UrlMetadata)

यूआरएल कॉन्टेक्स्ट की सूची.

JSON के काेड में दिखाना
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}

UrlMetadata

किसी एक यूआरएल को वापस पाने का कॉन्टेक्स्ट.

Fields
retrievedUrl string

टूल से वापस पाया गया यूआरएल.

urlRetrievalStatus enum (UrlRetrievalStatus)

यूआरएल वापस पाने का स्टेटस.

JSON के काेड में दिखाना
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}

UrlRetrievalStatus

यूआरएल वापस पाने का स्टेटस.

Enums
URL_RETRIEVAL_STATUS_UNSPECIFIED डिफ़ॉल्ट मान. इस वैल्यू का इस्तेमाल नहीं किया गया है.
URL_RETRIEVAL_STATUS_SUCCESS यूआरएल वापस पाने की प्रोसेस पूरी हो गई है.
URL_RETRIEVAL_STATUS_ERROR गड़बड़ी की वजह से, यूआरएल नहीं पाया जा सका.
URL_RETRIEVAL_STATUS_PAYWALL कॉन्टेंट पेवॉल के पीछे होने की वजह से, यूआरएल को वापस नहीं लाया जा सका.
URL_RETRIEVAL_STATUS_UNSAFE कॉन्टेंट असुरक्षित होने की वजह से, यूआरएल को वापस नहीं लाया जा सका.

CitationMetadata

किसी कॉन्टेंट के लिए सोर्स एट्रिब्यूशन का कलेक्शन.

Fields
citationSources[] object (CitationSource)

किसी जवाब के लिए सोर्स के उद्धरण.

JSON के काेड में दिखाना
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}

CitationSource

किसी जवाब के कुछ हिस्से के लिए, सोर्स का उद्धरण.

Fields
startIndex integer

ज़रूरी नहीं. जवाब के उस सेगमेंट की शुरुआत जिसे इस सोर्स के लिए एट्रिब्यूट किया गया है.

इंडेक्स से सेगमेंट की शुरुआत का पता चलता है. इसे बाइट में मापा जाता है.

endIndex integer

ज़रूरी नहीं. एट्रिब्यूट किए गए सेगमेंट के खत्म होने का समय (अलग से उपलब्ध).

uri string

ज़रूरी नहीं. यूआरआई, जिसे टेक्स्ट के किसी हिस्से के लिए सोर्स के तौर पर एट्रिब्यूट किया गया है.

license string

ज़रूरी नहीं. GitHub प्रोजेक्ट का लाइसेंस, जिसे सेगमेंट के सोर्स के तौर पर एट्रिब्यूट किया गया है.

कोड के उद्धरणों के लिए, लाइसेंस की जानकारी देना ज़रूरी है.

JSON के काेड में दिखाना
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}

GenerationConfig

मॉडल जनरेट करने और आउटपुट के लिए कॉन्फ़िगरेशन के विकल्प. हर मॉडल के लिए, सभी पैरामीटर कॉन्फ़िगर नहीं किए जा सकते.

Fields
stopSequences[] string

ज़रूरी नहीं. वर्णों के ऐसे क्रम (ज़्यादा से ज़्यादा पांच) जिन्हें शामिल करने पर, आउटपुट जनरेट होना बंद हो जाएगा. अगर यह विकल्प चुना जाता है, तो एपीआई 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 टेक्स्ट जनरेट करने से जुड़ी गाइड देखें.

responseJsonSchema value (Value format)

ज़रूरी नहीं. जनरेट किए गए जवाब का आउटपुट स्कीमा. यह responseSchema का विकल्प है. इसमें JSON स्कीमा स्वीकार किया जाता है.

अगर यह सेट है, तो responseSchema को हटाना होगा. हालांकि, responseMimeType की जानकारी देना ज़रूरी है.

पूरा JSON स्कीमा भेजा जा सकता है. हालांकि, सभी सुविधाएं काम नहीं करती हैं. खास तौर पर, सिर्फ़ इन प्रॉपर्टी के लिए यह सुविधा उपलब्ध है:

  • $id
  • $defs
  • $ref
  • $anchor
  • type
  • format
  • title
  • description
  • enum (स्ट्रिंग और संख्याओं के लिए)
  • items
  • prefixItems
  • minItems
  • maxItems
  • minimum
  • maximum
  • anyOf
  • oneOf (anyOf की तरह ही माना जाता है)
  • properties
  • additionalProperties
  • required

इसके अलावा, नॉन-स्टैंडर्ड propertyOrdering प्रॉपर्टी भी सेट की जा सकती है.

साइक्लिक रेफ़रंस को सीमित तौर पर अनरोल किया जाता है. इसलिए, इनका इस्तेमाल सिर्फ़ उन प्रॉपर्टी के लिए किया जा सकता है जो ज़रूरी नहीं हैं. (शून्य हो सकने वाली प्रॉपर्टी काफ़ी नहीं हैं.) अगर किसी सब-स्कीमा पर $ref सेट है, तो $ के तौर पर शुरू होने वाली प्रॉपर्टी के अलावा, कोई अन्य प्रॉपर्टी सेट नहीं की जा सकती.

responseModalities[] enum (Modality)

ज़रूरी नहीं. जवाब के लिए अनुरोध की गई मोडेलिटी. यह उन मोडैलिटी के सेट को दिखाता है जिन्हें मॉडल दिखा सकता है. साथ ही, यह रिस्पॉन्स में दिखना चाहिए. यह जवाब के तौर-तरीक़ों से पूरी तरह मेल खाता है.

किसी मॉडल में, काम करने वाली कई मॉडेलिटी के कॉम्बिनेशन हो सकते हैं. अगर अनुरोध की गई मोडेलिटी, काम करने वाले किसी भी कॉम्बिनेशन से मेल नहीं खाती है, तो गड़बड़ी का मैसेज दिखेगा.

खाली सूची का मतलब है कि सिर्फ़ टेक्स्ट का अनुरोध किया गया है.

candidateCount integer

ज़रूरी नहीं. जवाबों की कितनी संख्या जनरेट करके दिखानी है. अगर यह सेट नहीं है, तो डिफ़ॉल्ट रूप से इसकी वैल्यू 1 होगी. कृपया ध्यान दें कि यह सुविधा, पिछली जनरेशन के मॉडल (Gemini 1.0 फ़ैमिली) के लिए काम नहीं करती

maxOutputTokens integer

ज़रूरी नहीं. जवाब के तौर पर सुझाए गए टेक्स्ट में शामिल किए जाने वाले टोकन की ज़्यादा से ज़्यादा संख्या.

ध्यान दें: डिफ़ॉल्ट वैल्यू, मॉडल के हिसाब से अलग-अलग होती है. getModel फ़ंक्शन से मिले Model के Model.output_token_limit एट्रिब्यूट को देखें.

temperature number

ज़रूरी नहीं. इससे आउटपुट में रैंडमनेस को कंट्रोल किया जाता है.

ध्यान दें: डिफ़ॉल्ट वैल्यू, मॉडल के हिसाब से अलग-अलग होती है. getModel फ़ंक्शन से मिले Model के Model.temperature एट्रिब्यूट को देखें.

वैल्यू [0.0, 2.0] के बीच हो सकती हैं.

topP number

ज़रूरी नहीं. सैंपल लेते समय, टोकन की ज़्यादा से ज़्यादा कुल संभावना पर विचार किया जाता है.

यह मॉडल, टॉप-k और टॉप-p (न्यूक्लियस) सैंपलिंग का इस्तेमाल करता है.

टोकन को उनकी असाइन की गई संभावनाओं के आधार पर क्रम से लगाया जाता है, ताकि सिर्फ़ सबसे संभावित टोकन पर विचार किया जा सके. टॉप-k सैंपलिंग में, सीधे तौर पर चुने जाने वाले टोकन की ज़्यादा से ज़्यादा संख्या सीमित होती है. वहीं, न्यूक्लियस सैंपलिंग में, कुल संभावना के आधार पर टोकन की संख्या सीमित होती है.

ध्यान दें: डिफ़ॉल्ट वैल्यू, Model के हिसाब से अलग-अलग होती है. इसे getModel फ़ंक्शन से मिले Model.top_p एट्रिब्यूट से तय किया जाता है. topK एट्रिब्यूट की वैल्यू खाली होने का मतलब है कि मॉडल, टॉप-के सैंपलिंग लागू नहीं करता है. साथ ही, अनुरोधों पर topK सेट करने की अनुमति नहीं देता है.

topK integer

ज़रूरी नहीं. सैंपल लेते समय, ज़्यादा से ज़्यादा टोकन की संख्या.

Gemini के मॉडल, टॉप-पी (न्यूक्लियस) सैंपलिंग या टॉप-के और न्यूक्लियस सैंपलिंग का इस्तेमाल करते हैं. टॉप-k सैंपलिंग में, topK सबसे ज़्यादा संभावित टोकन के सेट को ध्यान में रखा जाता है. न्यूक्लियस सैंपलिंग का इस्तेमाल करने वाले मॉडल में, topK सेटिंग की अनुमति नहीं होती.

ध्यान दें: डिफ़ॉल्ट वैल्यू, Model के हिसाब से अलग-अलग होती है. इसे getModel फ़ंक्शन से मिले Model.top_p एट्रिब्यूट से तय किया जाता है. topK एट्रिब्यूट की वैल्यू खाली होने का मतलब है कि मॉडल, टॉप-के सैंपलिंग लागू नहीं करता है. साथ ही, अनुरोधों पर topK सेट करने की अनुमति नहीं देता है.

seed integer

ज़रूरी नहीं. डिकोडिंग में इस्तेमाल किया गया सीड. अगर इसे सेट नहीं किया जाता है, तो अनुरोध में रैंडम तरीके से जनरेट किए गए सीड का इस्तेमाल किया जाता है.

presencePenalty number

ज़रूरी नहीं. अगर टोकन को जवाब में पहले ही देखा जा चुका है, तो अगले टोकन के logprobs पर प्रेज़ेंस पेनल्टी लागू होती है.

यह जुर्माना, बाइनरी (चालू/बंद) होता है. यह इस बात पर निर्भर नहीं करता कि टोकन का इस्तेमाल कितनी बार किया गया है (पहली बार के बाद). हर बार इस्तेमाल करने पर बढ़ने वाली पेनल्टी के लिए, frequencyPenalty का इस्तेमाल करें.

पॉज़िटिव पेनल्टी से, जवाब में पहले से इस्तेमाल किए गए टोकन के इस्तेमाल को हतोत्साहित किया जाएगा. इससे शब्दावली बढ़ेगी.

नेगेटिव पेनल्टी से, जवाब में पहले से इस्तेमाल किए गए टोकन का इस्तेमाल करने को बढ़ावा मिलेगा. इससे शब्दावली कम हो जाएगी.

frequencyPenalty number

ज़रूरी नहीं. फ़्रीक्वेंसी पेनल्टी, अगले टोकन के logprobs पर लागू होती है. इसे अब तक के जवाब में हर टोकन के दिखने की संख्या से गुणा किया जाता है.

पॉज़िटिव पेनल्टी से, पहले से इस्तेमाल किए गए टोकन का इस्तेमाल करने को हतोत्साहित किया जाएगा. यह पेनल्टी, टोकन के इस्तेमाल की संख्या के हिसाब से लगाई जाएगी: किसी टोकन का जितनी बार इस्तेमाल किया जाएगा, मॉडल के लिए उस टोकन का दोबारा इस्तेमाल करना उतना ही मुश्किल होगा. इससे जवाबों में इस्तेमाल होने वाले शब्दों की संख्या बढ़ जाएगी.

चेतावनी: नेगेटिव पेनल्टी से मॉडल को, टोकन का फिर से इस्तेमाल करने के लिए बढ़ावा मिलेगा. ऐसा, टोकन के इस्तेमाल की संख्या के हिसाब से होगा. नेगेटिव वैल्यू कम होने पर, जवाब में इस्तेमाल किए गए शब्दों की संख्या कम हो जाएगी. नेगेटिव वैल्यू जितनी ज़्यादा होगी, मॉडल उतने ज़्यादा सामान्य टोकन दोहराएगा. ऐसा तब तक होगा, जब तक वह maxOutputTokens की सीमा तक नहीं पहुंच जाता.

responseLogprobs boolean

ज़रूरी नहीं. अगर यह वैल्यू सही है, तो जवाब में logprobs के नतीजे एक्सपोर्ट करें.

logprobs integer

ज़रूरी नहीं. सिर्फ़ तब मान्य होगा, जब responseLogprobs=True. इससे Candidate.logprobs_result में हर डिकोडिंग चरण में, सबसे ज़्यादा logprobs की संख्या सेट की जाती है. यह संख्या [1, 5] के बीच होनी चाहिए.

enableEnhancedCivicAnswers boolean

ज़रूरी नहीं. इस कुकी से, नागरिकता से जुड़े सवालों के बेहतर जवाब पाने की सुविधा चालू होती है. ऐसा हो सकता है कि यह सुविधा सभी मॉडल के लिए उपलब्ध न हो.

speechConfig object (SpeechConfig)

ज़रूरी नहीं. लिखे गए टेक्स्ट को बोली में बदलने की सुविधा का कॉन्फ़िगरेशन.

thinkingConfig object (ThinkingConfig)

ज़रूरी नहीं. सोचने की सुविधाओं के लिए कॉन्फ़िगरेशन. अगर इस फ़ील्ड को ऐसे मॉडल के लिए सेट किया जाता है जिनमें सोचने की सुविधा काम नहीं करती, तो गड़बड़ी का मैसेज दिखेगा.

mediaResolution enum (MediaResolution)

ज़रूरी नहीं. अगर यह जानकारी दी गई है, तो मीडिया के लिए तय किए गए रिज़ॉल्यूशन का इस्तेमाल किया जाएगा.

JSON के काेड में दिखाना
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "responseJsonSchema": value,
  "responseModalities": [
    enum (Modality)
  ],
  "candidateCount": integer,
  "maxOutputTokens": integer,
  "temperature": number,
  "topP": number,
  "topK": integer,
  "seed": integer,
  "presencePenalty": number,
  "frequencyPenalty": number,
  "responseLogprobs": boolean,
  "logprobs": integer,
  "enableEnhancedCivicAnswers": boolean,
  "speechConfig": {
    object (SpeechConfig)
  },
  "thinkingConfig": {
    object (ThinkingConfig)
  },
  "mediaResolution": enum (MediaResolution)
}

मोडेलिटी

जवाब देने के लिए इस्तेमाल की जा सकने वाली सुविधाएं.

Enums
MODALITY_UNSPECIFIED डिफ़ॉल्ट मान.
TEXT इससे पता चलता है कि मॉडल को टेक्स्ट दिखाना चाहिए.
IMAGE इससे पता चलता है कि मॉडल को इमेज दिखानी चाहिए.
AUDIO इससे पता चलता है कि मॉडल को ऑडियो जवाब देना चाहिए.

SpeechConfig

लिखे गए टेक्स्ट को बोली में बदलने की सुविधा का कॉन्फ़िगरेशन.

Fields
voiceConfig object (VoiceConfig)

एक आवाज़ में आउटपुट देने के लिए कॉन्फ़िगरेशन.

multiSpeakerVoiceConfig object (MultiSpeakerVoiceConfig)

ज़रूरी नहीं. एक से ज़्यादा स्पीकर सेटअप करने के लिए कॉन्फ़िगरेशन. यह voiceConfig फ़ील्ड के साथ काम नहीं करता.

languageCode string

ज़रूरी नहीं. स्पीच सिंथेसिस के लिए भाषा कोड (BCP 47 फ़ॉर्मैट में, जैसे कि "en-US").

मान्य वैल्यू ये हैं: de-DE, en-AU, en-GB, en-IN, en-US, es-US, fr-FR, hi-IN, pt-BR, ar-XA, es-ES, fr-CA, id-ID, it-IT, ja-JP, tr-TR, vi-VN, bn-IN, gu-IN, kn-IN, ml-IN, mr-IN, ta-IN, te-IN, nl-NL, ko-KR, cmn-CN, pl-PL, ru-RU, और th-TH.

JSON के काेड में दिखाना
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}

VoiceConfig

आवाज़ का इस्तेमाल करने के लिए कॉन्फ़िगरेशन.

फ़ील्ड
voice_config Union type
स्पीकर के इस्तेमाल के लिए कॉन्फ़िगरेशन. voice_config इनमें से सिर्फ़ एक हो सकता है:
prebuiltVoiceConfig object (PrebuiltVoiceConfig)

इस्तेमाल करने के लिए, पहले से तैयार की गई आवाज़ का कॉन्फ़िगरेशन.

JSON के काेड में दिखाना
{

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

PrebuiltVoiceConfig

पहले से तैयार किए गए स्पीकर के इस्तेमाल के लिए कॉन्फ़िगरेशन.

Fields
voiceName string

इस्तेमाल की जाने वाली प्रीसेट आवाज़ का नाम.

JSON के काेड में दिखाना
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

एक से ज़्यादा स्पीकर सेटअप करने के लिए कॉन्फ़िगरेशन.

Fields
speakerVoiceConfigs[] object (SpeakerVoiceConfig)

ज़रूरी है. स्पीकर की सभी चालू की गई आवाज़ें.

JSON के काेड में दिखाना
{
  "speakerVoiceConfigs": [
    {
      object (SpeakerVoiceConfig)
    }
  ]
}

SpeakerVoiceConfig

एक से ज़्यादा स्पीकर वाले सेटअप में, किसी एक स्पीकर का कॉन्फ़िगरेशन.

Fields
speaker string

ज़रूरी है. इस्तेमाल किए जाने वाले स्पीकर का नाम. यह प्रॉम्प्ट में दिए गए नाम से मेल खाना चाहिए.

voiceConfig object (VoiceConfig)

ज़रूरी है. आवाज़ का इस्तेमाल करने के लिए कॉन्फ़िगरेशन.

JSON के काेड में दिखाना
{
  "speaker": string,
  "voiceConfig": {
    object (VoiceConfig)
  }
}

ThinkingConfig

सोचने की सुविधाओं के लिए कॉन्फ़िगरेशन.

Fields
includeThoughts boolean

इससे पता चलता है कि जवाब में सोच को शामिल करना है या नहीं. अगर सही है, तो जवाब सिर्फ़ तब दिखाए जाते हैं, जब वे उपलब्ध हों.

thinkingBudget integer

मॉडल को कितने थॉट टोकन जनरेट करने चाहिए.

JSON के काेड में दिखाना
{
  "includeThoughts": boolean,
  "thinkingBudget": integer
}

MediaResolution

इनपुट मीडिया के लिए मीडिया रिज़ॉल्यूशन.

Enums
MEDIA_RESOLUTION_UNSPECIFIED मीडिया का रिज़ॉल्यूशन सेट नहीं किया गया है.
MEDIA_RESOLUTION_LOW मीडिया का रिज़ॉल्यूशन कम पर सेट है (64 टोकन).
MEDIA_RESOLUTION_MEDIUM मीडिया रिज़ॉल्यूशन को मीडियम (256 टोकन) पर सेट किया गया है.
MEDIA_RESOLUTION_HIGH मीडिया रिज़ॉल्यूशन को हाई पर सेट किया गया है (256 टोकन के साथ ज़ूम करके रीफ़्रेम किया गया है).

HarmCategory

रेटिंग की कैटगरी.

इन कैटगरी में, अलग-अलग तरह के नुकसान शामिल हैं. डेवलपर इनमें बदलाव कर सकते हैं.

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 Gemini - उत्पीड़न करने वाला कॉन्टेंट.
HARM_CATEGORY_HATE_SPEECH Gemini - नफ़रत फैलाने वाली भाषा और कॉन्टेंट.
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini - साफ़ तौर पर सेक्शुअल ऐक्ट दिखाने वाला कॉन्टेंट.
HARM_CATEGORY_DANGEROUS_CONTENT Gemini - खतरनाक कॉन्टेंट.
HARM_CATEGORY_CIVIC_INTEGRITY

Gemini - ऐसा कॉन्टेंट जिसका इस्तेमाल, नागरिकता की अखंडता को नुकसान पहुंचाने के लिए किया जा सकता है. DEPRECATED: use enableEnhancedCivicAnswers instead.

ModalityTokenCount

यह किसी एक मोड के लिए टोकन की गिनती की जानकारी दिखाता है.

Fields
modality enum (Modality)

इस टोकन की गिनती से जुड़ी मोडेलिटी.

tokenCount integer

टोकन की संख्या.

JSON के काेड में दिखाना
{
  "modality": enum (Modality),
  "tokenCount": integer
}

मोडेलिटी

कॉन्टेंट के हिस्से की मोडेलिटी

Enums
MODALITY_UNSPECIFIED अनजान तरीका.
TEXT सामान्य टेक्स्ट.
IMAGE इमेज.
VIDEO वीडियो.
AUDIO ऑडियो.
DOCUMENT दस्तावेज़, जैसे कि PDF.

SafetyRating

किसी कॉन्टेंट के लिए सुरक्षा रेटिंग.

सुरक्षा रेटिंग में, किसी कॉन्टेंट से होने वाले नुकसान की कैटगरी और उस कैटगरी में नुकसान होने की संभावना का लेवल शामिल होता है. नुकसान पहुंचाने वाले कॉन्टेंट की कई कैटगरी के हिसाब से, कॉन्टेंट को सुरक्षित माना जाता है. साथ ही, इसमें नुकसान पहुंचाने वाले कॉन्टेंट की कैटगरी के हिसाब से कॉन्टेंट को सुरक्षित माने जाने की संभावना भी शामिल होती है.

Fields
category enum (HarmCategory)

ज़रूरी है. इस रेटिंग की कैटगरी.

probability enum (HarmProbability)

ज़रूरी है. इस कॉन्टेंट से नुकसान पहुंचने की संभावना.

blocked boolean

क्या इस रेटिंग की वजह से इस कॉन्टेंट को ब्लॉक किया गया था?

JSON के काेड में दिखाना
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}

HarmProbability

किसी कॉन्टेंट के नुकसान पहुंचाने की संभावना.

क्लासिफ़िकेशन सिस्टम, कॉन्टेंट के असुरक्षित होने की संभावना बताता है. इससे यह पता नहीं चलता कि किसी कॉन्टेंट से कितना नुकसान हुआ है.

Enums
HARM_PROBABILITY_UNSPECIFIED प्रॉबबिलिटी की जानकारी नहीं दी गई है.
NEGLIGIBLE कॉन्टेंट के सुरक्षित न होने की संभावना बहुत कम होती है.
LOW कॉन्टेंट के असुरक्षित होने की संभावना कम होती है.
MEDIUM कॉन्टेंट के असुरक्षित होने की संभावना सामान्य है.
HIGH कॉन्टेंट के असुरक्षित होने की संभावना ज़्यादा होती है.

SafetySetting

सुरक्षा सेटिंग, जो सुरक्षा से जुड़ी पाबंदी के तरीके पर असर डालती है.

किसी कैटगरी के लिए सुरक्षा सेटिंग को पास करने से, कॉन्टेंट के ब्लॉक होने की अनुमति वाली संभावना बदल जाती है.

Fields
category enum (HarmCategory)

ज़रूरी है. इस सेटिंग के लिए कैटगरी.

threshold enum (HarmBlockThreshold)

ज़रूरी है. यह विकल्प, नुकसान पहुंचाने वाले कॉन्टेंट को ब्लॉक करने के लिए, संभावना की सीमा को कंट्रोल करता है.

JSON के काेड में दिखाना
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

HarmBlockThreshold

नुकसान पहुंचाने की तय की गई संभावना के आधार पर, जवाब को ब्लॉक करना.

Enums
HARM_BLOCK_THRESHOLD_UNSPECIFIED थ्रेशोल्ड की जानकारी नहीं दी गई है.
BLOCK_LOW_AND_ABOVE जिस कॉन्टेंट में न के बराबर एआई का इस्तेमाल किया गया है उसे अनुमति दी जाएगी.
BLOCK_MEDIUM_AND_ABOVE जिन वीडियो में उल्लंघन का स्तर 'मामूली' और 'कम' होगा उन्हें अनुमति दी जाएगी.
BLOCK_ONLY_HIGH जिस कॉन्टेंट में जोखिम का स्तर न के बराबर, कम, और सामान्य होगा उसे अनुमति दी जाएगी.
BLOCK_NONE सभी कॉन्टेंट को अनुमति दी जाएगी.
OFF सुरक्षा फ़िल्टर की सुविधा बंद करें.