Generating content

تتيح Gemini API إنشاء المحتوى باستخدام الصور والصوت والرموز البرمجية والأدوات وغير ذلك. للاطّلاع على تفاصيل حول كلّ من هذه الميزات، واصِل القراءة واطّلِع على نموذج الرموز البرمجية المخصّص للمهام، أو اطّلِع على الأدلة الشاملة.

الطريقة: models.generateContent

تُنشئ هذه الوظيفة نموذجًا للردّ استنادًا إلى إدخال GenerateContentRequest. يُرجى الرجوع إلى دليل إنشاء النصوص للحصول على معلومات تفصيلية عن الاستخدام. تختلف إمكانات الإدخال بين النماذج، بما في ذلك النماذج المحسّنة. يُرجى الرجوع إلى دليل النماذج ودليل الضبط للاطّلاع على التفاصيل.

نقطة نهاية

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

يستخدِم عنوان URL بنية تحويل ترميز gRPC.

مَعلمات المسار

model string

مطلوب. اسم Model المراد استخدامه لإنشاء الإنجاز.

التنسيق: models/{model} يكون على الشكل models/{model}.

نص الطلب

يحتوي نص الطلب على بيانات بالبنية التالية:

الحقول
contents[] object (Content)

مطلوب. محتوى المحادثة الحالية مع النموذج

بالنسبة إلى طلبات البحث التي تتضمّن جولة واحدة، يكون هذا مثيلًا واحدًا. بالنسبة إلى طلبات البحث التي تتضمّن عدّة أدوار، مثل chat، هذا حقل متكرّر يحتوي على سجلّ المحادثة وآخر طلب.

tools[] object (Tool)

اختياريّ. قائمة Tools التي قد يستخدمها Model لإنشاء الردّ التالي

Tool هو عبارة عن قطعة رمز تتيح للنظام التفاعل مع الأنظمة الخارجية لتنفيذ إجراء أو مجموعة من الإجراءات خارج نطاق المعرفة والمسؤوليات الخاصة بالتطبيق.Model Tool المتوافقة هي Function وcodeExecution. راجِع دليلَي استدعاء الدوال وتنفيذ الرموز البرمجية للاطّلاع على مزيد من المعلومات.

toolConfig object (ToolConfig)

اختياريّ. إعدادات الأداة لأي Tool محدّد في الطلب يُرجى الرجوع إلى دليل استدعاء الدوالّ للاطّلاع على مثال على الاستخدام.

safetySettings[] object (SafetySetting)

اختياريّ. قائمة بمثيلات SafetySetting الفريدة لحظر المحتوى غير الآمن

سيتم فرض هذا التغيير على GenerateContentRequest.contents وGenerateContentResponse.candidates. يجب ألا يكون هناك أكثر من إعداد واحد لكل نوع SafetyCategory. ستحظر واجهة برمجة التطبيقات أي محتوى أو ردّ لا يستوفي الحدّ الأدنى الذي تحدّده هذه الإعدادات. تلغي هذه القائمة الإعدادات التلقائية لكل SafetyCategory محدّد في safetySettings. إذا لم يكن هناك SafetySetting لـ SafetyCategory معيّن مقدَّم في القائمة، ستستخدم واجهة برمجة التطبيقات إعدادات السلامة التلقائية لهذه الفئة. يمكن استخدام فئات المحتوى الضار HARM_CATEGORY_HATE_SPEECH وHARM_CATEGORY_SEXUALLY_EXPLICIT وHARM_CATEGORY_DANGEROUS_CONTENT وHARM_CATEGORY_HARASSMENT وHARM_CATEGORY_CIVIC_INTEGRITY. يُرجى الرجوع إلى الدليل للحصول على معلومات تفصيلية عن إعدادات الأمان المتاحة. يمكنك أيضًا الرجوع إلى إرشادات السلامة للتعرّف على كيفية دمج اعتبارات السلامة في تطبيقات الذكاء الاصطناعي.

systemInstruction object (Content)

اختياريّ. ضبط المطوّر تعليمات النظام يتوفّر حاليًا النص فقط.

generationConfig object (GenerationConfig)

اختياريّ. خيارات الضبط لإنشاء النماذج والنواتج

cachedContent string

اختياريّ. اسم المحتوى المخزّن مؤقتًا لاستخدامه كسياق لعرض التوقّعات التنسيق: cachedContents/{cachedContent}

مثال على الطلب

نص

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Write a story about a magic backpack.";

const result = await model.generateContent(prompt);
console.log(result.response.text());

انتقال

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

محارة

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

Kotlin

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

val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)

Swift

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

let prompt = "Write a story about a magic backpack."
let response = try await generativeModel.generateContent(prompt)
if let text = response.text {
  print(text)
}

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Write a story about a magic backpack.';

final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Java

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

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

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

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

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

صورة

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType,
    },
  };
}

const prompt = "Describe how this product might be manufactured.";
// Note: The only accepted mime types are some image types, image/*.
const imagePart = fileToGenerativePart(
  `${mediaPath}/jetpack.jpg`,
  "image/jpeg",
);

const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());

انتقال

model := client.GenerativeModel("gemini-1.5-flash")

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

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

printResponse(resp)

محارة

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

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

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

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

Kotlin

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

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

val response = generativeModel.generateContent(inputContent)
print(response.text)

Swift

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

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

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

let response = try await generativeModel.generateContent(image, prompt)
if let text = response.text {
  print(text)
}

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);

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

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

final response = await model.generateContent([
  Content.multi([TextPart(prompt), image])
]);
print(response.text);

Java

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

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

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

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

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

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

الصوت

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType,
    },
  };
}

const prompt = "Give me a summary of this audio file.";
// Note: The only accepted mime types are some image types, image/*.
const audioPart = fileToGenerativePart(
  `${mediaPath}/samplesmall.mp3`,
  "audio/mp3",
);

const result = await model.generateContent([prompt, audioPart]);
console.log(result.response.text());

محارة

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

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_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-1.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Please describe this file."},
          {"file_data":{"mime_type": "audio/mpeg", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

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

فيديو

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
// import { GoogleAIFileManager, FileState } from "@google/generative-ai/server";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/Big_Buck_Bunny.mp4`,
  { mimeType: "video/mp4" },
);

let file = await fileManager.getFile(uploadResult.file.name);
while (file.state === FileState.PROCESSING) {
  process.stdout.write(".");
  // Sleep for 10 seconds
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  // Fetch the file from the API again
  file = await fileManager.getFile(uploadResult.file.name);
}

if (file.state === FileState.FAILED) {
  throw new Error("Video processing failed.");
}

const prompt = "Describe this video clip";
const videoPart = {
  fileData: {
    fileUri: uploadResult.file.uri,
    mimeType: uploadResult.file.mimeType,
  },
};

const result = await model.generateContent([prompt, videoPart]);
console.log(result.response.text());

انتقال

model := client.GenerativeModel("gemini-1.5-flash")

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

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

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

printResponse(resp)

محارة

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

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_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-1.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions."},
          {"file_data":{"mime_type": "video/mp4", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

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

PDF

Python

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

محارة

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=${GOOGLE_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-1.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Can you add a few more lines to this poem?"},
          {"file_data":{"mime_type": "application/pdf", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

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

دردشة

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: [{ text: "Hello" }],
    },
    {
      role: "model",
      parts: [{ text: "Great to meet you. What would you like to know?" }],
    },
  ],
});
let result = await chat.sendMessage("I have 2 dogs in my house.");
console.log(result.response.text());
result = await chat.sendMessage("How many paws are in my house?");
console.log(result.response.text());

انتقال

model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()

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

res, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))
if err != nil {
	log.Fatal(err)
}
printResponse(res)

