Generating content

Gemini API mbështet gjenerimin e përmbajtjes me imazhe, audio, kode, mjete dhe më shumë. Për detaje mbi secilën prej këtyre veçorive, lexoni dhe shikoni kodin mostër të fokusuar në detyrë ose lexoni udhëzuesit gjithëpërfshirës.

Metoda: modele.gjenerojë Përmbajtje

Gjeneron një përgjigje modeli të dhënë një hyrje GenerateContentRequest . Referojuni udhëzuesit për gjenerimin e tekstit për informacion të detajuar të përdorimit. Aftësitë e hyrjes ndryshojnë midis modeleve, duke përfshirë modelet e sintonizuara. Për detaje, referojuni udhëzuesit të modelit dhe akordimit .

Pika përfundimtare

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

Parametrat e rrugës

string model

E detyrueshme. Emri i Model që do të përdoret për gjenerimin e përfundimit.

Formati: models/{model} . Ajo merr formën models/{model} .

Trupi i kërkesës

Trupi i kërkesës përmban të dhëna me strukturën e mëposhtme:

Fushat
contents[] object ( Content )

E detyrueshme. Përmbajtja e bisedës aktuale me modelen.

Për pyetjet me një kthesë, ky është një shembull i vetëm. Për pyetjet me shumë kthesa si chat , kjo është një fushë e përsëritur që përmban historikun e bisedave dhe kërkesën më të fundit.

tools[] object ( Tool )

Fakultative. Një listë e Tools Model mund të përdorë për të gjeneruar përgjigjen e radhës.

Një Tool është një pjesë kodi që i mundëson sistemit të ndërveprojë me sisteme të jashtme për të kryer një veprim, ose grup veprimesh, jashtë njohurive dhe qëllimit të Model . Tool e mbështetura janë Function dhe codeExecution . Referojuni thirrjes së funksionit dhe udhëzuesve të ekzekutimit të kodit për të mësuar më shumë.

Objekti toolConfig object ( ToolConfig )

Fakultative. Konfigurimi i mjetit për çdo Tool të specifikuar në kërkesë. Referojuni udhëzuesit për thirrjen e funksionit për një shembull përdorimi.

objekti safetySettings[] object ( SafetySetting )

Fakultative. Një listë e rasteve unike të SafetySetting për bllokimin e përmbajtjes së pasigurt.

Kjo do të zbatohet në GenerateContentRequest.contents dhe GenerateContentResponse.candidates . Nuk duhet të ketë më shumë se një cilësim për çdo lloj SafetyCategory . API do të bllokojë çdo përmbajtje dhe përgjigje që nuk arrin të përmbushë kufijtë e vendosur nga këto cilësime. Kjo listë anashkalon cilësimet e paracaktuara për secilën SafetyCategory të specifikuar në Cilësimet e sigurisë. Nëse nuk ka SafetySetting për një SafetyCategory të dhënë në listë, API do të përdorë cilësimin e paracaktuar të sigurisë për atë kategori. Kategoritë e dëmtimit HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY mbështeten. Referojuni udhëzuesit për informacion të detajuar mbi cilësimet e disponueshme të sigurisë. Referojuni gjithashtu udhëzimit të sigurisë për të mësuar se si të përfshini konsideratat e sigurisë në aplikacionet tuaja të AI.

Sistemi i objektit systemInstruction object ( Content )

Fakultative. Udhëzimet e sistemit të grupit të zhvilluesit. Aktualisht, vetëm tekst.

generationConfig object ( GenerationConfig )

Fakultative. Opsionet e konfigurimit për gjenerimin e modelit dhe daljet.

string cachedContent

Fakultative. Emri i përmbajtjes së memorizuar për t'u përdorur si kontekst për të shërbyer parashikimin. Formati: cachedContents/{cachedContent}

Shembull i kërkesës

Teksti

Python

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

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

Shkoni

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)

Shell

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

Imazhi

Python

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

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

Shkoni

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)

Shell

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

Audio

Python

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

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

Shell

# 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

Video

Python

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

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

Shkoni

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)

Shell

# 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

Shell

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

Bisedë

Python

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

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

Shkoni

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)

Shell

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

Cache

Python

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

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

Modeli i akorduar

Python

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

Modaliteti JSON

Python

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

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

Shkoni

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

Shell

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

Ekzekutimi i kodit

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

Funksioni Thirrja

Python

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

Nyja.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());
}

Shell


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

Konfigurimi i gjeneratës

Python

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

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

Shkoni

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)

Shell

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

Cilësimet e sigurisë

Python

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

Nyja.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);
}

Shkoni

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)

Shell

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

Udhëzimi i sistemit

Python

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

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

Shkoni

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)

Shell

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

Trupi i reagimit

Nëse është i suksesshëm, trupi i përgjigjes përmban një shembull të GenerateContentResponse .

Metoda: modele.streamGenerateContent

Gjeneron një përgjigje të transmetuar nga modeli i dhënë një hyrje GenerateContentRequest .

