Generating content

Gemini API از تولید محتوا با تصاویر، صدا، کد، ابزار و موارد دیگر پشتیبانی می کند. برای جزئیات بیشتر در مورد هر یک از این ویژگی ها، کد نمونه متمرکز بر وظیفه را بخوانید و بررسی کنید، یا راهنمای جامع را بخوانید.

روش: models.generateContent

یک پاسخ مدل با یک ورودی GenerateContentRequest ایجاد می کند. برای اطلاعات دقیق استفاده به راهنمای تولید متن مراجعه کنید. قابلیت های ورودی بین مدل ها از جمله مدل های تنظیم شده متفاوت است. برای جزئیات به راهنمای مدل و راهنمای تنظیم مراجعه کنید.

نقطه پایانی پست https: / /generativelanguage.googleapis.com /v1beta /{model=models /*}:generateContent
پارامترهای مسیر
string model

مورد نیاز. نام Model که برای ایجاد تکمیل استفاده می شود.

قالب: models/{model} . شکل models/{model} را می‌گیرد.

درخواست بدن

بدنه درخواست حاوی داده هایی با ساختار زیر است:

فیلدها
contents[] object ( Content )

مورد نیاز. محتوای گفتگوی فعلی با مدل.

برای پرس و جوهای تک نوبتی، این یک نمونه است. برای جستجوهای چند نوبتی مانند چت ، این یک فیلد تکراری است که حاوی تاریخچه مکالمه و آخرین درخواست است.

tools[] object ( Tool )

اختیاری. فهرستی از Tools Model ممکن است برای ایجاد پاسخ بعدی استفاده کند.

Tool قطعه ای از کد است که سیستم را قادر می سازد تا با سیستم های خارجی برای انجام یک عمل یا مجموعه ای از اقدامات خارج از دانش و محدوده Model تعامل داشته باشد. Tool پشتیبانی شده Function و codeExecution هستند. برای کسب اطلاعات بیشتر به فراخوانی تابع و راهنمای اجرای کد مراجعه کنید.

شی toolConfig object ( ToolConfig )

اختیاری. پیکربندی ابزار برای هر Tool در درخواست مشخص شده است. برای مثال استفاده به راهنمای فراخوانی تابع مراجعه کنید.

شیء safetySettings[] object ( SafetySetting )

اختیاری. فهرستی از نمونه‌های SafetySetting منحصر به فرد برای مسدود کردن محتوای ناامن.

این در GenerateContentRequest.contents و GenerateContentResponse.candidates اعمال خواهد شد. برای هر نوع SafetyCategory نباید بیش از یک تنظیم وجود داشته باشد. API هر محتوا و پاسخی را که نتواند آستانه تعیین شده توسط این تنظیمات را برآورده کند مسدود می کند. این فهرست تنظیمات پیش‌فرض را برای هر SafetyCategory مشخص‌شده در تنظیمات ایمنی لغو می‌کند. اگر هیچ SafetySetting برای یک SafetyCategory معین در لیست ارائه نشده باشد، API از تنظیمات ایمنی پیش‌فرض برای آن دسته استفاده می‌کند. دسته‌های آسیب 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}

درخواست نمونه
متن
پایتون
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
جاوا
Client client = new Client();

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

System.out.println(response.text());
تصویر
پایتون
from google import genai
import PIL.Image

client = genai.Client()
organ = PIL.Image.open(media / "organ.jpg")
response = client.models.generate_content(
    model="gemini-2.0-flash", contents=["Tell me about this instrument", organ]
)
print(response.text)
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
جاوا
Client client = new Client();

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

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

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

System.out.println(response.text());
صوتی
پایتون
from google import genai

client = genai.Client()
sample_audio = client.files.upload(file=media / "sample.mp3")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
print(response.text)
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
ویدیو
پایتون
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
پایتون
from google import genai

client = genai.Client()
sample_pdf = client.files.upload(file=media / "test.pdf")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["Give me a summary of this document:", sample_pdf],
)
print(f"{response.text=}")
برو
ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

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

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

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

response, err := client.Models.GenerateContent(ctx, "gemini-2.0-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
printResponse(response)
پوسته
MIME_TYPE=$(file -b --mime-type "${PDF_PATH}")
NUM_BYTES=$(wc -c < "${PDF_PATH}")
DISPLAY_NAME=TEXT


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json
چت کنید
پایتون
from google import genai
from google.genai import types

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

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

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

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

GenerateContentResponse response2 = chat.sendMessage("How many paws are in my house?");
System.out.println(response2.text());
حافظه پنهان
پایتون
from google import genai
from google.genai import types

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

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

response = client.models.generate_content(
    model=model_name,
    contents="Please summarize this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)
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)
مدل کوک شده
پایتون
# With Gemini 2 we're launching a new SDK. See the following doc for details.
# https://ai.google.dev/gemini-api/docs/migrate
حالت JSON
پایتون
from google import genai
from google.genai import types
from typing_extensions import TypedDict

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

client = genai.Client()
result = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="List a few popular cookie recipes.",
    config=types.GenerateContentConfig(
        response_mime_type="application/json", response_schema=list[Recipe]
    ),
)
print(result)
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
جاوا
Client client = new Client();

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

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

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

System.out.println(response.text());
اجرای کد
پایتون
from google import genai
from google.genai import types

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

print("-" * 80)
# The .text accessor concatenates the parts into a markdown-formatted text.
print("\n", response.text)
برو
ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

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

// Print the response.
printResponse(response)

fmt.Println("--------------------------------------------------------------------------------")
fmt.Println(response.Text())
جاوا
Client client = new Client();

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

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

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

System.out.println("-".repeat(80));
System.out.println(response.text());
فراخوانی تابع
پایتون
from google import genai
from google.genai import types

client = genai.Client()

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

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

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

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

# Create a chat session; function calling (via tools) is enabled in the config.
chat = client.chats.create(
    model="gemini-2.0-flash",
    config=types.GenerateContentConfig(tools=[add, subtract, multiply, divide]),
)
response = chat.send_message(
    message="I have 57 cats, each owns 44 mittens, how many mittens is that in total?"
)
print(response.text)
برو
ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
modelName := "gemini-2.0-flash"

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

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

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

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

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

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

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

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

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

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

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

printResponse(finalResponse)
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'
جاوا
Client client = new Client();

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

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

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

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

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

                )
        )
        .build();

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


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

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

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

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

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

System.out.println(result);
پیکربندی نسل
پایتون
from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Tell me a story about a magic backpack.",
    config=types.GenerateContentConfig(
        candidate_count=1,
        stop_sequences=["x"],
        max_output_tokens=20,
        temperature=1.0,
    ),
)
print(response.text)
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"
جاوا
Client client = new Client();

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

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

System.out.println(response.text());
تنظیمات ایمنی
پایتون
from google import genai
from google.genai import types

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

print(response.candidates[0].safety_ratings)
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
جاوا
Client client = new Client();

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

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

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

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

System.out.println(response.candidates().get().getFirst().safetyRatings());
دستورالعمل سیستم
پایتون
from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Good morning! How are you?",
    config=types.GenerateContentConfig(
        system_instruction="You are a cat. Your name is Neko."
    ),
)
print(response.text)
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"}}}'
جاوا
Client client = new Client();

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

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

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

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

System.out.println(response.text());
بدن پاسخگو

در صورت موفقیت آمیز بودن، بدنه پاسخ حاوی نمونه ای از GenerateContentResponse است.

روش: models.streamGenerateContent

یک پاسخ جریانی از مدل با یک ورودی GenerateContentRequest ایجاد می کند.

نقطه پایانی پست https: / /generativelanguage.googleapis.com /v1beta /{model=models /*}:streamGenerateContent
پارامترهای مسیر
string model

مورد نیاز. نام Model که برای ایجاد تکمیل استفاده می شود.

قالب: models/{model} . شکل models/{model} را می‌گیرد.

درخواست بدن

بدنه درخواست حاوی داده هایی با ساختار زیر است:

فیلدها
contents[] object ( Content )

مورد نیاز. محتوای گفتگوی فعلی با مدل.

برای پرس و جوهای تک نوبتی، این یک نمونه است. برای جستجوهای چند نوبتی مانند چت ، این یک فیلد تکراری است که حاوی تاریخچه مکالمه و آخرین درخواست است.

tools[] object ( Tool )

اختیاری. فهرستی از Tools Model ممکن است برای ایجاد پاسخ بعدی استفاده کند.

Tool قطعه ای از کد است که سیستم را قادر می سازد تا با سیستم های خارجی برای انجام یک عمل یا مجموعه ای از اقدامات خارج از دانش و محدوده Model تعامل داشته باشد. Tool پشتیبانی شده Function و codeExecution هستند. برای کسب اطلاعات بیشتر به فراخوانی تابع و راهنمای اجرای کد مراجعه کنید.

شی toolConfig object ( ToolConfig )

اختیاری. پیکربندی ابزار برای هر Tool در درخواست مشخص شده است. برای مثال استفاده به راهنمای فراخوانی تابع مراجعه کنید.

شیء safetySettings[] object ( SafetySetting )

اختیاری. فهرستی از نمونه‌های SafetySetting منحصر به فرد برای مسدود کردن محتوای ناامن.

این در GenerateContentRequest.contents و GenerateContentResponse.candidates اعمال خواهد شد. برای هر نوع SafetyCategory نباید بیش از یک تنظیم وجود داشته باشد. API هر محتوا و پاسخی را که نتواند آستانه تعیین شده توسط این تنظیمات را برآورده کند مسدود می کند. این فهرست تنظیمات پیش‌فرض را برای هر SafetyCategory مشخص‌شده در تنظیمات ایمنی لغو می‌کند. اگر هیچ SafetySetting برای یک SafetyCategory معین در لیست ارائه نشده باشد، API از تنظیمات ایمنی پیش‌فرض برای آن دسته استفاده می‌کند. دسته‌های آسیب 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}

درخواست نمونه
متن
پایتون
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."}]}]}'
جاوا
Client client = new Client();

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

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

responseStream.close();
تصویر
پایتون
from google import genai
import PIL.Image

client = genai.Client()
organ = PIL.Image.open(media / "organ.jpg")
response = client.models.generate_content_stream(
    model="gemini-2.0-flash", contents=["Tell me about this instrument", organ]
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
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
جاوا
Client client = new Client();

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

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


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

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

responseStream.close();
صوتی
پایتون
from google import genai

client = genai.Client()
sample_audio = client.files.upload(file=media / "sample.mp3")
response = client.models.generate_content_stream(
    model="gemini-2.0-flash",
    contents=["Give me a summary of this audio file.", sample_audio],
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
برو
ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

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

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

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

for result, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-2.0-flash",
	contents,
	nil,
) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(result.Candidates[0].Content.Parts[0].Text)
}
پوسته
# Use File API to upload audio data to API request.
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo
ویدیو
پایتون
from google import genai
import time

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

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

response = client.models.generate_content_stream(
    model="gemini-2.0-flash", contents=[myfile, "Describe this video clip"]
)
for chunk in response:
    print(chunk.text)
    print("_" * 80)
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
پایتون
from google import genai

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

for chunk in response:
    print(chunk.text)
    print("_" * 80)
برو
ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

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

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

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

for result, err := range client.Models.GenerateContentStream(
	ctx,
	"gemini-2.0-flash",
	contents,
	nil,
) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(result.Candidates[0].Content.Parts[0].Text)
}
پوسته
MIME_TYPE=$(file -b --mime-type "${PDF_PATH}")
NUM_BYTES=$(wc -c < "${PDF_PATH}")
DISPLAY_NAME=TEXT


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo
چت کنید
پایتون
from google import genai
from google.genai import types

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

print(chat.get_history())
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 است.

Generate ContentResponse

پاسخ از مدلی که از چندین پاسخ نامزد پشتیبانی می کند.

رتبه‌بندی ایمنی و فیلتر محتوا هم برای prompt در GenerateContentResponse.prompt_feedback و هم برای هر نامزد در finishReason و در safetyRatings گزارش می‌شود. API: - همه نامزدهای درخواست شده یا هیچ یک از آنها را برمی‌گرداند - فقط در صورتی که مشکلی در درخواست وجود داشته باشد، هیچ نامزدی را برمی‌گرداند ( promptFeedback بررسی کنید) - بازخورد هر نامزد را در finishReason و safetyRatings گزارش می‌کند.

فیلدها
candidates[] object ( Candidate )

پاسخ های کاندیدا از مدل.

شیء promptFeedback object ( PromptFeedback )

بازخورد درخواست مربوط به فیلترهای محتوا را برمی‌گرداند.

شیء usageMetadata object ( UsageMetadata )

فقط خروجی فراداده در مورد استفاده از رمز درخواست های تولید.

string modelVersion

فقط خروجی نسخه مدل مورد استفاده برای ایجاد پاسخ.

string responseId

فقط خروجی answerId برای شناسایی هر پاسخ استفاده می شود.

نمایندگی JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string,
  "responseId": string
}
PromptFeedback

مجموعه ای از فراداده های بازخوردی که در GenerateContentRequest.content مشخص شده است.

فیلدها
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

فراداده در مورد استفاده از رمز درخواست تولید.

فیلدها
promptTokenCount integer

تعداد توکن ها در اعلان. هنگامی که cachedContent تنظیم می‌شود، این اندازه هنوز کل اندازه مؤثر است به این معنی که شامل تعداد نشانه‌های موجود در محتوای کش می‌شود.

cachedContentTokenCount integer

تعداد توکن ها در قسمت کش شده اعلان (محتوای ذخیره شده)

candidatesTokenCount integer

تعداد کل توکن ها در همه نامزدهای پاسخ تولید شده.

toolUsePromptTokenCount integer

فقط خروجی تعداد نشانه‌های موجود در اعلان (های) استفاده از ابزار.

thoughtsTokenCount integer

فقط خروجی تعداد نشانه های افکار برای مدل های تفکر.

totalTokenCount integer

تعداد کل توکن برای درخواست تولید (کاندیداهای سریع + پاسخ).

شی promptTokensDetails[] object ( ModalityTokenCount )

فقط خروجی فهرست روش هایی که در ورودی درخواست پردازش شدند.

شی cacheTokensDetails[] object ( ModalityTokenCount )

فقط خروجی فهرست روش‌های محتوای حافظه پنهان در ورودی درخواست.

شی candidatesTokensDetails[] object ( ModalityTokenCount )

فقط خروجی فهرست روش هایی که در پاسخ بازگردانده شد.

شی toolUsePromptTokensDetails[] object ( ModalityTokenCount )

فقط خروجی فهرست روش‌هایی که برای ورودی‌های درخواست استفاده از ابزار پردازش شده‌اند.

نمایندگی JSON
{
  "promptTokenCount": integer,
  "cachedContentTokenCount": integer,
  "candidatesTokenCount": integer,
  "toolUsePromptTokenCount": integer,
  "thoughtsTokenCount": integer,
  "totalTokenCount": integer,
  "promptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "cacheTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "candidatesTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "toolUsePromptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ]
}
نامزد

یک کاندید پاسخ تولید شده از مدل.

فیلدها
شی content object ( Content )

فقط خروجی محتوای تولید شده از مدل برگردانده شده است.

finishReason enum ( FinishReason )

اختیاری. فقط خروجی دلیل توقف تولید توکن توسط مدل.

اگر خالی باشد، مدل تولید توکن را متوقف نکرده است.

safetyRatings[] object ( SafetyRating )

فهرست رتبه بندی برای ایمنی یک نامزد پاسخ.

حداکثر یک رتبه برای هر دسته وجود دارد.

citationMetadata object ( CitationMetadata )

فقط خروجی اطلاعات استناد برای نامزد تولید شده توسط مدل.

این قسمت ممکن است با اطلاعات تلاوت برای هر متن موجود در content پر شود. این‌ها قسمت‌هایی هستند که از مطالب دارای حق چاپ در داده‌های آموزشی بنیادی LLM «خوانده می‌شوند».

tokenCount integer

فقط خروجی شمارش رمز برای این نامزد.

شی groundingAttributions[] object ( GroundingAttribution )

فقط خروجی اطلاعات انتساب برای منابعی که به یک پاسخ پایه کمک کرده اند.

این فیلد برای تماس‌های GenerateAnswer پر شده است.

شیء groundingMetadata object ( GroundingMetadata )

فقط خروجی متاداده پایه برای نامزد.

این فیلد برای تماس‌های GenerateContent پر شده است.

number avgLogprobs

فقط خروجی میانگین امتیاز احتمال ورود نامزد.

شیء logprobsResult object ( LogprobsResult )

فقط خروجی امتیازات لاگ احتمال برای توکن های پاسخ و نشانه های برتر

شی urlContextMetadata object ( UrlContextMetadata )

فقط خروجی فراداده مربوط به ابزار بازیابی زمینه آدرس اینترنتی.

integer index

فقط خروجی فهرست نامزد در لیست کاندیداهای پاسخ.

finishMessage string پیام

اختیاری. فقط خروجی دلیل توقف تولید توکن ها توسط مدل را شرح می دهد. این فقط زمانی پر می شود که finishReason تنظیم شده باشد.

نمایندگی JSON
{
  "content": {
    object (Content)
  },
  "finishReason": enum (FinishReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ],
  "citationMetadata": {
    object (CitationMetadata)
  },
  "tokenCount": integer,
  "groundingAttributions": [
    {
      object (GroundingAttribution)
    }
  ],
  "groundingMetadata": {
    object (GroundingMetadata)
  },
  "avgLogprobs": number,
  "logprobsResult": {
    object (LogprobsResult)
  },
  "urlContextMetadata": {
    object (UrlContextMetadata)
  },
  "index": integer,
  "finishMessage": string
}
FinishReason

دلیل توقف تولید توکن ها توسط مدل را مشخص می کند.

Enums
FINISH_REASON_UNSPECIFIED مقدار پیش فرض این مقدار استفاده نشده است.
STOP نقطه توقف طبیعی مدل یا توالی توقف ارائه شده.
MAX_TOKENS حداکثر تعداد توکن‌هایی که در درخواست مشخص شده بود به دست آمد.
SAFETY محتوای نامزد پاسخ به دلایل ایمنی پرچم گذاری شد.
RECITATION محتوای نامزد پاسخ به دلایل تلاوت پرچم گذاری شد.
LANGUAGE محتوای نامزد پاسخ به دلیل استفاده از زبان پشتیبانی نشده پرچم گذاری شد.
OTHER دلیل نامعلوم
BLOCKLIST تولید رمز متوقف شد زیرا محتوا حاوی عبارات ممنوع است.
PROHIBITED_CONTENT تولید رمز به دلیل داشتن محتوای ممنوعه متوقف شد.
SPII تولید رمز متوقف شد زیرا محتوا به طور بالقوه حاوی اطلاعات قابل شناسایی شخصی حساس (SPII) است.
MALFORMED_FUNCTION_CALL فراخوانی تابع تولید شده توسط مدل نامعتبر است.
IMAGE_SAFETY تولید توکن متوقف شد زیرا تصاویر تولید شده حاوی نقض ایمنی هستند.
IMAGE_PROHIBITED_CONTENT تولید تصویر متوقف شد زیرا تصاویر تولید شده دارای محتوای ممنوعه دیگری هستند.
IMAGE_OTHER تولید تصویر به دلیل مشکلات متفرقه دیگر متوقف شد.
NO_IMAGE انتظار می‌رفت که این مدل یک تصویر تولید کند، اما هیچ‌کدام ایجاد نشد.
IMAGE_RECITATION تولید تصویر به دلیل تلاوت متوقف شد.
UNEXPECTED_TOOL_CALL مدل یک فراخوانی ابزار ایجاد کرد اما هیچ ابزاری در درخواست فعال نشد.
TOO_MANY_TOOL_CALLS مدل به طور متوالی ابزارهای زیادی را فراخوانی کرد، بنابراین سیستم از اجرا خارج شد.
GroundingAttribution

ذکر منبعی که به یک پاسخ کمک کرده است.

فیلدها
شی 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 که از طریق Semantic Retriever واکشی شده است.

نمایندگی JSON
{

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

شناسه بخشی در GroundingPassage .

فیلدها
string passageId

فقط خروجی شناسه متن مطابق با GenerateAnswerRequest 's GroundingPassage.id .

partIndex integer

فقط خروجی فهرست بخش در GroundingPassage.content GenerateAnswerRequest .

نمایندگی JSON
{
  "passageId": string,
  "partIndex": integer
}
SemanticRetrieverChunk

شناسه یک Chunk بازیابی شده از طریق Semantic Retriever مشخص شده در GenerateAnswerRequest با استفاده از SemanticRetrieverConfig .

فیلدها
string source

فقط خروجی نام منبعی که SemanticRetrieverConfig.source درخواست مطابقت دارد. مثال: corpora/123 یا corpora/123/documents/abc

string chunk ای

فقط خروجی نام Chunk حاوی متن نسبت داده شده. مثال: corpora/123/documents/abc/chunks/xyz

نمایندگی JSON
{
  "source": string,
  "chunk": string
}
GroundingMetadata

هنگامی که اتصال زمین فعال است، متادیتا به مشتری بازگردانده می شود.

فیلدها
شی groundingChunks[] object ( GroundingChunk )

فهرست منابع پشتیبان بازیابی شده از منبع زمینی مشخص شده.

شی groundingSupports[] object ( GroundingSupport )

لیست پشتیبانی از زمین

string webSearchQueries[]

جستارهای جستجوی وب برای جستجوی وب بعدی.

شی searchEntryPoint object ( SearchEntryPoint )

اختیاری. ورودی جستجوی گوگل برای جستجوهای وب بعدی.

object ( RetrievalMetadata ) retrievalMetadata ( RetrievalMetadata )

فراداده مربوط به بازیابی در جریان زمین.

نمایندگی JSON
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  }
}
SearchEntryPoint

نقطه ورودی جستجوی گوگل

فیلدها
renderedContent string

اختیاری. قطعه محتوای وب که می تواند در یک صفحه وب یا نمای وب برنامه جاسازی شود.

رشته sdkBlob string ( bytes format)

اختیاری. Base64 JSON کدگذاری شده آرایه ای از تاپل <search term, search url> را نشان می دهد.

رشته ای با کد base64.

نمایندگی JSON
{
  "renderedContent": string,
  "sdkBlob": string
}
GroundingChunk

قطعه زمین.

فیلدها
chunk_type Union type
نوع تکه ای. chunk_type فقط می تواند یکی از موارد زیر باشد:
شیء web object ( Web )

زمین کردن تکه از وب.

شیء retrievedContext object ( RetrievedContext )

اختیاری. قطعه زمینی از زمینه بازیابی شده توسط ابزار جستجوی فایل.

نمایندگی JSON
{

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

تکه ای از وب.

فیلدها
string uri

مرجع URI قطعه.

string title

عنوان تکه.

نمایندگی JSON
{
  "uri": string,
  "title": string
}
RetrievedContext

تکه‌ای از متن بازیابی شده توسط ابزار جستجوی فایل.

فیلدها
string uri

اختیاری. مرجع URI سند بازیابی معنایی.

string title

اختیاری. عنوان سند

string text

اختیاری. متن تکه.

نمایندگی JSON
{
  "uri": string,
  "title": string,
  "text": string
}
GroundingSupport

پشتیبانی زمین.

فیلدها
groundingChunkIndices[] integer

فهرستی از شاخص‌ها (به «grounding_chunk») که استنادهای مرتبط با ادعا را مشخص می‌کند. برای مثال [1،3،4] به این معنی است که grounding_chunk[1]، grounding_chunk[3]، grounding_chunk[4] محتوای بازیابی شده منتسب به ادعا هستند.



امتیاز اعتماد مراجع پشتیبانی محدوده از 0 تا 1. 1 مطمئن ترین است. اندازه این لیست باید به اندازه groundingChunkIndices باشد.

segment object ( Segment )

بخشی از محتوایی که این پشتیبانی به آن تعلق دارد.

نمایندگی JSON
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}
بخش

بخش محتوا

فیلدها
partIndex integer

فقط خروجی نمایه یک شی Part در شیء محتوای مادر آن.

startIndex integer

فقط خروجی شاخص شروع در قسمت داده شده، در بایت اندازه گیری می شود. آفست از شروع قطعه، شامل، با شروع از صفر.

endIndex integer

فقط خروجی نمایه پایان در قسمت داده شده، بر حسب بایت اندازه گیری می شود. افست از شروع قطعه، انحصاری، شروع از صفر.

string text

فقط خروجی متن مربوط به بخش از پاسخ.

نمایندگی JSON
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}
RetrievalMetadata

فراداده مربوط به بازیابی در جریان زمین.

فیلدها
number googleSearchDynamicRetrievalScore

اختیاری. امتیاز نشان می‌دهد که اطلاعات جستجوی Google چقدر می‌تواند به پاسخگویی به درخواست کمک کند. امتیاز در محدوده [0، 1] است که 0 کمترین احتمال و 1 محتمل ترین است. این امتیاز تنها زمانی جمع می شود که جستجوی google grounding و بازیابی پویا فعال باشد. برای تعیین اینکه آیا جستجوی گوگل راه اندازی شود یا خیر، با آستانه مقایسه می شود.

نمایندگی JSON
{
  "googleSearchDynamicRetrievalScore": number
}
Logprobs Result

نتایج Logprobs

فیلدها
topCandidates[] object ( TopCandidates )

طول = تعداد کل مراحل رمزگشایی.

object ( Candidate ) chosenCandidates[] ( نامزد )

طول = تعداد کل مراحل رمزگشایی. نامزدهای انتخاب شده ممکن است در topCandidates باشند یا نباشند.

number logProbabilitySum

مجموع احتمالات لاگ برای همه توکن ها.

نمایندگی JSON
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ],
  "logProbabilitySum": number
}
Top Candidates

کاندیداهایی که در هر مرحله رمزگشایی احتمالات ثبت بالا را دارند.

فیلدها
candidates[] object ( Candidate )

بر اساس احتمال گزارش به ترتیب نزولی مرتب شده است.

نمایندگی JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}
نامزد

نامزد برای نشانه و امتیاز logprobs.

فیلدها
string token

مقدار رشته رمز نامزد.

tokenId integer

مقدار شناسه رمز نامزد.

logProbability number احتمال

احتمال ثبت نام نامزد.

نمایندگی JSON
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}
UrlContextMetadata

فراداده مربوط به ابزار بازیابی زمینه آدرس اینترنتی.

فیلدها
شی urlMetadata[] object ( UrlMetadata )

فهرست زمینه url.

نمایندگی JSON
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}
UrlMetadata

زمینه بازیابی یک URL واحد.

فیلدها
retrievedUrl string

آدرس اینترنتی توسط ابزار بازیابی شده است.

urlRetrievalStatus enum ( UrlRetrievalStatus )

وضعیت بازیابی url.

نمایندگی JSON
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}
UrlRetrievalStatus

وضعیت بازیابی url.

Enums
URL_RETRIEVAL_STATUS_UNSPECIFIED مقدار پیش فرض این مقدار استفاده نشده است.
URL_RETRIEVAL_STATUS_SUCCESS بازیابی آدرس اینترنتی با موفقیت انجام شد.
URL_RETRIEVAL_STATUS_ERROR بازیابی آدرس اینترنتی به دلیل خطا انجام نشد.
URL_RETRIEVAL_STATUS_PAYWALL بازیابی URL انجام نشد زیرا محتوا پشت دیوار پرداخت است.
URL_RETRIEVAL_STATUS_UNSAFE بازیابی URL انجام نشد زیرا محتوا ناامن است.
CitationMetadata

مجموعه ای از منابع منبع برای یک قطعه محتوا.

فیلدها
شی citationSources[] object ( CitationSource )

استناد به منابع برای پاسخ خاص.

نمایندگی JSON
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}
منبع استناد

استناد به یک منبع برای بخشی از یک پاسخ خاص.

فیلدها
startIndex integer

اختیاری. شروع بخش پاسخی که به این منبع نسبت داده می شود.

شاخص شروع بخش را نشان می دهد که در بایت اندازه گیری می شود.

endIndex integer

اختیاری. انتهای بخش منتسب، انحصاری.

string uri

اختیاری. URI که به عنوان منبع بخشی از متن نسبت داده می شود.

string license

اختیاری. مجوز برای پروژه GitHub که به عنوان منبعی برای بخش نسبت داده می شود.

اطلاعات مجوز برای استناد کد مورد نیاز است.

نمایندگی JSON
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}
GenerationConfig

گزینه های پیکربندی برای تولید مدل و خروجی ها. همه پارامترها برای هر مدلی قابل تنظیم نیستند.

فیلدها
string stopSequences[]

اختیاری. مجموعه ای از دنباله های کاراکتر (تا 5) که تولید خروجی را متوقف می کند. اگر مشخص شود، API در اولین ظاهر یک stop_sequence متوقف می‌شود. توالی توقف به عنوان بخشی از پاسخ درج نخواهد شد.

string responseMimeType

اختیاری. نوع 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 روی یک طرح فرعی تنظیم شود، هیچ ویژگی دیگری به جز آنهایی که با $ شروع می‌شوند، نمی‌توانند تنظیم شوند.

مقدار responseJsonSchema value ( Value format)

اختیاری. یک جزئیات داخلی به جای این فیلد از responseJsonSchema استفاده کنید.

responseModalities[] enum ( Modality )

اختیاری. روشهای درخواستی پاسخ. مجموعه ای از روش هایی را نشان می دهد که مدل می تواند بازگرداند و باید در پاسخ انتظار داشت. این دقیقاً مطابق با روش‌های پاسخ است.

یک مدل ممکن است چندین ترکیب از روش های پشتیبانی شده داشته باشد. اگر روش‌های درخواستی با هیچ یک از ترکیب‌های پشتیبانی‌شده مطابقت نداشته باشند، یک خطا برگردانده می‌شود.

یک لیست خالی معادل درخواست فقط متن است.

candidateCount integer

اختیاری. تعداد پاسخ های تولید شده برای بازگشت. اگر تنظیم نشود، به طور پیش‌فرض روی ۱ خواهد بود. لطفاً توجه داشته باشید که این برای مدل‌های نسل قبلی (خانواده Gemini 1.0) کار نمی‌کند.

maxOutputTokens integer

اختیاری. حداکثر تعداد نشانه هایی که باید در یک نامزد پاسخ گنجانده شود.

توجه: مقدار پیش فرض بسته به مدل متفاوت است، به ویژگی Model.output_token_limit Model بازگشتی از تابع getModel مراجعه کنید.

number temperature

اختیاری. تصادفی بودن خروجی را کنترل می کند.

توجه: مقدار پیش فرض بر اساس مدل متفاوت است، به ویژگی Model.temperature Model بازگشتی از تابع getModel مراجعه کنید.

مقادیر می توانند از [0.0، 2.0] متغیر باشند.

number topP

اختیاری. حداکثر احتمال تجمعی نشانه هایی که باید در هنگام نمونه گیری در نظر گرفته شوند.

این مدل از نمونه برداری ترکیبی Top-k و Top-p (هسته) استفاده می کند.

توکن ها بر اساس احتمالات اختصاص داده شده مرتب می شوند تا فقط محتمل ترین توکن ها در نظر گرفته شوند. نمونه‌گیری Top-k مستقیماً حداکثر تعداد توکن‌های مورد نظر را محدود می‌کند، در حالی که نمونه‌برداری هسته‌ای تعداد نشانه‌ها را بر اساس احتمال تجمعی محدود می‌کند.

توجه: مقدار پیش‌فرض براساس Model متفاوت است و با ویژگی Model.top_p که از تابع getModel برگردانده شده است، مشخص می‌شود. یک ویژگی topK خالی نشان می‌دهد که مدل نمونه‌گیری top-k را اعمال نمی‌کند و اجازه تنظیم topK در درخواست‌ها نمی‌دهد.

topK integer

اختیاری. حداکثر تعداد نشانه هایی که باید در هنگام نمونه گیری در نظر گرفته شود.

مدل های Gemini از نمونه برداری Top-p (هسته) یا ترکیبی از نمونه برداری Top-k و هسته استفاده می کنند. نمونه گیری Top-k مجموعه ای از محتمل ترین توکن های topK را در نظر می گیرد. مدل‌هایی که با نمونه‌برداری هسته اجرا می‌شوند، اجازه تنظیم topK را نمی‌دهند.

توجه: مقدار پیش‌فرض براساس Model متفاوت است و با ویژگی Model.top_p که از تابع getModel برگردانده شده است، مشخص می‌شود. یک ویژگی topK خالی نشان می‌دهد که مدل نمونه‌گیری top-k را اعمال نمی‌کند و اجازه تنظیم topK در درخواست‌ها نمی‌دهد.

integer seed

اختیاری. بذر مورد استفاده در رمزگشایی اگر تنظیم نشود، درخواست از یک دانه تولید شده به طور تصادفی استفاده می کند.

presencePenalty number جریمه

اختیاری. اگر نشانه قبلاً در پاسخ دیده شده باشد، جریمه حضور برای logprobs نشانه بعدی اعمال می شود.

این پنالتی باینری روشن/خاموش است و به تعداد دفعات استفاده از توکن (بعد از اولین بار) بستگی ندارد. برای جریمه ای که با هر بار استفاده افزایش می یابد، از frequencyPenalty استفاده کنید.

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

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

frequencyPenalty number

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

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

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

responseLogprobs boolean

اختیاری. If true, export the logprobs results in response.

logprobs integer

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

enableEnhancedCivicAnswers boolean

اختیاری. Enables enhanced civic answers. It may not be available for all models.

speechConfig object ( SpeechConfig )

اختیاری. The speech generation config.

thinkingConfig object ( ThinkingConfig )

اختیاری. Config for thinking features. An error will be returned if this field is set for models that don't support thinking.

imageConfig object ( ImageConfig )

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

mediaResolution enum ( MediaResolution )

اختیاری. If specified, the media resolution specified will be used.

JSON representation
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "_responseJsonSchema": value,
  "responseJsonSchema": value,
  "responseModalities": [
    enum (Modality)
  ],
  "candidateCount": integer,
  "maxOutputTokens": integer,
  "temperature": number,
  "topP": number,
  "topK": integer,
  "seed": integer,
  "presencePenalty": number,
  "frequencyPenalty": number,
  "responseLogprobs": boolean,
  "logprobs": integer,
  "enableEnhancedCivicAnswers": boolean,
  "speechConfig": {
    object (SpeechConfig)
  },
  "thinkingConfig": {
    object (ThinkingConfig)
  },
  "imageConfig": {
    object (ImageConfig)
  },
  "mediaResolution": enum (MediaResolution)
}
مدالیته

Supported modalities of the response.

Enums
MODALITY_UNSPECIFIED Default value.
TEXT Indicates the model should return text.
IMAGE Indicates the model should return images.
AUDIO Indicates the model should return audio.
SpeechConfig

The speech generation config.

فیلدها
voiceConfig object ( VoiceConfig )

The configuration in case of single-voice output.

multiSpeakerVoiceConfig object ( MultiSpeakerVoiceConfig )

اختیاری. The configuration for the multi-speaker setup. It is mutually exclusive with the voiceConfig field.

languageCode string

اختیاری. Language code (in BCP 47 format, eg "en-US") for speech synthesis.

Valid values are: de-DE, en-AU, en-GB, en-IN, en-US, es-US, fr-FR, hi-IN, pt-BR, ar-XA, es-ES, fr-CA, id-ID, it-IT, ja-JP, tr-TR, vi-VN, bn-IN, gu-IN, kn-IN, ml-IN, mr-IN, ta-IN, te-IN, nl-NL, ko-KR, cmn-CN, pl-PL, ru-RU, and th-TH.

JSON representation
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}
VoiceConfig

The configuration for the voice to use.

فیلدها
voice_config Union type
The configuration for the speaker to use. voice_config can be only one of the following:
prebuiltVoiceConfig object ( PrebuiltVoiceConfig )

The configuration for the prebuilt voice to use.

JSON representation
{

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

The configuration for the prebuilt speaker to use.

فیلدها
voiceName string

The name of the preset voice to use.

JSON representation
{
  "voiceName": string
}
MultiSpeakerVoiceConfig

The configuration for the multi-speaker setup.

فیلدها
speakerVoiceConfigs[] object ( SpeakerVoiceConfig )

مورد نیاز. All the enabled speaker voices.

JSON representation
{
  "speakerVoiceConfigs": [
    {
      object (SpeakerVoiceConfig)
    }
  ]
}
SpeakerVoiceConfig

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

فیلدها
speaker string

مورد نیاز. The name of the speaker to use. Should be the same as in the prompt.

voiceConfig object ( VoiceConfig )

مورد نیاز. The configuration for the voice to use.

JSON representation
{
  "speaker": string,
  "voiceConfig": {
    object (VoiceConfig)
  }
}
ThinkingConfig

Config for thinking features.

فیلدها
includeThoughts boolean

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

thinkingBudget integer

The number of thoughts tokens that the model should generate.

JSON representation
{
  "includeThoughts": boolean,
  "thinkingBudget": integer
}
ImageConfig

Config for image generation features.

فیلدها
aspectRatio string

اختیاری. The aspect ratio of the image to generate. Supported aspect ratios: 1:1, 2:3, 3:2, 3:4, 4:3, 9:16, 16:9, 21:9.

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

JSON representation
{
  "aspectRatio": string
}
MediaResolution

Media resolution for the input media.

Enums
MEDIA_RESOLUTION_UNSPECIFIED Media resolution has not been set.
MEDIA_RESOLUTION_LOW Media resolution set to low (64 tokens).
MEDIA_RESOLUTION_MEDIUM Media resolution set to medium (256 tokens).
MEDIA_RESOLUTION_HIGH Media resolution set to high (zoomed reframing with 256 tokens).
HarmCategory

The category of a rating.

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

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

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

ModalityTokenCount

Represents token counting info for a single modality.

فیلدها
modality enum ( Modality )

The modality associated with this token count.

tokenCount integer

Number of tokens.

JSON representation
{
  "modality": enum (Modality),
  "tokenCount": integer
}
مدالیته

Content Part modality

Enums
MODALITY_UNSPECIFIED Unspecified modality.
TEXT متن ساده
IMAGE تصویر.
VIDEO ویدئو.
AUDIO صوتی.
DOCUMENT Document, eg PDF.
SafetyRating

Safety rating for a piece of content.

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

فیلدها
category enum ( HarmCategory )

مورد نیاز. The category for this rating.

probability enum ( HarmProbability )

مورد نیاز. The probability of harm for this content.

blocked boolean

Was this content blocked because of this rating?

JSON representation
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}
HarmProbability

The probability that a piece of content is harmful.

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

Enums
HARM_PROBABILITY_UNSPECIFIED Probability is unspecified.
NEGLIGIBLE Content has a negligible chance of being unsafe.
LOW Content has a low chance of being unsafe.
MEDIUM Content has a medium chance of being unsafe.
HIGH Content has a high chance of being unsafe.
SafetySetting

Safety setting, affecting the safety-blocking behavior.

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

فیلدها
category enum ( HarmCategory )

مورد نیاز. The category for this setting.

threshold enum ( HarmBlockThreshold )

مورد نیاز. Controls the probability threshold at which harm is blocked.

JSON representation
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}
HarmBlockThreshold

Block at and beyond a specified harm probability.

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