محارة

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_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"

Kotlin

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

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

val response = chat.sendMessage("How many paws are in my house?")
print(response.text)

Swift

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

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

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

// To generate text output, call sendMessage and pass in the message
let response = try await chat.sendMessage("How many paws are in my house?")
if let text = response.text {
  print(text)
}

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final chat = model.startChat(history: [
  Content.text('hello'),
  Content.model([TextPart('Great to meet you. What would you like to know?')])
]);
var response =
    await chat.sendMessage(Content.text('I have 2 dogs in my house.'));
print(response.text);
response =
    await chat.sendMessage(Content.text('How many paws are in my house?'));
print(response.text);

Java

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

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

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

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

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

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

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

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

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

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

ذاكرة التخزين المؤقت

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const cacheManager = new GoogleAICacheManager(process.env.API_KEY);
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
});

const cacheResult = await cacheManager.create({
  model: "models/gemini-1.5-flash-001",
  contents: [
    {
      role: "user",
      parts: [
        {
          fileData: {
            fileUri: uploadResult.file.uri,
            mimeType: uploadResult.file.mimeType,
          },
        },
      ],
    },
  ],
});

console.log(cacheResult);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModelFromCachedContent(cacheResult);
const result = await model.generateContent(
  "Please summarize this transcript.",
);
console.log(result.response.text());

النموذج المحسَّن

Python

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

وضع JSON

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI, SchemaType } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

const schema = {
  description: "List of recipes",
  type: SchemaType.ARRAY,
  items: {
    type: SchemaType.OBJECT,
    properties: {
      recipeName: {
        type: SchemaType.STRING,
        description: "Name of the recipe",
        nullable: false,
      },
    },
    required: ["recipeName"],
  },
};

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-pro",
  generationConfig: {
    responseMimeType: "application/json",
    responseSchema: schema,
  },
});

const result = await model.generateContent(
  "List a few popular cookie recipes.",
);
console.log(result.response.text());

انتقال

model := client.GenerativeModel("gemini-1.5-pro-latest")
// Ask the model to respond with JSON.
model.ResponseMIMEType = "application/json"
// Specify the schema.
model.ResponseSchema = &genai.Schema{
	Type:  genai.TypeArray,
	Items: &genai.Schema{Type: genai.TypeString},
}
resp, err := model.GenerateContent(ctx, genai.Text("List a few popular cookie recipes using this JSON schema."))
if err != nil {
	log.Fatal(err)
}
for _, part := range resp.Candidates[0].Content.Parts {
	if txt, ok := part.(genai.Text); ok {
		var recipes []string
		if err := json.Unmarshal([]byte(txt), &recipes); err != nil {
			log.Fatal(err)
		}
		fmt.Println(recipes)
	}
}

محارة

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_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

Kotlin

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-pro",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey,
        generationConfig = generationConfig {
            responseMimeType = "application/json"
            responseSchema = Schema(
                name = "recipes",
                description = "List of recipes",
                type = FunctionType.ARRAY,
                items = Schema(
                    name = "recipe",
                    description = "A recipe",
                    type = FunctionType.OBJECT,
                    properties = mapOf(
                        "recipeName" to Schema(
                            name = "recipeName",
                            description = "Name of the recipe",
                            type = FunctionType.STRING,
                            nullable = false
                        ),
                    ),
                    required = listOf("recipeName")
                ),
            )
        })

val prompt = "List a few popular cookie recipes."
val response = generativeModel.generateContent(prompt)
print(response.text)

Swift

let jsonSchema = Schema(
  type: .array,
  description: "List of recipes",
  items: Schema(
    type: .object,
    properties: [
      "recipeName": Schema(type: .string, description: "Name of the recipe", nullable: false),
    ],
    requiredProperties: ["recipeName"]
  )
)

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

let prompt = "List a few popular cookie recipes."
let response = try await generativeModel.generateContent(prompt)
if let text = response.text {
  print(text)
}

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final schema = Schema.array(
    description: 'List of recipes',
    items: Schema.object(properties: {
      'recipeName':
          Schema.string(description: 'Name of the recipe.', nullable: false)
    }, requiredProperties: [
      'recipeName'
    ]));

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

final prompt = 'List a few popular cookie recipes.';
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Java

Schema<List<String>> schema =
    new Schema(
        /* name */ "recipes",
        /* description */ "List of recipes",
        /* format */ null,
        /* nullable */ false,
        /* list */ null,
        /* properties */ null,
        /* required */ null,
        /* items */ new Schema(
            /* name */ "recipe",
            /* description */ "A recipe",
            /* format */ null,
            /* nullable */ false,
            /* list */ null,
            /* properties */ Map.of(
                "recipeName",
                new Schema(
                    /* name */ "recipeName",
                    /* description */ "Name of the recipe",
                    /* format */ null,
                    /* nullable */ false,
                    /* list */ null,
                    /* properties */ null,
                    /* required */ null,
                    /* items */ null,
                    /* type */ FunctionType.STRING)),
            /* required */ null,
            /* items */ null,
            /* type */ FunctionType.OBJECT),
        /* type */ FunctionType.ARRAY);

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

GenerationConfig generationConfig = configBuilder.build();

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

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

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

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

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

تنفيذ الرمز البرمجي

Python

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

Kotlin


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

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

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

// Alternatively, you can use the `text` accessor which joins the parts into a markdown compatible
// text representation
println(response.text)

Java

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

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

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

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

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

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

استدعاء الدوالّ

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
async function setLightValues(brightness, colorTemperature) {
  // This mock API returns the requested lighting values
  return {
    brightness,
    colorTemperature,
  };
}

const controlLightFunctionDeclaration = {
  name: "controlLight",
  parameters: {
    type: "OBJECT",
    description: "Set the brightness and color temperature of a room light.",
    properties: {
      brightness: {
        type: "NUMBER",
        description:
          "Light level from 0 to 100. Zero is off and 100 is full brightness.",
      },
      colorTemperature: {
        type: "STRING",
        description:
          "Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.",
      },
    },
    required: ["brightness", "colorTemperature"],
  },
};

// Executable function code. Put it in a map keyed by the function name
// so that you can call it once you get the name string from the model.
const functions = {
  controlLight: ({ brightness, colorTemperature }) => {
    return setLightValues(brightness, colorTemperature);
  },
};

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  tools: { functionDeclarations: [controlLightFunctionDeclaration] },
});
const chat = model.startChat();
const prompt = "Dim the lights so the room feels cozy and warm.";

// Send the message to the model.
const result = await chat.sendMessage(prompt);

// For simplicity, this uses the first function call found.
const call = result.response.functionCalls()[0];

if (call) {
  // Call the executable function named in the function call
  // with the arguments specified in the function call and
  // let it call the hypothetical API.
  const apiResponse = await functions[call.name](call.args);

  // Send the API response back to the model so it can generate
  // a text response that can be displayed to the user.
  const result2 = await chat.sendMessage([
    {
      functionResponse: {
        name: "controlLight",
        response: apiResponse,
      },
    },
  ]);

  // Log the text response.
  console.log(result2.response.text());
}

محارة


cat > tools.json << EOF
{
  "function_declarations": [
    {
      "name": "enable_lights",
      "description": "Turn on the lighting system.",
      "parameters": { "type": "object" }
    },
    {
      "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.",
      "parameters": { "type": "object" }
    }
  ]
} 
EOF

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=$GOOGLE_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": ['$(source "$tools")'],

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

    "contents": {
      "role": "user",
      "parts": {
        "text": "What can you do?"
      }
    }
  }
') 2>/dev/null |sed -n '/"content"/,/"finishReason"/p'

Kotlin

fun multiply(a: Double, b: Double) = a * b

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