Pika përfundimtare

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

Parametrat e rrugës

string model

E detyrueshme. Emri i Model që do të përdoret për gjenerimin e përfundimit.

Formati: models/{model} . Ajo merr formën models/{model} .

Trupi i kërkesës

Trupi i kërkesës përmban të dhëna me strukturën e mëposhtme:

Fushat
contents[] object ( Content )

E detyrueshme. Përmbajtja e bisedës aktuale me modelen.

Për pyetjet me një kthesë, ky është një shembull i vetëm. Për pyetjet me shumë kthesa si chat , kjo është një fushë e përsëritur që përmban historikun e bisedave dhe kërkesën më të fundit.

tools[] object ( Tool )

Fakultative. Një listë e Tools Model mund të përdorë për të gjeneruar përgjigjen e radhës.

Një Tool është një pjesë kodi që i mundëson sistemit të ndërveprojë me sisteme të jashtme për të kryer një veprim, ose grup veprimesh, jashtë njohurive dhe qëllimit të Model . Tool e mbështetura janë Function dhe codeExecution . Referojuni thirrjes së funksionit dhe udhëzuesve të ekzekutimit të kodit për të mësuar më shumë.

Objekti toolConfig object ( ToolConfig )

Fakultative. Konfigurimi i mjetit për çdo Tool të specifikuar në kërkesë. Referojuni udhëzuesit për thirrjen e funksionit për një shembull përdorimi.

objekti safetySettings[] object ( SafetySetting )

Fakultative. Një listë e rasteve unike të SafetySetting për bllokimin e përmbajtjes së pasigurt.

Kjo do të zbatohet në GenerateContentRequest.contents dhe GenerateContentResponse.candidates . Nuk duhet të ketë më shumë se një cilësim për çdo lloj SafetyCategory . API do të bllokojë çdo përmbajtje dhe përgjigje që nuk arrin të përmbushë kufijtë e vendosur nga këto cilësime. Kjo listë anashkalon cilësimet e paracaktuara për secilën SafetyCategory të specifikuar në Cilësimet e sigurisë. Nëse nuk ka SafetySetting për një SafetyCategory të dhënë në listë, API do të përdorë cilësimin e paracaktuar të sigurisë për atë kategori. Kategoritë e dëmtimit HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY mbështeten. Referojuni udhëzuesit për informacion të detajuar mbi cilësimet e disponueshme të sigurisë. Referojuni gjithashtu udhëzimit të sigurisë për të mësuar se si të përfshini konsideratat e sigurisë në aplikacionet tuaja të AI.

Sistemi i objektit systemInstruction object ( Content )

Fakultative. Udhëzimet e sistemit të grupit të zhvilluesit. Aktualisht, vetëm tekst.

generationConfig object ( GenerationConfig )

Fakultative. Opsionet e konfigurimit për gjenerimin e modelit dhe daljet.

string cachedContent

Fakultative. Emri i përmbajtjes së memorizuar për t'u përdorur si kontekst për të shërbyer parashikimin. Formati: cachedContents/{cachedContent}

Shembull i kërkesës

Teksti

Python

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

Nyja.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);
}

Shkoni

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

Shell

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

Imazhi

Python

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

Nyja.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);
}

Shkoni

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

Shell

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

Audio

Python

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

Shell

# 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

Video

Python

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

Nyja.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);
}

Shkoni

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

Shell

# 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

Shell

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

Bisedë

Python

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

Nyja.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);
}

Shkoni

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

Shell

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

    });

Trupi i reagimit

Nëse është i suksesshëm, trupi i përgjigjes përmban një rrymë shembujsh GenerateContentResponse .

Generate Content Response

Përgjigje nga modeli që mbështet përgjigje të shumta të kandidatëve.

Vlerësimet e sigurisë dhe filtrimi i përmbajtjes raportohen si për kërkesën në GenerateContentResponse.prompt_feedback dhe për secilin kandidat në finishReason dhe në safetyRatings . API: - Kthen ose të gjithë kandidatët e kërkuar ose asnjërin prej tyre - Nuk kthen fare kandidatë vetëm nëse ka pasur diçka të gabuar me kërkesën (kontrollo promptFeedback ) - Raporton komentet për secilin kandidat në finishReason dhe safetyRatings .

Fushat
candidates[] object ( Candidate )

Përgjigjet e kandidatëve nga modeli.

object ( PromptFeedback ) promptFeedback (PromptFeedback)

Kthen komentet e kërkesës në lidhje me filtrat e përmbajtjes.

usageMetadata object ( UsageMetadata )

Vetëm dalje. Të dhënat meta mbi përdorimin e tokenit të kërkesave të gjenerimit.

string modelVersion

Vetëm dalje. Versioni i modelit i përdorur për të gjeneruar përgjigjen.

Përfaqësimi JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string
}

PromptFeedback

Një grup i meta të dhënave të komenteve, kërkesa e specifikuar në GenerateContentRequest.content .

Fushat
blockReason enum ( BlockReason )