val usableFunctions = listOf(multiplyDefinition)

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

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

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

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

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

// Whenever the model responds with text, show it in the UI
response.text?.let { modelResponse ->
    println(modelResponse)
}

Swift

// Calls a hypothetical API to control a light bulb and returns the values that were set.
func controlLight(brightness: Double, colorTemperature: String) -> JSONObject {
  return ["brightness": .number(brightness), "colorTemperature": .string(colorTemperature)]
}

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

let chat = generativeModel.startChat()

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

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

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

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

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

if let text = response2.text {
  print(text)
}

Dart

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

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

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

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

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

List<FunctionCall> functionCalls;
while ((functionCalls = response.functionCalls.toList()).isNotEmpty) {
  var responses = <FunctionResponse>[
    for (final functionCall in functionCalls)
      dispatchFunctionCall(functionCall)
  ];
  content
    ..add(response.candidates.first.content)
    ..add(Content.functionResponses(responses));
  response = await model.generateContent(content);
}
print('Response: ${response.text}');

Java

FunctionDeclaration multiplyDefinition =
    defineFunction(
        /* name  */ "multiply",
        /* description */ "returns a * b.",
        /* parameters */ Arrays.asList(
            Schema.numDouble("a", "First parameter"),
            Schema.numDouble("b", "Second parameter")),
        /* required */ Arrays.asList("a", "b"));

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

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

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

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

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

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

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

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

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

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

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

          chat.sendMessage(userMessage);
        } catch (JSONException e) {
          throw new RuntimeException(e);
        }
      }
    },
    executor);

إعدادات الإنشاء

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  generationConfig: {
    candidateCount: 1,
    stopSequences: ["x"],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

const result = await model.generateContent(
  "Tell me a story about a magic backpack.",
);
console.log(result.response.text());

انتقال

model := client.GenerativeModel("gemini-1.5-pro-latest")
model.SetTemperature(0.9)
model.SetTopP(0.5)
model.SetTopK(20)
model.SetMaxOutputTokens(100)
model.SystemInstruction = genai.NewUserContent(genai.Text("You are Yoda from Star Wars."))
model.ResponseMIMEType = "application/json"
resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
if err != nil {
	log.Fatal(err)
}
printResponse(resp)

محارة

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
        "contents": [{
            "parts":[
                {"text": "Write a story about a magic backpack."}
            ]
        }],
        "safetySettings": [
            {
                "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
                "threshold": "BLOCK_ONLY_HIGH"
            }
        ],
        "generationConfig": {
            "stopSequences": [
                "Title"
            ],
            "temperature": 1.0,
            "maxOutputTokens": 800,
            "topP": 0.8,
            "topK": 10
        }
    }'  2> /dev/null | grep "text"

Kotlin

val config = generationConfig {
  temperature = 0.9f
  topK = 16
  topP = 0.1f
  maxOutputTokens = 200
  stopSequences = listOf("red")
}

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        generationConfig = config)

Swift

let config = GenerationConfig(
  temperature: 0.9,
  topP: 0.1,
  topK: 16,
  candidateCount: 1,
  maxOutputTokens: 200,
  stopSequences: ["red", "orange"]
)

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

Dart

final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Tell me a story about a magic backpack.';

final response = await model.generateContent(
  [Content.text(prompt)],
  generationConfig: GenerationConfig(
    candidateCount: 1,
    stopSequences: ['x'],
    maxOutputTokens: 20,
    temperature: 1.0,
  ),
);
print(response.text);

Java

GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.temperature = 0.9f;
configBuilder.topK = 16;
configBuilder.topP = 0.1f;
configBuilder.maxOutputTokens = 200;
configBuilder.stopSequences = Arrays.asList("red");

GenerationConfig generationConfig = configBuilder.build();

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

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

إعدادات السلامة

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  safetySettings: [
    {
      category: HarmCategory.HARM_CATEGORY_HARASSMENT,
      threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
    },
    {
      category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
      threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    },
  ],
});

const unsafePrompt =
  "I support Martians Soccer Club and I think " +
  "Jupiterians Football Club sucks! Write an ironic phrase telling " +
  "them how I feel about them.";

const result = await model.generateContent(unsafePrompt);

try {
  result.response.text();
} catch (e) {
  console.error(e);
  console.log(result.response.candidates[0].safetyRatings);
}

انتقال

model := client.GenerativeModel("gemini-1.5-flash")
model.SafetySettings = []*genai.SafetySetting{
	{
		Category:  genai.HarmCategoryDangerousContent,
		Threshold: genai.HarmBlockLowAndAbove,
	},
	{
		Category:  genai.HarmCategoryHarassment,
		Threshold: genai.HarmBlockMediumAndAbove,
	},
}
resp, err := model.GenerateContent(ctx, genai.Text("I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them."))
if err != nil {
	log.Fatal(err)
}
printResponse(resp)

محارة

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

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

Kotlin

val harassmentSafety = SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH)

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

val generativeModel =
    GenerativeModel(
        // The Gemini 1.5 models are versatile and work with most use cases
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        safetySettings = listOf(harassmentSafety, hateSpeechSafety))

Swift

let safetySettings = [
  SafetySetting(harmCategory: .dangerousContent, threshold: .blockLowAndAbove),
  SafetySetting(harmCategory: .harassment, threshold: .blockMediumAndAbove),
  SafetySetting(harmCategory: .hateSpeech, threshold: .blockOnlyHigh),
]

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

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'I support Martians Soccer Club and I think '
    'Jupiterians Football Club sucks! Write an ironic phrase telling '
    'them how I feel about them.';

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

Java

SafetySetting harassmentSafety =
    new SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH);

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

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

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

تعليمات النظام

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  systemInstruction: "You are a cat. Your name is Neko.",
});

const prompt = "Good morning! How are you?";

const result = await model.generateContent(prompt);
const response = result.response;
const text = response.text();
console.log(text);

انتقال

model := client.GenerativeModel("gemini-1.5-flash")
model.SystemInstruction = genai.NewUserContent(genai.Text("You are a cat. Your name is Neko."))
resp, err := model.GenerateContent(ctx, genai.Text("Good morning! How are you?"))
if err != nil {
	log.Fatal(err)
}
printResponse(resp)

محارة

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_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"}}}'

Kotlin

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        systemInstruction = content { text("You are a cat. Your name is Neko.") },
    )

Swift

let generativeModel =
  GenerativeModel(
    // Specify a model that supports system instructions, like a Gemini 1.5 model
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    systemInstruction: ModelContent(role: "system", parts: "You are a cat. Your name is Neko.")
  )

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
  systemInstruction: Content.system('You are a cat. Your name is Neko.'),
);
final prompt = 'Good morning! How are you?';

final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Java

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

نص الاستجابة

إذا كانت الاستجابة ناجحة، يحتوي نص الاستجابة على مثال GenerateContentResponse.

الطريقة: models.streamGenerateContent

تُنشئ استجابة مُذاعة من النموذج استنادًا إلى الإدخال GenerateContentRequest.

نقطة نهاية

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

يستخدِم عنوان URL بنية تحويل ترميز gRPC.

مَعلمات المسار

model string

مطلوب. اسم Model المراد استخدامه لإنشاء الإنجاز.

التنسيق: models/{model} يكون على الشكل models/{model}.

نص الطلب

يحتوي نص الطلب على بيانات بالبنية التالية:

الحقول
contents[] object (Content)

مطلوب. محتوى المحادثة الحالية مع النموذج

بالنسبة إلى طلبات البحث التي تتضمّن جولة واحدة، يكون هذا مثيلًا واحدًا. بالنسبة إلى طلبات البحث التي تتضمّن عدّة أدوار، مثل chat، هذا حقل متكرّر يحتوي على سجلّ المحادثة وآخر طلب.

tools[] object (Tool)

اختياريّ. قائمة Tools التي قد يستخدمها Model لإنشاء الردّ التالي

Tool هو عبارة عن قطعة رمز تتيح للنظام التفاعل مع الأنظمة الخارجية لتنفيذ إجراء أو مجموعة من الإجراءات خارج نطاق المعرفة والمسؤوليات الخاصة بالتطبيق.Model Tool المتوافقة هي Function وcodeExecution. راجِع دليلَي استدعاء الدوال وتنفيذ الرموز البرمجية للاطّلاع على مزيد من المعلومات.

toolConfig object (ToolConfig)

اختياريّ. إعدادات الأداة لأي Tool محدّد في الطلب يُرجى الرجوع إلى دليل استدعاء الدوالّ للاطّلاع على مثال على الاستخدام.

safetySettings[] object (SafetySetting)

اختياريّ. قائمة بمثيلات SafetySetting الفريدة لحظر المحتوى غير الآمن

سيتم فرض هذا التغيير على GenerateContentRequest.contents وGenerateContentResponse.candidates. يجب ألا يكون هناك أكثر من إعداد واحد لكل نوع SafetyCategory. ستحظر واجهة برمجة التطبيقات أي محتوى أو ردّ لا يستوفي الحدّ الأدنى الذي تحدّده هذه الإعدادات. تلغي هذه القائمة الإعدادات التلقائية لكل SafetyCategory محدّد في safetySettings. إذا لم يكن هناك SafetySetting لـ SafetyCategory معيّن مقدَّم في القائمة، ستستخدم واجهة برمجة التطبيقات إعدادات السلامة التلقائية لهذه الفئة. يمكن استخدام فئات المحتوى الضار HARM_CATEGORY_HATE_SPEECH وHARM_CATEGORY_SEXUALLY_EXPLICIT وHARM_CATEGORY_DANGEROUS_CONTENT وHARM_CATEGORY_HARASSMENT وHARM_CATEGORY_CIVIC_INTEGRITY. يُرجى الرجوع إلى الدليل للحصول على معلومات تفصيلية عن إعدادات الأمان المتاحة. يمكنك أيضًا الرجوع إلى إرشادات السلامة للتعرّف على كيفية دمج اعتبارات السلامة في تطبيقات الذكاء الاصطناعي.

systemInstruction object (Content)

اختياريّ. ضبط المطوّر تعليمات النظام يتوفّر حاليًا النص فقط.

generationConfig object (GenerationConfig)

اختياريّ. خيارات الضبط لإنشاء النماذج والنواتج

cachedContent string

اختياريّ. اسم المحتوى المخزّن مؤقتًا لاستخدامه كسياق لعرض التوقّعات التنسيق: cachedContents/{cachedContent}

مثال على الطلب

نص

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Write a story about a magic backpack.";

const result = await model.generateContentStream(prompt);

// Print text as it comes in.
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}

انتقال

model := client.GenerativeModel("gemini-1.5-flash")
iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
	resp, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	printResponse(resp)
}

محارة

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

Kotlin

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

val prompt = "Write a story about a magic backpack."
// Use streaming with text-only input
generativeModel.generateContentStream(prompt).collect { chunk -> print(chunk.text) }

Swift

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

let prompt = "Write a story about a magic backpack."
// Use streaming with text-only input
for try await response in generativeModel.generateContentStream(prompt) {
  if let text = response.text {
    print(text)
  }
}

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Write a story about a magic backpack.';

final responses = model.generateContentStream([Content.text(prompt)]);
await for (final response in responses) {
  print(response.text);
}

Java

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

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

صورة

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType,
    },
  };
}

const prompt = "Describe how this product might be manufactured.";
// Note: The only accepted mime types are some image types, image/*.
const imagePart = fileToGenerativePart(
  `${mediaPath}/jetpack.jpg`,
  "image/jpeg",
);

const result = await model.generateContentStream([prompt, imagePart]);

// Print text as it comes in.
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}

انتقال

model := client.GenerativeModel("gemini-1.5-flash")

imgData, err := os.ReadFile(filepath.Join(testDataDir, "organ.jpg"))
if err != nil {
	log.Fatal(err)
}
iter := model.GenerateContentStream(ctx,
	genai.Text("Tell me about this instrument"),
	genai.ImageData("jpeg", imgData))
for {
	resp, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	printResponse(resp)
}

محارة

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

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

Kotlin

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

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

generativeModel.generateContentStream(inputContent).collect { chunk -> print(chunk.text) }

Swift

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

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

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

for try await response in generativeModel.generateContentStream(image, prompt) {
  if let text = response.text {
    print(text)
  }
}

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);

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

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

final responses = model.generateContentStream([
  Content.multi([TextPart(prompt), image])
]);
await for (final response in responses) {
  print(response.text);
}

Java

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

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

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

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

الصوت

Python

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

محارة

# 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=${GOOGLE_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-1.5-flash:streamGenerateContent?alt=sse&key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Please describe this file."},
          {"file_data":{"mime_type": "audio/mpeg", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

فيديو

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
// import { GoogleAIFileManager, FileState } from "@google/generative-ai/server";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/Big_Buck_Bunny.mp4`,
  { mimeType: "video/mp4" },
);

let file = await fileManager.getFile(uploadResult.file.name);
while (file.state === FileState.PROCESSING) {
  process.stdout.write(".");
  // Sleep for 10 seconds
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  // Fetch the file from the API again
  file = await fileManager.getFile(uploadResult.file.name);
}

if (file.state === FileState.FAILED) {
  throw new Error("Video processing failed.");
}

const prompt = "Describe this video clip";
const videoPart = {
  fileData: {
    fileUri: uploadResult.file.uri,
    mimeType: uploadResult.file.mimeType,
  },
};

const result = await model.generateContentStream([prompt, videoPart]);
// Print text as it comes in.
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}

انتقال

model := client.GenerativeModel("gemini-1.5-flash")

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

iter := model.GenerateContentStream(ctx,
	genai.Text("Describe this video clip"),
	genai.FileData{URI: file.URI})
for {
	resp, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	printResponse(resp)
}

محارة

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

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_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-1.5-flash:streamGenerateContent?alt=sse&key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Please describe this file."},
          {"file_data":{"mime_type": "video/mp4", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

PDF

Python

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

محارة

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=${GOOGLE_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-1.5-flash:streamGenerateContent?alt=sse&key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Can you add a few more lines to this poem?"},
          {"file_data":{"mime_type": "application/pdf", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

دردشة

Python

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

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: [{ text: "Hello" }],
    },
    {
      role: "model",
      parts: [{ text: "Great to meet you. What would you like to know?" }],
    },
  ],
});
let result = await chat.sendMessageStream("I have 2 dogs in my house.");
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}
result = await chat.sendMessageStream("How many paws are in my house?");
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}

انتقال

model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()

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

iter := cs.SendMessageStream(ctx, genai.Text("How many paws are in my house?"))
for {
	resp, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	printResponse(resp)
}

محارة

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:streamGenerateContent?alt=sse&key=$GOOGLE_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"

Kotlin

// Use streaming with multi-turn conversations (like chat)
val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

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

chat.sendMessageStream("How many paws are in my house?").collect { chunk -> print(chunk.text) }

Swift

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

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

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

// To stream generated text output, call sendMessageStream and pass in the message
let contentStream = chat.sendMessageStream("How many paws are in my house?")
for try await chunk in contentStream {
  if let text = chunk.text {
    print(text)
  }
}

Dart

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final chat = model.startChat(history: [
  Content.text('hello'),
  Content.model([TextPart('Great to meet you. What would you like to know?')])
]);
var responses =
    chat.sendMessageStream(Content.text('I have 2 dogs in my house.'));