Fakultative. Nëse vendoset, kërkesa është bllokuar dhe asnjë kandidat nuk kthehet. Riformuloni kërkesën.

Objekt safetyRatings[] object ( SafetyRating )

Vlerësimet për sigurinë e shpejtë. Ka më së shumti një vlerësim për kategori.

Përfaqësimi JSON
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

BlockReason

Përcakton arsyen pse u bllokua kërkesa.

Enums
BLOCK_REASON_UNSPECIFIED Vlera e paracaktuar. Kjo vlerë është e papërdorur.
SAFETY Kërkesa u bllokua për arsye sigurie. Inspektoni safetyRatings për të kuptuar se cila kategori e sigurisë e bllokoi atë.
OTHER Kërkesa u bllokua për arsye të panjohura.
BLOCKLIST Kërkesa u bllokua për shkak të kushteve që përfshihen nga lista e bllokimit të terminologjisë.
PROHIBITED_CONTENT Kërkesa u bllokua për shkak të përmbajtjes së ndaluar.
IMAGE_SAFETY Kandidatët u bllokuan për shkak të përmbajtjes së pasigurt të gjenerimit të imazheve.

Metadata e përdorimit

Të dhënat meta mbi përdorimin e tokenit të kërkesës së gjenerimit.

Fushat
promptTokenCount integer

Numri i shenjave në prompt. Kur caktohet cachedContent , kjo është ende madhësia totale efektive e kërkesës që do të thotë se kjo përfshin numrin e shenjave në përmbajtjen e memorizuar.

cachedContentTokenCount integer

Numri i shenjave në pjesën e memorizuar të kërkesës (përmbajtja e ruajtur në memorie)

candidatesTokenCount integer

Numri i përgjithshëm i argumenteve në të gjithë kandidatët e përgjigjeve të gjeneruara.

toolUsePromptTokenCount integer

Vetëm dalje. Numri i shenjave të pranishme në kërkesën(et) e përdorimit të veglave.

totalTokenCount integer

Numri total i shenjave për kërkesën e gjenerimit (kërkesa + kandidatët përgjigje).

objekt promptTokensDetails[] object ( ModalityTokenCount )

Vetëm dalje. Lista e modaliteteve që janë përpunuar në hyrjen e kërkesës.

cacheTokensDetails[] object ( ModalityTokenCount )

Vetëm dalje. Lista e modaliteteve të përmbajtjes së memorizuar në hyrjen e kërkesës.

candidatesTokensDetails[] object ( ModalityTokenCount )

Vetëm dalje. Lista e modaliteteve që janë kthyer në përgjigje.

object ( ModalityTokenCount ) toolUsePromptTokensDetails[] ( ModalityTokenCount )

Vetëm dalje. Lista e modaliteteve që u përpunuan për hyrjet e kërkesës për përdorim të veglave.

Përfaqësimi JSON
{
  "promptTokenCount": integer,
  "cachedContentTokenCount": integer,
  "candidatesTokenCount": integer,
  "toolUsePromptTokenCount": integer,
  "totalTokenCount": integer,
  "promptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "cacheTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "candidatesTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "toolUsePromptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ]
}

Kandidati

Një kandidat përgjigjeje i krijuar nga modeli.

Fushat
objekti content object ( Content )

Vetëm dalje. Përmbajtja e gjeneruar e kthyer nga modeli.

finishReason enum ( FinishReason )

Fakultative. Vetëm dalje. Arsyeja pse modeli ndaloi gjenerimin e argumenteve.

Nëse është bosh, modeli nuk ka ndaluar së gjeneruari shenja.

Objekt safetyRatings[] object ( SafetyRating )

Lista e vlerësimeve për sigurinë e një kandidati të përgjigjes.

Ka më së shumti një vlerësim për kategori.

citationMetadata object ( CitationMetadata )

Vetëm dalje. Informacioni i citimit për kandidatin e krijuar nga modeli.

Kjo fushë mund të plotësohet me informacion recitimi për çdo tekst të përfshirë në content . Këto janë pasazhe që janë "recituar" nga materiali me të drejtë autori në të dhënat e trajnimit të LLM-së.

tokenCount integer

Vetëm dalje. Numërimi simbolik për këtë kandidat.

groundingAttributions[] object ( GroundingAttribution )

Vetëm dalje. Informacioni i atribuimit për burimet që kontribuan në një përgjigje të bazuar.

Kjo fushë është e mbushur për thirrjet GenerateAnswer .

object ( GroundingMetadata ) groundingMetadata ( GroundingMetadata )

Vetëm dalje. Meta të dhënat bazë për kandidatin.

Kjo fushë është e mbushur për thirrjet GenerateContent .

number avgLogprobs

Vetëm dalje. Rezultati mesatar i probabilitetit log të kandidatit.

logprobsResult object ( LogprobsResult )

Vetëm dalje. Rezultatet e gjasave të regjistrit për argumentet e përgjigjes dhe shenjat kryesore

index integer

Vetëm dalje. Indeksi i kandidatit në listën e kandidatëve të përgjigjeve.

Përfaqësimi 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
}

PërfundoArsyeja

Përcakton arsyen pse modeli ndaloi gjenerimin e argumenteve.

Enums
FINISH_REASON_UNSPECIFIED Vlera e paracaktuar. Kjo vlerë është e papërdorur.
STOP Pika natyrore e ndalimit të modelit ose sekuenca e parashikuar e ndalimit.
MAX_TOKENS U arrit numri maksimal i argumenteve siç specifikohet në kërkesë.
SAFETY Përmbajtja e kandidatit të përgjigjes u raportua për arsye sigurie.
RECITATION Përmbajtja e kandidatit të përgjigjes u shënua për arsye recitimi.
LANGUAGE Përmbajtja e kandidatit të përgjigjes u raportua për përdorimin e një gjuhe të pambështetur.
OTHER Arsyeja e panjohur.
BLOCKLIST Gjenerimi i tokenit u ndal sepse përmbajtja përmban terma të ndaluar.
PROHIBITED_CONTENT Prodhimi i tokenit u ndal për përmbajtje potencialisht të ndaluar.
SPII Gjenerimi i tokenit u ndal sepse përmbajtja potencialisht përmban informacione të ndjeshme personale të identifikueshme (SPII).
MALFORMED_FUNCTION_CALL Thirrja e funksionit e krijuar nga modeli është e pavlefshme.
IMAGE_SAFETY Prodhimi i tokenit u ndal sepse imazhet e krijuara përmbajnë shkelje të sigurisë.

Atribuimi i themelimit

Atribuimi për një burim që kontribuoi në një përgjigje.

Fushat
objekti sourceId object ( AttributionSourceId )

Vetëm dalje. Identifikuesi për burimin që kontribuon në këtë atribuim.

objekti content object ( Content )

Përmbajtja e burimit bazë që përbën këtë atribut.

Përfaqësimi JSON
{
  "sourceId": {
    object (AttributionSourceId)
  },
  "content": {
    object (Content)
  }
}

AttributionSourceId

Identifikuesi për burimin që kontribuon në këtë atribuim.

Fushat
source Union type
source mund të jetë vetëm një nga sa vijon:
object ( GroundingPassageId ) groundingPassage ( GroundingPassageId )

Identifikuesi për një pasazh në linjë.

objekt semanticRetrieverChunk object ( SemanticRetrieverChunk )

Identifikuesi për një Chunk të marrë nëpërmjet Semantic Retriever.

Përfaqësimi JSON
{

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

GroundingPassageId

Identifikues për një pjesë brenda një GroundingPassage .

Fushat
string passageId

Vetëm dalje. ID e pasazhit që përputhet me GenerateAnswerRequest 's GroundingPassage.id .

partIndex integer

Vetëm dalje. Indeksi i pjesës brenda GenerateAnswerRequest 's GroundingPassage.content .

Përfaqësimi JSON
{
  "passageId": string,
  "partIndex": integer
}

SemanticRetrieverChunk

Identifikuesi për një Chunk të marrë nëpërmjet Retriever Semantic të specifikuar në GenerateAnswerRequest duke përdorur SemanticRetrieverConfig .

Fushat
source string

Vetëm dalje. Emri i burimit që përputhet me SemanticRetrieverConfig.source të kërkesës. Shembull: corpora/123 ose corpora/123/documents/abc

string chunk

Vetëm dalje. Emri i Chunk që përmban tekstin e atribuar. Shembull: corpora/123/documents/abc/chunks/xyz

Përfaqësimi JSON
{
  "source": string,
  "chunk": string
}

GroundingMetadata

Metadatat i kthehen klientit kur aktivizohet tokëzimi.

Fushat
object ( GroundingChunk ) groundingChunks[] ( GroundingChunk )

Lista e referencave mbështetëse të marra nga burimi i specifikuar i tokëzimit.

objekti groundingSupports[] object ( GroundingSupport )

Lista e mbështetjes së tokëzimit.

string webSearchQueries[]

Pyetjet e kërkimit në ueb për kërkimin vijues në ueb.

objekt searchEntryPoint object ( SearchEntryPoint )

Fakultative. Hyrja e kërkimit në Google për kërkimet vijuese në ueb.

retrievalMetadata object ( RetrievalMetadata )

Meta të dhënat që lidhen me marrjen në rrjedhën e tokëzimit.

Përfaqësimi JSON
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  }
}

SearchEntryPoint

Pika hyrëse e kërkimit në Google.

Fushat
renderedContent string përmbajtjes

Fakultative. Pjesë e përmbajtjes së uebit që mund të futet në një faqe ueb ose në një pamje ueb aplikacioni.

vargu sdkBlob string ( bytes format)

Fakultative. Base64 i koduar JSON që përfaqëson grupin e <term kërkimi, url kërkimi> tuple.

Një varg i koduar me bazë 64.