await for (final response in responses) {
  print(response.text);
  print('_' * 80);
}
responses =
    chat.sendMessageStream(Content.text('How many paws are in my house?'));
await for (final response in responses) {
  print(response.text);
  print('_' * 80);
}

Java

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

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

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

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

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

      @Override
      public void onError(Throwable t) {}

    });

نص الاستجابة

إذا كانت الاستجابة ناجحة، يحتوي نص الاستجابة على بثّ لعناصر GenerateContentResponse.

GenerateContentResponse

استجابة من النموذج تتيح عدّة إجابات مرشحة

يتم تسجيل تقييمات السلامة وفلترة المحتوى لكل من الطلب في GenerateContentResponse.prompt_feedback ولكل نموذج في finishReason وsafetyRatings. واجهة برمجة التطبيقات: - تعرض جميع المرشحين المطلوبين أو لا تعرض أيّ منهم - لا تعرض أيّ مرشّحين على الإطلاق إلا إذا كان هناك خطأ في الطلب (راجِع promptFeedback) - تُبلغ عن الملاحظات بشأن كلّ مرشّح في finishReason وsafetyRatings.

الحقول
candidates[] object (Candidate)

الردود المُحتمَلة من النموذج

promptFeedback object (PromptFeedback)

تعرِض هذه السمة ملاحظات الطلب المتعلّقة بفلاتر المحتوى.

usageMetadata object (UsageMetadata)

النتائج فقط. البيانات الوصفية حول استخدام الرموز المميّزة لطلبات الإنشاء

modelVersion string

النتائج فقط. إصدار النموذج المستخدَم لإنشاء الردّ

تمثيل JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string
}

PromptFeedback

مجموعة من البيانات الوصفية للملاحظات والآراء التي حدّدها الطلب في GenerateContentRequest.content

الحقول
blockReason enum (BlockReason)

اختياريّ. في حال ضبط هذا الخيار، يتم حظر الطلب ولا يتم عرض أيّ مرشّحين. إعادة صياغة الطلب

safetyRatings[] object (SafetyRating)

تقييمات لأمان الطلب يجب أن يكون هناك تقييم واحد كحد أقصى لكل فئة.

تمثيل JSON
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

BlockReason

يحدّد سبب حظر الطلب.

عمليات التعداد
BLOCK_REASON_UNSPECIFIED القيمة التلقائية هذه القيمة غير مستخدَمة.
SAFETY تم حظر الطلب لأسباب تتعلق بالسلامة. راجِع safetyRatings لمعرفة فئة السلامة التي حظرت المحتوى.
OTHER تم حظر الطلب لأسباب غير معروفة.
BLOCKLIST تم حظر الطلب بسبب العبارات المضمّنة في قائمة حظر المصطلحات.
PROHIBITED_CONTENT تم حظر الطلب بسبب محتوى محظور.
IMAGE_SAFETY تم حظر الصور المرشحة بسبب محتوى غير آمن لإنشاء الصور.

UsageMetadata

البيانات الوصفية حول استخدام الرمز المميّز لطلب الإنشاء

الحقول
promptTokenCount integer

عدد الرموز المميّزة في الطلب عند ضبط القيمة cachedContent، يظلّ هذا هو إجمالي حجم الطلب الفعّال، ما يعني أنّه يشمل عدد الرموز المميّزة في المحتوى المخزّن مؤقتًا.

cachedContentTokenCount integer

عدد الرموز المميّزة في الجزء المخزّن مؤقتًا من الطلب (المحتوى المخزّن مؤقتًا)

candidatesTokenCount integer

إجمالي عدد الرموز المميّزة في جميع الردود المُحتمَلة التي تم إنشاؤها

totalTokenCount integer

إجمالي عدد الرموز المميّزة لطلب الإنشاء (الطلب + المرشحون للردّ)

promptTokensDetails[] object (ModalityTokenCount)

النتائج فقط. قائمة بالوضعيات التي تمت معالجتها في إدخال الطلب

cacheTokensDetails[] object (ModalityTokenCount)

النتائج فقط. قائمة بأشكال المحتوى المخزّن مؤقتًا في إدخال الطلب

candidatesTokensDetails[] object (ModalityTokenCount)

النتائج فقط. قائمة بالوسائط التي تم عرضها في الاستجابة

تمثيل JSON
{
  "promptTokenCount": integer,
  "cachedContentTokenCount": integer,
  "candidatesTokenCount": integer,
  "totalTokenCount": integer,
  "promptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "cacheTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "candidatesTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ]
}

مرشح

ردّ محتمل تم إنشاؤه من النموذج

الحقول
content object (Content)

النتائج فقط. المحتوى الذي تم إنشاؤه من النموذج

finishReason enum (FinishReason)

اختياريّ. النتائج فقط. سبب توقّف النموذج عن إنشاء الرموز المميّزة

إذا كان الحقل فارغًا، يعني ذلك أنّ النموذج لم يتوقف عن إنشاء الرموز المميّزة.

safetyRatings[] object (SafetyRating)

قائمة بتقييمات أمان المرشح للردّ

يجب أن يكون هناك تقييم واحد كحد أقصى لكل فئة.

citationMetadata object (CitationMetadata)

النتائج فقط. معلومات الاقتباس للمرشح الذي تم إنشاؤه بالاستناد إلى نموذج

قد تتم تعبئة هذا الحقل بمعلومات حول القراءة لأي نص مضمّن في content. هذه هي مقاطع "مُقروءة" من مواد محمية بموجب حقوق الطبع والنشر في بيانات التدريب الأساسية لنموذج اللغة المحوسبة الكبير.

tokenCount integer

النتائج فقط. عدد الرموز المميّزة لهذا المرشّح.

groundingAttributions[] object (GroundingAttribution)

النتائج فقط. معلومات الإسناد للمصادر التي ساهمت في تقديم إجابة مستندة إلى الحقائق

يتمّ ملء هذا الحقل لطلبات GenerateAnswer.

groundingMetadata object (GroundingMetadata)

النتائج فقط. البيانات الوصفية الأساسية للمرشح

يتمّ ملء هذا الحقل لطلبات GenerateContent.

avgLogprobs number

النتائج فقط. متوسّط نتيجة الاحتمالية اللوغاريتمية للمرشّح

logprobsResult object (LogprobsResult)

النتائج فقط. نتائج الاحتمالية اللوغاريتمية لعلامات الاستجابة والعلامات الرئيسية

index integer

النتائج فقط. فهرس المرشح في قائمة مرشّحي الردود

تمثيل JSON
{
  "content": {
    object (Content)
  },
  "finishReason": enum (FinishReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ],
  "citationMetadata": {
    object (CitationMetadata)
  },
  "tokenCount": integer,
  "groundingAttributions": [
    {
      object (GroundingAttribution)
    }
  ],
  "groundingMetadata": {
    object (GroundingMetadata)
  },
  "avgLogprobs": number,
  "logprobsResult": {
    object (LogprobsResult)
  },
  "index": integer
}

FinishReason

يحدِّد سبب توقُّف النموذج عن إنشاء الرموز المميّزة.