Përfaqësimi JSON
{
  "renderedContent": string,
  "sdkBlob": string
}

GroundingChunk

Copë e tokëzimit.

Fushat
chunk_type Union type
Lloji i copës. chunk_type mund të jetë vetëm një nga sa vijon:
objekt web object ( Web )

Një pjesë e tokëzimit nga uebi.

Përfaqësimi JSON
{

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

Web

Pjesë nga uebi.

Fushat
string uri

Referenca URI e pjesës.

string title

Titulli i pjesës.

Përfaqësimi JSON
{
  "uri": string,
  "title": string
}

Mbështetja e Tokës

Mbështetja e tokëzimit.

Fushat
groundingChunkIndices[] integer

Një listë indeksesh (në 'grounding_chunk') që specifikon citimet që lidhen me pretendimin. Për shembull, [1,3,4] do të thotë që tokëzimi_copë[1], tokëzimi_copë[3], tokëzimi_copë[4] janë përmbajtja e marrë që i atribuohet pretendimit.

number confidenceScores[]

Rezultati i besimit të referencave mbështetëse. Vargjet nga 0 në 1. 1 është më i sigurti. Kjo listë duhet të ketë të njëjtën madhësi si indekset e tokëzimitChunk.

objekt segment object ( Segment )

Segmenti i përmbajtjes së cilës i përket kjo mbështetje.

Përfaqësimi JSON
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

Segmenti

Segmenti i përmbajtjes.

Fushat
partIndex integer

Vetëm dalje. Indeksi i një objekti Part brenda objektit të tij mëmë Përmbajtje.

startIndex integer

Vetëm dalje. Indeksi i fillimit në pjesën e dhënë, i matur në bajt. Kompensimi nga fillimi i Pjesës, përfshirëse, duke filluar nga zero.

endIndex integer

Vetëm dalje. Indeksi i fundit në pjesën e dhënë, i matur në bajt. Kompensimi nga fillimi i Pjesës, ekskluziv, duke filluar nga zero.

string text

Vetëm dalje. Teksti që korrespondon me segmentin nga përgjigja.

Përfaqësimi JSON
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

RetrievalMetadata

Meta të dhënat që lidhen me marrjen në rrjedhën e tokëzimit.

Fushat
number googleSearchDynamicRetrievalScore

Fakultative. Rezultati që tregon se sa e mundshme informacioni nga kërkimi në Google mund të ndihmojë në përgjigjen e kërkesës. Rezultati është në intervalin [0, 1], ku 0 është më pak e mundshme dhe 1 është më e mundshme. Ky rezultat plotësohet vetëm kur aktivizohet baza e kërkimit në Google dhe rikthimi dinamik. Do të krahasohet me pragun për të përcaktuar nëse do të aktivizohet kërkimi në Google.

Përfaqësimi JSON
{
  "googleSearchDynamicRetrievalScore": number
}

Rezultati i problemeve të ditarit

Rezultati i problemit të ditarit

Fushat
topCandidates[] object ( TopCandidates )

Gjatësia = numri i përgjithshëm i hapave të dekodimit.

chosenCandidates[] object ( Candidate )

Gjatësia = numri i përgjithshëm i hapave të dekodimit. Kandidatët e zgjedhur mund të jenë ose jo në topKandidatët.

Përfaqësimi JSON
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ]
}

Top Kandidatët

Kandidatët me probabilitete të regjistrit kryesor në çdo hap të dekodimit.

Fushat
candidates[] object ( Candidate )

Renditur sipas probabilitetit të regjistrit në rend zbritës.

Përfaqësimi JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

Kandidati

Kandidati për shenjën dhe pikën logprobs.

Fushat
string token

Vlera e vargut token të kandidatit.

integer tokenId

Vlera e ID-së së kandidatit.

log number logProbability

Probabiliteti i regjistrit të kandidatit.

Përfaqësimi JSON
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

Metadatat e Citimit

Një koleksion i atributeve burimore për një pjesë të përmbajtjes.

Fushat
citationSources[] object ( CitationSource )

Citime në burime për një përgjigje specifike.

Përfaqësimi JSON
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}

Burimi i Citimit

Një citim në një burim për një pjesë të një përgjigje specifike.

Fushat
startIndex integer

Fakultative. Fillimi i segmentit të përgjigjes që i atribuohet këtij burimi.

Indeksi tregon fillimin e segmentit, i matur në bajt.

endIndex integer

Fakultative. Fundi i segmentit të atribuar, ekskluziv.

string uri

Fakultative. URI që atribuohet si burim për një pjesë të tekstit.

string license

Fakultative. Licenca për projektin GitHub që i atribuohet si burim për segmentin.

Informacioni i licencës kërkohet për citimet e kodit.

Përfaqësimi JSON
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}

GenerationConfig

Opsionet e konfigurimit për gjenerimin e modelit dhe daljet. Jo të gjithë parametrat janë të konfigurueshëm për çdo model.

Fushat
string stopSequences[]

Fakultative. Grupi i sekuencave të karaktereve (deri në 5) që do të ndalojnë gjenerimin e prodhimit. Nëse specifikohet, API do të ndalojë në shfaqjen e parë të një stop_sequence . Sekuenca e ndalimit nuk do të përfshihet si pjesë e përgjigjes.

string responseMimeType

Fakultative. Lloji MIME i tekstit kandidat të krijuar. Llojet MIME të mbështetura janë: text/plain : (parazgjedhja) Prodhimi i tekstit. application/json : Përgjigja JSON në kandidatët e përgjigjes. text/x.enum : ENUM si përgjigje e vargut në kandidatët e përgjigjes. Referojuni dokumenteve për një listë të të gjitha llojeve të tekstit MIME të mbështetur.

responseSchema object ( Schema )

Fakultative. Skema e daljes së tekstit të gjeneruar të kandidatit. Skemat duhet të jenë një nëngrup i skemës OpenAPI dhe mund të jenë objekte, primitivë ose vargje.

Nëse caktohet, duhet të vendoset gjithashtu një responseMimeType përputhshmeMimeType. Llojet e përputhshme MIME: application/json : Skema për përgjigjen JSON. Referojuni udhëzuesit për gjenerimin e tekstit JSON për më shumë detaje.

responseModalities[] enum ( Modality )

Fakultative. Modalitetet e kërkuara të përgjigjes. Përfaqëson grupin e modaliteteve që modeli mund t'i kthejë dhe duhet të priten në përgjigje. Kjo është një përputhje e saktë me modalitetet e përgjigjes.

Një model mund të ketë kombinime të shumta të modaliteteve të mbështetura. Nëse modalitetet e kërkuara nuk përputhen me asnjë nga kombinimet e mbështetura, do të kthehet një gabim.

Një listë boshe është e barabartë me kërkesën vetëm për tekst.

candidateCount integer

Fakultative. Numri i përgjigjeve të gjeneruara për t'u kthyer. Nëse nuk është caktuar, kjo do të jetë e paracaktuar në 1. Ki parasysh se kjo nuk funksionon për modelet e gjeneratës së mëparshme (familja Gemini 1.0)

maxOutputTokens integer

Fakultative. Numri maksimal i argumenteve për t'u përfshirë në një kandidat përgjigjeje.

Shënim: Vlera e paracaktuar ndryshon sipas modelit, shikoni atributin Model.output_token_limitModel të kthyer nga funksioni getModel .

number temperature

Fakultative. Kontrollon rastësinë e daljes.

Shënim: Vlera e paracaktuar ndryshon sipas modelit, shikoni atributin Model.temperatureModel të kthyer nga funksioni getModel .

Vlerat mund të variojnë nga [0.0, 2.0].

number topP

Fakultative. Probabiliteti maksimal kumulativ i argumenteve për t'u marrë parasysh gjatë marrjes së mostrave.

Modeli përdor kampionimin e kombinuar Top-k dhe Top-p (bërthamë).

Shenjat renditen në bazë të probabiliteteve të tyre të caktuara në mënyrë që të merren parasysh vetëm argumentet më të mundshëm. Mostra Top-k kufizon drejtpërdrejt numrin maksimal të argumenteve për t'u marrë në konsideratë, ndërsa kampionimi i bërthamës kufizon numrin e argumenteve bazuar në probabilitetin kumulativ.

Shënim: Vlera e paracaktuar ndryshon sipas Model dhe specifikohet nga atributi Model.top_p i kthyer nga funksioni getModel . Një atribut bosh topK tregon se modeli nuk aplikon kampionimin top-k dhe nuk lejon vendosjen e topK në kërkesat.

topK integer

Fakultative. Numri maksimal i argumenteve që duhen marrë parasysh gjatë marrjes së mostrave.

Modelet e Binjakëve përdorin kampionimin Top-p (bërthamë) ose një kombinim të kampionimit të Top-k dhe bërthamës. Mostra Top-k merr në konsideratë grupin e tokenëve më të mundshëm topK . Modelet që funksionojnë me kampionim bërthamor nuk lejojnë vendosjen e topK.

Shënim: Vlera e paracaktuar ndryshon sipas Model dhe specifikohet nga atributi Model.top_p i kthyer nga funksioni getModel . Një atribut bosh topK tregon se modeli nuk aplikon kampionimin top-k dhe nuk lejon vendosjen e topK në kërkesat.

integer seed

Fakultative. Fara e përdorur në dekodim. Nëse nuk është caktuar, kërkesa përdor një farë të krijuar rastësisht.

prania number presencePenalty

Fakultative. Dënimi i pranisë zbatohet për logprob-et e shenjës tjetër nëse shenja është parë tashmë në përgjigje.

Ky penallti është binar i ndezur/fikur dhe nuk varet nga numri i herëve që përdoret token (pas të parës). Përdorni frequencyPenalty për një dënim që rritet me çdo përdorim.

Një ndëshkim pozitiv do të dekurajojë përdorimin e shenjave që janë përdorur tashmë në përgjigje, duke rritur fjalorin.