عمليات التعداد
FINISH_REASON_UNSPECIFIED القيمة التلقائية هذه القيمة غير مستخدَمة.
STOP نقطة التوقف الطبيعية للنموذج أو تسلسل التوقف المقدَّم
MAX_TOKENS تم الوصول إلى الحد الأقصى لعدد الرموز المميّزة كما هو محدّد في الطلب.
SAFETY تم الإبلاغ عن المحتوى المُقترَح للردّ لأسباب تتعلّق بالأمان.
RECITATION تم الإبلاغ عن محتوى المرشح للردّ لأسباب تتعلّق بالقراءة.
LANGUAGE تم الإبلاغ عن المحتوى المُقترَح للردّ بسبب استخدامه لغة غير متوافقة.
OTHER سبب غير معروف
BLOCKLIST توقّف إنشاء الرمز المميّز لأنّ المحتوى يتضمّن عبارات محظورة.
PROHIBITED_CONTENT تم إيقاف إنشاء الرمز المميّز لأنّه يُحتمل أن يتضمّن محتوى محظورًا.
SPII توقّف إنشاء الرمز المميّز لأنّ المحتوى قد يحتوي على معلومات حسّاسة تكشف عن الهوية (SPII).
MALFORMED_FUNCTION_CALL طلب الدالة الذي أنشأه النموذج غير صالح.
IMAGE_SAFETY توقّفت عملية إنشاء الرمز المميّز لأنّ الصور التي تم إنشاؤها تتضمّن انتهاكات للسلامة.

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 تم استرجاعه من خلال "أداة استرجاع المحتوى الدلالي"

تمثيل JSON
{

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

GroundingPassageId

معرّف لجزء ضمن GroundingPassage

الحقول
passageId string

النتائج فقط. رقم تعريف الفقرة التي تتطابق مع GroundingPassage.id في GenerateAnswerRequest

partIndex integer

النتائج فقط. فهرس الجزء ضمن GroundingPassage.content في GenerateAnswerRequest

تمثيل JSON
{
  "passageId": string,
  "partIndex": integer
}

SemanticRetrieverChunk

معرّف Chunk الذي تم استرجاعه من خلال "أداة استرجاع المحتوى الدلالي" المحدّدة في GenerateAnswerRequest باستخدام SemanticRetrieverConfig.

الحقول
source string

النتائج فقط. اسم المصدر الذي يتطابق مع SemanticRetrieverConfig.source في الطلب مثال: corpora/123 أو corpora/123/documents/abc

chunk string

النتائج فقط. اسم Chunk الذي يحتوي على النص المنسوب مثال: corpora/123/documents/abc/chunks/xyz

تمثيل JSON
{
  "source": string,
  "chunk": string
}

GroundingMetadata

يتم عرض البيانات الوصفية للعميل عند تفعيل وضع التأريض.

الحقول
groundingChunks[] object (GroundingChunk)

قائمة بالمراجع الداعمة التي تم استرجاعها من مصدر مرجعي محدّد

groundingSupports[] object (GroundingSupport)

قائمة بأجهزة التأريض

webSearchQueries[] string

طلبات بحث الويب لبحث الويب اللاحق

searchEntryPoint object (SearchEntryPoint)

اختياريّ. إدخال بحث Google لإجراء عمليات بحث لاحقة على الويب

retrievalMetadata object (RetrievalMetadata)

البيانات الوصفية ذات الصلة بالاسترداد في عملية التأصيل

تمثيل JSON
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  }
}

SearchEntryPoint

نقطة دخول "بحث Google"

الحقول
renderedContent string

اختياريّ. مقتطف محتوى ويب يمكن تضمينه في صفحة ويب أو عرض ويب للتطبيق.

sdkBlob string (bytes format)

اختياريّ. ملف JSON بترميز Base64 يمثّل صفيفًا من مجموعة <عبارة البحث، عنوان URL للبحث>

سلسلة مُشفَّرة باستخدام base64

تمثيل JSON
{
  "renderedContent": string,
  "sdkBlob": string
}

GroundingChunk

مجموعة بيانات أساسية

الحقول
chunk_type Union type
نوع المقطع يمكن أن يكون chunk_type واحدًا مما يلي فقط:
web object (Web)

مقتطف أساسي من الويب

تمثيل JSON
{

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

الويب

مقتطف من الويب

الحقول
uri string

مرجع معرّف الموارد المنتظم للقطعة

title string

عنوان المقطع

تمثيل JSON
{
  "uri": string,
  "title": string
}

GroundingSupport

دعم التأريض

الحقول
groundingChunkIndices[] integer

قائمة بالفهرس (في "grounding_chunk") التي تحدّد الإحالات المرتبطة بالمطالبة على سبيل المثال، يعني [1,3,4] أنّ grounding_chunk[1] وgrounding_chunk[3] وgrounding_chunk[4] هي المحتوى الذي تم استرجاعه والمرتبط بالمطالبة.

confidenceScores[] number

درجة الثقة في مراجع الدعم تتراوح بين 0 و1. و1 هو الخيار الأكثر ثقة. يجب أن تكون هذه القائمة بالحجم نفسه مثل groundingChunkIndices.

segment object (Segment)

جزء من المحتوى الذي ينتمي إليه هذا الدعم

تمثيل JSON
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

تقسيم

جزء من المحتوى

الحقول
partIndex integer

النتائج فقط. فهرس عنصر Part ضمن عنصر Content الرئيسي

startIndex integer

النتائج فقط. فهرس البدء في الجزء المحدّد، ويقاس بوحدات البايت. القيمة المُعدَّلة من بداية الجزء، شاملة، بدءًا من الصفر

endIndex integer

النتائج فقط. فهرس النهاية في الجزء المحدّد، ويقاس بالبايت. القيمة المضافة إلى بداية الجزء، حصرية، تبدأ من القيمة صفر.

text string

النتائج فقط. النص المقابل للقطعة من الردّ

تمثيل JSON
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

RetrievalMetadata

البيانات الوصفية ذات الصلة بالاسترداد في عملية التأصيل

الحقول
googleSearchDynamicRetrievalScore number

اختياريّ. نتيجة تشير إلى مدى احتمالية أن تساعد المعلومات الواردة من "بحث Google" في الإجابة عن الطلب. تقع النتيجة في النطاق [0, 1]، حيث يشير الصفر إلى أقل احتمال و1 إلى أعلى احتمال. لا تتم تعبئة هذه النتيجة إلا عند تفعيل ميزة "الربط بنتائج البحث من Google" وميزة "الاسترجاع الديناميكي". وسيتمّ مقارنتها بالحدّ الأدنى لتحديد ما إذا كان سيتمّ تفعيل "بحث Google".

تمثيل JSON
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

نتيجة Logprobs

الحقول
topCandidates[] object (TopCandidates)

الطول = إجمالي عدد خطوات فك التشفير

chosenCandidates[] object (Candidate)

الطول = إجمالي عدد خطوات فك التشفير قد تكون المرشحات التي تم اختيارها في topCandidates أو لا تكون.

تمثيل JSON
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ]
}

TopCandidates

المرشّحات التي تتضمن أعلى احتمالات السجلّ في كل خطوة من خطوات فك التشفير

الحقول
candidates[] object (Candidate)

تم ترتيبها تنازليًا حسب اللوغاريتم اللوغاريتمي لاحتمالات حدوثها.

تمثيل JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

مرشح

مرشح لرمز logprobs وعلامته

الحقول
token string

قيمة سلسلة الرمز المميّز للمرشّح

tokenId integer

قيمة معرّف الرمز المميّز للمرشّح

logProbability number

اللوغاريتم اللوغاريتمي لاحتمالات المرشّح

تمثيل JSON
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

CitationMetadata

مجموعة من الإحالات إلى مصادر جزء من المحتوى

الحقول
citationSources[] object (CitationSource)

إحالات إلى مصادر ردّ معيّن

تمثيل JSON
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}

CitationSource

اقتباس لمصدر جزء من ردّ معيّن

الحقول
startIndex integer

اختياريّ. بداية جزء من الردّ المنسوب إلى هذا المصدر

يشير الفهرس إلى بداية المقطع، ويتم قياسه بوحدات البايت.

endIndex integer