Një ndëshkim negativ do të inkurajojë përdorimin e shenjave që janë përdorur tashmë në përgjigje, duke ulur fjalorin.

frequencyPenalty number dënimit

Fakultative. Dënimi i frekuencës i aplikuar për logprobs të shenjës tjetër, shumëzuar me numrin e herëve që çdo shenjë është parë në përgjigjen deri tani.

Një ndëshkim pozitiv do të dekurajojë përdorimin e shenjave që janë përdorur tashmë, në përpjesëtim me numrin e herëve të përdorur token: Sa më shumë të përdoret një token, aq më e vështirë është për modelin që ta përdorë atë token përsëri duke rritur fjalorin e përgjigjeve.

Kujdes: Një ndëshkim negativ do ta inkurajojë modelin të ripërdorë tokenat në përpjesëtim me numrin e herëve që është përdorur token. Vlerat e vogla negative do të zvogëlojnë fjalorin e një përgjigjeje. Vlerat më të mëdha negative do të bëjnë që modeli të fillojë të përsërisë një token të përbashkët derisa të arrijë kufirin maxOutputTokens .

responseLogprobs boolean

Fakultative. Nëse është e vërtetë, eksportoni logprobs rezulton në përgjigje.

logprobs integer

Fakultative. E vlefshme vetëm nëse responseLogprobs=True . Kjo cakton numrin e logprobs kryesore për t'u kthyer në çdo hap të dekodimit në Candidate.logprobs_result .

enableEnhancedCivicAnswers boolean

Fakultative. Mundëson përgjigje të zgjeruara qytetare. Mund të mos jetë i disponueshëm për të gjitha modelet.

object ( SpeechConfig ) speechConfig (SpeechConfig)

Fakultative. Konfigurimi i gjenerimit të të folurit.

mediaResolution enum ( MediaResolution )

Fakultative. Nëse specifikohet, do të përdoret rezolucioni i specifikuar i medias.

Përfaqësimi JSON
{
  "stopSequences": [
    string
  ],
  "responseMimeType": string,
  "responseSchema": {
    object (Schema)
  },
  "responseModalities": [
    enum (Modality)
  ],
  "candidateCount": integer,
  "maxOutputTokens": integer,
  "temperature": number,
  "topP": number,
  "topK": integer,
  "seed": integer,
  "presencePenalty": number,
  "frequencyPenalty": number,
  "responseLogprobs": boolean,
  "logprobs": integer,
  "enableEnhancedCivicAnswers": boolean,
  "speechConfig": {
    object (SpeechConfig)
  },
  "mediaResolution": enum (MediaResolution)
}

Modaliteti

Modalitetet e mbështetura të përgjigjes.

Enums
MODALITY_UNSPECIFIED Vlera e paracaktuar.
TEXT Tregon se modeli duhet të kthejë tekst.
IMAGE Tregon se modeli duhet të kthejë imazhe.
AUDIO Tregon se modeli duhet të kthejë audio.

SpeechConfig

Konfigurimi i gjenerimit të të folurit.

Fushat
object ( VoiceConfig ) voiceConfig (VoiceConfig)

Konfigurimi për t'u përdorur nga altoparlanti.

Përfaqësimi JSON
{
  "voiceConfig": {
    object (VoiceConfig)
  }
}

VoiceConfig

Konfigurimi për përdorimin e zërit.

Fushat
voice_config Union type
Konfigurimi për t'u përdorur nga altoparlanti. voice_config mund të jetë vetëm një nga sa vijon:
object ( PrebuiltVoiceConfig ) prebuiltVoiceConfig ( PrebuiltVoiceConfig )

Konfigurimi për zërin e parandërtuar për t'u përdorur.

Përfaqësimi JSON
{

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

PrebuiltVoiceConfig

Konfigurimi për t'u përdorur për altoparlantin e parandërtuar.

Fushat
voiceName string

Emri i zërit të paracaktuar për t'u përdorur.

Përfaqësimi JSON
{
  "voiceName": string
}

MediaRezolucioni

Rezolucioni i medias për median hyrëse.

Enums
MEDIA_RESOLUTION_UNSPECIFIED Rezolucioni i medias nuk është vendosur.
MEDIA_RESOLUTION_LOW Rezolucioni i medias është vendosur në të ulët (64 argumente).
MEDIA_RESOLUTION_MEDIUM Rezolucioni i medias është vendosur në mesatare (256 argumente).
MEDIA_RESOLUTION_HIGH Rezolucioni i medias u caktua në nivel të lartë (rikuadrimi i zmadhuar me 256 shenja).

Kategoria e dëmit

Kategoria e një vlerësimi.

Këto kategori mbulojnë lloje të ndryshme dëmtimesh që zhvilluesit mund të dëshirojnë t'i rregullojnë.

Enums
HARM_CATEGORY_UNSPECIFIED Kategoria është e paspecifikuar.
HARM_CATEGORY_DEROGATORY PALM - Komentet negative ose të dëmshme që synojnë identitetin dhe/ose atributin e mbrojtur.
HARM_CATEGORY_TOXICITY PALM - Përmbajtje që është e vrazhdë, mosrespektuese ose profane.
HARM_CATEGORY_VIOLENCE PALM - Përshkruan skenarë që përshkruajnë dhunën kundër një individi ose grupi, ose përshkrime të përgjithshme të grykës.
HARM_CATEGORY_SEXUAL PALM - Përmban referenca për akte seksuale ose përmbajtje të tjera të turpshme.
HARM_CATEGORY_MEDICAL PALM - Promovon këshilla mjekësore të pakontrolluara.
HARM_CATEGORY_DANGEROUS PALM - Përmbajtje e rrezikshme që promovon, lehtëson ose inkurajon akte të dëmshme.
HARM_CATEGORY_HARASSMENT Binjakët – Përmbajtje ngacmuese.
HARM_CATEGORY_HATE_SPEECH Binjakët – Gjuhë dhe përmbajtje urrejtjeje.
HARM_CATEGORY_SEXUALLY_EXPLICIT Binjakët – Përmbajtje seksuale eksplicite.
HARM_CATEGORY_DANGEROUS_CONTENT Binjakët – Përmbajtje të rrezikshme.
HARM_CATEGORY_CIVIC_INTEGRITY Binjakët - Përmbajtje që mund të përdoret për të dëmtuar integritetin qytetar.

ModalityTokenCount

Përfaqëson informacionin e numërimit të shenjave për një modalitet të vetëm.

Fushat
modality enum ( Modality )

Modaliteti i lidhur me këtë numërim simbolik.

tokenCount integer

Numri i argumenteve.

Përfaqësimi JSON
{
  "modality": enum (Modality),
  "tokenCount": integer
}

Modaliteti

Modaliteti i pjesës së përmbajtjes

Enums
MODALITY_UNSPECIFIED Modalitet i paspecifikuar.
TEXT Tekst i thjeshtë.
IMAGE Imazhi.
VIDEO Video.
AUDIO Audio.
DOCUMENT Dokument, p.sh. PDF.

Vlerësimi i Sigurisë

Vlerësimi i sigurisë për një pjesë të përmbajtjes.

Vlerësimi i sigurisë përmban kategorinë e dëmtimit dhe nivelin e probabilitetit të dëmtimit në atë kategori për një pjesë të përmbajtjes. Përmbajtja klasifikohet për siguri në një sërë kategorish dëmi dhe këtu përfshihet probabiliteti i klasifikimit të dëmit.

Fushat
numërimi i category enum ( HarmCategory )

E detyrueshme. Kategoria për këtë vlerësim.

numër probability enum ( HarmProbability )

E detyrueshme. Mundësia e dëmtimit për këtë përmbajtje.

boolean blocked

A u bllokua kjo përmbajtje për shkak të këtij vlerësimi?

Përfaqësimi JSON
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}

Dëm Probabiliteti

Probabiliteti që një pjesë e përmbajtjes të jetë e dëmshme.

Sistemi i klasifikimit jep probabilitetin që përmbajtja të jetë e pasigurt. Kjo nuk tregon ashpërsinë e dëmit për një pjesë të përmbajtjes.

Enums
HARM_PROBABILITY_UNSPECIFIED Probabiliteti është i papërcaktuar.
NEGLIGIBLE Përmbajtja ka një shans të papërfillshëm për të qenë i pasigurt.
LOW Përmbajtja ka një shans të ulët për të qenë i pasigurt.
MEDIUM Përmbajtja ka një shans mesatar për të qenë e pasigurt.
HIGH Përmbajtja ka një shans të lartë për të qenë i pasigurt.

SafetySetting

Vendosja e sigurisë, që ndikon në sjelljen e bllokimit të sigurisë.

Kalimi i një cilësimi sigurie për një kategori ndryshon probabilitetin e lejuar që përmbajtja të jetë e bllokuar.

Fushat
numërimi i category enum ( HarmCategory )

E detyrueshme. Kategoria për këtë cilësim.

threshold enum ( HarmBlockThreshold )

E detyrueshme. Kontrollon pragun e probabilitetit në të cilin dëmi është bllokuar.

Përfaqësimi JSON
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

HarmBlockThreshold

Blloko në dhe përtej një probabiliteti të caktuar dëmtimi.

Enums
HARM_BLOCK_THRESHOLD_UNSPECIFIED Pragu është i paspecifikuar.
BLOCK_LOW_AND_ABOVE Përmbajtja me NEGLIGIBLE do të lejohet.
BLOCK_MEDIUM_AND_ABOVE Përmbajtja me NEGLIGIBLE dhe LOW do të lejohet.
BLOCK_ONLY_HIGH Përmbajtja me NEGJLIGIBLE, LOW dhe MESIMORE do të lejohet.
BLOCK_NONE E gjithë përmbajtja do të lejohet.
OFF Fikni filtrin e sigurisë.