اختياريّ. نهاية الجزء المنسوب، حصريًا

uri string

اختياريّ. معرّف الموارد المنتظم (URI) الذي يُنسب إليه مصدر جزء من النص

license string

اختياريّ. ترخيص مشروع GitHub الذي يُنسب إليه المصدر الخاص بالقسم

يجب إدخال معلومات الترخيص لإضافة مراجع الرموز البرمجية.

تمثيل JSON
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}

GenerationConfig

خيارات الضبط لإنشاء النماذج والنواتج لا يمكن ضبط بعض المَعلمات لكلّ نموذج.

الحقول
stopSequences[] string

اختياريّ. مجموعة تسلسلات الأحرف (ما يصل إلى 5) التي ستؤدي إلى إيقاف إنشاء الإخراج في حال تحديد هذا الحقل، ستتوقف واجهة برمجة التطبيقات عند أول ظهور لـ stop_sequence. لن يتم تضمين تسلسل الإيقاف كجزء من الاستجابة.

responseMimeType string

اختياريّ. نوع MIME للنص المُقترَح الذي تم إنشاؤه أنواع MIME المتوافقة هي: text/plain: (تلقائي) إخراج نصي. ‫application/json: استجابة JSON في العناصر المُحتمَلة للاستجابة ‫text/x.enum: ENUM كسلسلة ردّ في المرشحين للردّ يُرجى الرجوع إلى المستندات للحصول على قائمة بجميع أنواع MIME النصية المتوافقة.

responseSchema object (Schema)

اختياريّ. مخطّط الإخراج للنص المُقترَح الذي تم إنشاؤه يجب أن تكون المخططات مجموعة فرعية من مخطّط OpenAPI ويمكن أن تكون عناصر أو عناصر أساسية أو صفائف.

في حال ضبط responseMimeType، يجب أيضًا ضبط responseMimeType متوافق. أنواع MIME المتوافقة: application/json: مخطّط استجابة JSON راجِع دليل إنشاء النصوص بتنسيق JSON للاطّلاع على مزيد من التفاصيل.

responseModalities[] enum (Modality)

اختياريّ. طرق الردّ المطلوبة يمثّل مجموعة الأنماط التي يمكن أن يعرضها النموذج، والتي من المفترض أن تظهر في الردّ. هذه مطابقة تامّة لطريقة الردّ.

قد يتضمّن النموذج مجموعات متعدّدة من الوسائط المتوافقة. إذا لم تتطابق الوسائل المطلوبة مع أي من التركيبات المتوافقة، سيتم عرض خطأ.

وتكون القائمة الفارغة مساوية لطلب نص فقط.

candidateCount integer

اختياريّ. عدد الردود التي تم إنشاؤها المطلوب عرضها.

في الوقت الحالي، لا يمكن ضبط هذه القيمة إلا على 1. في حال عدم ضبط هذا الخيار، سيتم ضبطه تلقائيًا على 1.

maxOutputTokens integer

اختياريّ. الحد الأقصى لعدد الرموز المميّزة المطلوب تضمينها في أحد الردود المُحتمَلة

ملاحظة: تختلف القيمة التلقائية حسب الطراز، اطّلِع على سمة Model.output_token_limit للعنصر Model الذي تم إرجاعه من الدالة getModel.

temperature number

اختياريّ. تتحكّم هذه السمة في العشوائية في الإخراج.

ملاحظة: تختلف القيمة التلقائية حسب الطراز، اطّلِع على سمة Model.temperature للعنصر Model الذي تم إرجاعه من الدالة getModel.

يمكن أن تتراوح القيم بين [0.0, 2.0].

topP number

اختياريّ. الحد الأقصى الاحتمالية التراكمية للرموز المميّزة التي يجب أخذها في الاعتبار عند أخذ العينات

يستخدم النموذج أسلوب أخذ العينات من النوعَين Top-k وTop-p (النواة).

يتم ترتيب الرموز بناءً على الاحتمالات المحدّدة لها حتى لا يتم أخذ سوى الرموز الأكثر احتمالًا في الاعتبار. يحدّ أسلوب أخذ عيّنات من أهمّ k رمزًا مباشرةً من الحدّ الأقصى لعدد الرموز التي يجب أخذها في الاعتبار، في حين يحدّ أسلوب أخذ عيّنات من نواة النصّ من عدد الرموز استنادًا إلى الاحتمالية التراكمية.

ملاحظة: تختلف القيمة التلقائية حسب Model ويتم تحديدها من خلال السمة Model.top_p التي يتم عرضها من الدالة getModel. تشير السمة topK الفارغة إلى أنّ النموذج لا يطبّق تحليل عيّنات "أهم k" ولا يسمح بضبط topK على الطلبات.

topK integer

اختياريّ. الحد الأقصى لعدد الرموز المميّزة التي يجب أخذها في الاعتبار عند أخذ عيّنات

تستخدِم نماذج Gemini أسلوب أخذ عيّنات Top-p (النواة) أو مزيجًا من أسلوب أخذ عيّنات Top-k وأسلوب أخذ عيّنات النواة. تأخذ تقنية أخذ عيّنات من أهمّ k بعين الاعتبار مجموعة من topK الرموز الأكثر احتمالًا. لا تسمح النماذج التي تعمل باستخدام تحليل عيّنات النوى بإعداد topK.

ملاحظة: تختلف القيمة التلقائية حسب Model ويتم تحديدها من خلال السمة Model.top_p التي يتم عرضها من دالة getModel. تشير السمة topK الفارغة إلى أنّ النموذج لا يطبّق تحليل عيّنات "أهم k" ولا يسمح بضبط topK على الطلبات.

seed integer

اختياريّ. البذرة المستخدَمة في فك التشفير في حال عدم ضبط هذه القيمة، يستخدم الطلب بذرة يتم إنشاؤها عشوائيًا.

presencePenalty number

اختياريّ. يتم تطبيق عقوبة الحضور على logprobs للرمز المميّز التالي إذا سبق أن ظهر الرمز المميّز في الاستجابة.

هذه العقوبة ثنائية التشغيل/الإيقاف ولا تعتمد على عدد المرات التي تم فيها استخدام الرمز المميّز (بعد المرة الأولى). استخدِم frequencyPenalty لفرض عقوبة تزداد مع كل استخدام.

ستؤدي العقوبة الإيجابية إلى عدم استخدام الرموز التي سبق استخدامها في الردّ، ما يؤدي إلى زيادة المفردات.

ستشجّع العقوبة السلبية استخدام الرموز التي سبق استخدامها في الردّ، ما يؤدي إلى تقليل المفردات.

frequencyPenalty number

اختياريّ. عقوبة تكرار الظهور المطبَّقة على logprobs للرمز التالي، مضروبةً في عدد مرّات ظهور كلّ رمز في الردّ إلى الآن

ستؤدي العقوبة الإيجابية إلى عدم استخدام الرموز المميزة التي سبق استخدامها، وذلك بما يتناسب مع عدد المرات التي تم فيها استخدام الرمز المميّز: وكلما زاد استخدام الرمز المميّز، زادت صعوبة استخدام النموذج لهذا الرمز المميّز مرة أخرى، ما يؤدي إلى زيادة مفردات الردود.

تحذير: ستشجّع العقوبة السلبية النموذج على إعادة استخدام الرموز المميّزة بما يتناسب مع عدد المرات التي تم فيها استخدام الرمز المميّز. ستؤدي القيم السلبية الصغيرة إلى تقليل مفردات الردّ. ستؤدي القيم السالبة الأكبر إلى بدء تكرار النموذج لرمز موحّد إلى أن يصل إلى الحدّ الأقصى maxOutputTokens.

responseLogprobs boolean

اختياريّ. إذا كانت القيمة هي true، يتم تصدير نتائج logprobs في الاستجابة.

logprobs integer

اختياريّ. لا يكون صالحًا إلا إذا كان responseLogprobs=True. يحدِّد هذا الإعداد عدد أهم logprobs التي سيتم عرضها في كل خطوة ترميز في Candidate.logprobs_result.

enableEnhancedCivicAnswers boolean

اختياريّ. تفعيل الإجابات المحسّنة عن الأسئلة المتعلقة بالشؤون المدنية قد لا تتوفّر هذه الميزة لبعض الطُرز.

speechConfig object (SpeechConfig)

اختياريّ. إعدادات إنشاء الكلام

تمثيل JSON
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "responseModalities": [
    enum (Modality)
  ],
  "candidateCount": integer,
  "maxOutputTokens": integer,
  "temperature": number,
  "topP": number,
  "topK": integer,
  "seed": integer,
  "presencePenalty": number,
  "frequencyPenalty": number,
  "responseLogprobs": boolean,
  "logprobs": integer,
  "enableEnhancedCivicAnswers": boolean,
  "speechConfig": {
    object (SpeechConfig)
  }
}

منهجية

طرق الردّ المتاحة

عمليات التعداد
MODALITY_UNSPECIFIED القيمة التلقائية
TEXT يشير إلى أنّ النموذج يجب أن يعرض نصًا.
IMAGE يشير إلى أنّ النموذج يجب أن يعرض صورًا.
AUDIO يشير إلى أنّ النموذج يجب أن يعرض الصوت.

SpeechConfig

إعدادات إنشاء الكلام

الحقول
voiceConfig object (VoiceConfig)

الإعدادات التي سيستخدمها مكبّر الصوت

تمثيل JSON
{
  "voiceConfig": {
    object (VoiceConfig)
  }
}

VoiceConfig

إعدادات الصوت المطلوب استخدامه

الحقول
voice_config Union type
الإعدادات التي سيستخدمها مكبّر الصوت يمكن أن يكون voice_config واحدًا مما يلي فقط:
prebuiltVoiceConfig object (PrebuiltVoiceConfig)

إعدادات الصوت المُعدّ مسبقًا لاستخدامه

تمثيل JSON
{

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

PrebuiltVoiceConfig

الإعدادات التي يجب استخدامها في مكبّر الصوت المُعدّ مسبقًا

الحقول
voiceName string

اسم الصوت المُعدّ مسبقًا المطلوب استخدامه.

تمثيل JSON
{
  "voiceName": string
}

HarmCategory

فئة التقييم

وتشمل هذه الفئات أنواعًا مختلفة من الأضرار التي قد يريد المطوّرون تعديلها.

عمليات التعداد
HARM_CATEGORY_UNSPECIFIED الفئة غير محدّدة.
HARM_CATEGORY_DEROGATORY PaLM: التعليقات السلبية أو الضارة التي تستهدف الهوية و/أو السمة المحمية
HARM_CATEGORY_TOXICITY PaLM: المحتوى غير المهذَّب أو غير المحترم أو الذي يتضمن لغة نابية
HARM_CATEGORY_VIOLENCE PaLM: يصف سيناريوهات تصوّر عنفًا ضد فرد أو مجموعة، أو أوصافًا عامة للمحتوى الدموي.
HARM_CATEGORY_SEXUAL PaLM: يتضمّن إشارات إلى أفعال جنسية أو محتوًى بذيئًا آخر.
HARM_CATEGORY_MEDICAL PaLM: يروّج للنصائح الطبية غير المدقّقة.
HARM_CATEGORY_DANGEROUS PaLM: المحتوى الخطير الذي يروّج لأفعال ضارة أو يسهّل تنفيذها أو يشجّع عليها
HARM_CATEGORY_HARASSMENT Gemini: المحتوى الذي يهدف إلى المضايقة
HARM_CATEGORY_HATE_SPEECH Gemini: الكلام الذي يحض على الكراهية والمحتوى الذي يحض على الكراهية
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini: محتوى جنسي فاضح
HARM_CATEGORY_DANGEROUS_CONTENT Gemini: المحتوى الخطير
HARM_CATEGORY_CIVIC_INTEGRITY Gemini: المحتوى الذي يمكن استخدامه للإضرار بالنزاهة المدنية

ModalityTokenCount

تمثّل معلومات احتساب الرموز المميّزة لوضع واحد.

الحقول
modality enum (Modality)

طريقة القياس المرتبطة بعدد الرموز المميّزة هذا.

tokenCount integer

عدد الرموز المميّزة

تمثيل JSON
{
  "modality": enum (Modality),
  "tokenCount": integer
}

منهجية

طريقة عرض جزء المحتوى

عمليات التعداد
MODALITY_UNSPECIFIED طريقة غير محدّدة
TEXT نص عادي
IMAGE صورة:
VIDEO الفيديو
AUDIO ملف صوتي:
DOCUMENT مستند، مثل ملف PDF

SafetyRating

تقييم السلامة لجزء من المحتوى

يتضمّن تقييم السلامة فئة الضرر ومستوى احتمالية الضرر في تلك الفئة لقطعة المحتوى. يتم تصنيف المحتوى حسب الأمان في عدد من فئات الضرر، ويتم تضمين احتمالية تصنيف المحتوى على أنّه ضار هنا.

الحقول
category enum (HarmCategory)

مطلوب. فئة هذا التقييم

probability enum (HarmProbability)

مطلوب. احتمالية الضرر من هذا المحتوى

blocked boolean

هل تم حظر هذا المحتوى بسبب هذا التقييم؟

تمثيل JSON
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}

HarmProbability

احتمال أن يكون محتوى معيّن ضارًا

يقدّم نظام التصنيف احتمالية أن يكون المحتوى غير آمن. ولا يشير ذلك إلى شدة الضرر الذي قد يتسبب فيه المحتوى.

عمليات التعداد
HARM_PROBABILITY_UNSPECIFIED الاحتمالية غير محدّدة.
NEGLIGIBLE هناك احتمال ضئيل بأن يكون المحتوى غير آمن.
LOW احتمالية منخفضة بأن يكون المحتوى غير آمن
MEDIUM هناك احتمالية متوسطة بأن يكون المحتوى غير آمن.
HIGH هناك احتمال كبير بأنّ المحتوى غير آمن.

SafetySetting

إعدادات الأمان التي تؤثّر في سلوك الحظر للحفاظ على الأمان

يؤدي تطبيق إعدادات الأمان لفئة معيّنة إلى تغيير الاحتمالية المسموح بها لحظر المحتوى.

الحقول
category enum (HarmCategory)

مطلوب. فئة هذا الإعداد.

threshold enum (HarmBlockThreshold)

مطلوب. تتحكّم هذه السمة في حدّ الاحتمال الذي يتم عنده حظر المحتوى الضار.

تمثيل JSON
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

HarmBlockThreshold

الحظر عند بلوغ احتمالية ضرر محدّدة أو تجاوزها

عمليات التعداد
HARM_BLOCK_THRESHOLD_UNSPECIFIED لم يتم تحديد الحدّ الأدنى.
BLOCK_LOW_AND_ABOVE سيتم السماح بالمحتوى الذي يتضمّن NEGLIGIBLE.
BLOCK_MEDIUM_AND_ABOVE سيتم السماح بالمحتوى الذي يتضمن تقييمَي NEGLIGIBLE وLOW.
BLOCK_ONLY_HIGH سيتم السماح بالمحتوى الذي يتضمن قيم "منخفضة" و"متوسطة" و"منخفضة جدًا".
BLOCK_NONE سيتم السماح بكل المحتوى.
OFF أوقِف فلتر الأمان.