Generating content

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

Metoda: models.generateContent

Gjeneron një përgjigje modeli të dhënë nga një input GenerateContentRequest . Referojuni udhëzuesit të gjenerimit të tekstit për informacion të detajuar mbi përdorimin. Aftësitë e inputit ndryshojnë midis modeleve, duke përfshirë modelet e akorduara. Referojuni udhëzuesit të modelit dhe udhëzuesit të akordimit për detaje.

Pika e Fundit

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

Parametrat e shtegut

string model

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

Formati: models/{model} . 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 modelin.

Për pyetjet me një kthesë, kjo është një instancë e vetme. Për pyetjet me shumë kthesa si chat , kjo është një fushë e përsëritur që përmban historikun e bisedës dhe kërkesën e fundit.

tools[] object ( Tool )

Opsionale. Një listë e Tools Model mund të përdorë për të gjeneruar përgjigjen tjetër.

Një Tool është një pjesë kodi që i mundëson sistemit të bashkëveprojë me sisteme të jashtme për të kryer një veprim, ose një sërë veprimesh, jashtë njohurive dhe fushëveprimit të Model . Tool e mbështetura janë Function dhe codeExecution . Referojuni udhëzuesve të Thirrjes së Funksionit dhe Ekzekutimit të Kodit për të mësuar më shumë.

object ( ToolConfig ) toolConfig (ToolConfig)

Opsionale. Konfigurimi i mjetit për çdo Tool të specifikuar në kërkesë. Referojuni udhëzuesit të thirrjes së funksionit për një shembull përdorimi.

objekti safetySettings[] object ( SafetySetting )

Opsionale. Një listë e instancave unike 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 secilin lloj SafetyCategory . API do të bllokojë çdo përmbajtje dhe përgjigje që nuk arrin pragjet e vendosura nga këto cilësime. Kjo listë mbivendos cilësimet fillestare për secilën SafetyCategory të specifikuar në safetyCettings. Nëse nuk ka SafetySetting për një SafetyCategory të caktuar të dhënë në listë, API do të përdorë cilësimin fillestar të sigurisë për atë kategori. Mbështeten kategoritë e dëmit HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY. Referojuni udhëzuesit për informacion të detajuar mbi cilësimet e sigurisë në dispozicion. Referojuni gjithashtu udhëzuesit të Sigurisë për të mësuar se si të përfshini konsideratat e sigurisë në aplikacionet tuaja të IA-së.

objekti systemInstruction object ( Content )

Opsionale. Zhvilluesi ka vendosur udhëzimet e sistemit . Aktualisht, vetëm tekst.

object ( GenerationConfig ) generationConfig (GenerationConfig)

Opsionale. Opsione konfigurimi për gjenerimin e modelit dhe rezultatet.

string cachedContent

Opsionale. Emri i përmbajtjes së ruajtur në memorien e përkohshme që do të përdoret si kontekst për të shërbyer parashikimin. Formati: cachedContents/{cachedContent}

Shembull kërkese

Tekst

Python

from google import genai

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

Node.js

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

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

Shko

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

Guaskë

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

Java

Client client = new Client();

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

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

Imazh

Python

from google import genai
import PIL.Image

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

Node.js

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

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

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

Shko

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

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

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

Guaskë

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

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

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

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

Java

Client client = new Client();

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

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

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

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

Audio

Python

from google import genai

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

Node.js

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

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

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

Shko

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

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

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

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

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

Guaskë

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

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

Video

Python

from google import genai
import time

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

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

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

Node.js

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

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

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

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

Shko

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

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

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

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

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

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

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

Guaskë

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

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

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

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

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

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

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

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

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

cat response.json
echo

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

PDF

Python

from google import genai

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

Shko

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

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

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

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

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

Guaskë

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

Bisedë

Python

from google import genai
from google.genai import types

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

Node.js

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

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

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

Shko

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

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

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

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

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

Guaskë

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

Java

Client client = new Client();

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

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

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

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

Memoria e përkohshme

Python

from google import genai
from google.genai import types

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

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

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

Node.js

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

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

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

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

Shko

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

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

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

Model i akorduar

Python

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

Modaliteti JSON

Python

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

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

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

Node.js

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

Shko

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

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

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

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

Guaskë

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

Java

Client client = new Client();

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

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

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

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

Ekzekutimi i kodit

Python

from google import genai
from google.genai import types

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

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

Shko

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

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

// Print the response.
printResponse(response)

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

Java

Client client = new Client();

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

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

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

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

Thirrja e funksionit

Python

from google import genai
from google.genai import types

client = genai.Client()

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

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

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

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

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

Shko

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

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

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

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

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

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

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

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

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

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

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

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

printResponse(finalResponse)

Node.js

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Guaskë


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

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

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

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

Java

Client client = new Client();

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

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

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

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

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

                )
        )
        .build();

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


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

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

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

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

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

System.out.println(result);

Konfigurimi i gjenerimit

Python

from google import genai
from google.genai import types

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

Node.js

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

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

console.log(response.text);

Shko

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

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

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

printResponse(response)

Guaskë

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

Java

Client client = new Client();

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

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

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

Cilësimet e Sigurisë

Python

from google import genai
from google.genai import types

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

print(response.candidates[0].safety_ratings)

Node.js

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

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

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

Shko

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

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

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

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

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

Guaskë

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

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

Java

Client client = new Client();

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

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

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

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

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

Udhëzime për Sistemin

Python

from google import genai
from google.genai import types

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

Node.js

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

Shko

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

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

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

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

Guaskë

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

Java

Client client = new Client();

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

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

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

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

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

Trupi i përgjigjes

Nëse është e suksesshme, trupi i përgjigjes përmban një instancë të GenerateContentResponse .

Metoda: models.streamGenerateContent

Gjeneron një përgjigje të transmetuar nga modeli kur jepet një input GenerateContentRequest .

Pika e Fundit

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

Parametrat e shtegut

string model

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

Formati: models/{model} . 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 modelin.

Për pyetjet me një kthesë, kjo është një instancë e vetme. Për pyetjet me shumë kthesa si chat , kjo është një fushë e përsëritur që përmban historikun e bisedës dhe kërkesën e fundit.

tools[] object ( Tool )

Opsionale. Një listë e Tools Model mund të përdorë për të gjeneruar përgjigjen tjetër.

Një Tool është një pjesë kodi që i mundëson sistemit të bashkëveprojë me sisteme të jashtme për të kryer një veprim, ose një sërë veprimesh, jashtë njohurive dhe fushëveprimit të Model . Tool e mbështetura janë Function dhe codeExecution . Referojuni udhëzuesve të Thirrjes së Funksionit dhe Ekzekutimit të Kodit për të mësuar më shumë.

object ( ToolConfig ) toolConfig (ToolConfig)

Opsionale. Konfigurimi i mjetit për çdo Tool të specifikuar në kërkesë. Referojuni udhëzuesit të thirrjes së funksionit për një shembull përdorimi.

objekti safetySettings[] object ( SafetySetting )

Opsionale. Një listë e instancave unike 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 secilin lloj SafetyCategory . API do të bllokojë çdo përmbajtje dhe përgjigje që nuk arrin pragjet e vendosura nga këto cilësime. Kjo listë mbivendos cilësimet fillestare për secilën SafetyCategory të specifikuar në safetyCettings. Nëse nuk ka SafetySetting për një SafetyCategory të caktuar të dhënë në listë, API do të përdorë cilësimin fillestar të sigurisë për atë kategori. Mbështeten kategoritë e dëmit HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY. Referojuni udhëzuesit për informacion të detajuar mbi cilësimet e sigurisë në dispozicion. Referojuni gjithashtu udhëzuesit të Sigurisë për të mësuar se si të përfshini konsideratat e sigurisë në aplikacionet tuaja të IA-së.

objekti systemInstruction object ( Content )

Opsionale. Zhvilluesi ka vendosur udhëzimet e sistemit . Aktualisht, vetëm tekst.

object ( GenerationConfig ) generationConfig (GenerationConfig)

Opsionale. Opsione konfigurimi për gjenerimin e modelit dhe rezultatet.

string cachedContent

Opsionale. Emri i përmbajtjes së ruajtur në memorien e përkohshme që do të përdoret si kontekst për të shërbyer parashikimin. Formati: cachedContents/{cachedContent}

Shembull kërkese

Tekst

Python

from google import genai

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

Node.js

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

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

Shko

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

Guaskë

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

Java

Client client = new Client();

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

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

responseStream.close();

Imazh

Python

from google import genai
import PIL.Image

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

Node.js

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

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

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

Shko

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

Guaskë

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

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

Java

Client client = new Client();

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

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


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

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

responseStream.close();

Audio

Python

from google import genai

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

Shko

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

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

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

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

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

Guaskë

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

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

Video

Python

from google import genai
import time

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

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

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

Node.js

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

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

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

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

Shko

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

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

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

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

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

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

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

Guaskë

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

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

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

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

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

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

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

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

cat response.json
echo

PDF

Python

from google import genai

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

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

Shko

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

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

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

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

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

Guaskë

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

Bisedë

Python

from google import genai
from google.genai import types

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

print(chat.get_history())

Node.js

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

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

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

console.log(chat.getHistory());

Shko

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

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

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

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

fmt.Println(chat.History(false))

Guaskë

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

Trupi i përgjigjes

Nëse është i suksesshëm, trupi i përgjigjes përmban një rrjedhë instancash GenerateContentResponse .

GjeneroniPërgjigjePërmbajtjeje

Përgjigje nga modeli që mbështet përgjigje të shumëfishta kandidate.

Vlerësimet e sigurisë dhe filtrimi i përmbajtjes raportohen si për kërkesën në GenerateContentResponse.prompt_feedback ashtu edhe 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 asnjë kandidat vetëm nëse ka pasur diçka të gabuar me kërkesën (kontrolloni promptFeedback ) - Raporton reagime mbi secilin kandidat në finishReason dhe safetyRatings .

Fushat
candidates[] object ( Candidate )

Përgjigjet e kandidatëve nga modeli.

object ( PromptFeedback ) promptFeedback (PromptFeedback)

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

object ( UsageMetadata ) usageMetadata (UsageMetadata)

Vetëm rezultate. Meta të dhëna mbi përdorimin e tokenëve nga kërkesat e gjenerimit.

string modelVersion

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

vargu i ID- string responseId

Vetëm rezultat. responseId përdoret për të identifikuar çdo përgjigje.

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

Reagime të Shpejta

Një grup meta të dhënash reagimi të specifikuara në GenerateContentRequest.content .

Fushat
numërimi i blockReason enum ( BlockReason )

Opsionale. Nëse vendoset, kërkesa është bllokuar dhe nuk janë kthyer kandidatë. Riformulojeni kërkesën.

safetyRatings[] object ( SafetyRating )

Vlerësime për sigurinë e kërkesës. Ka maksimumi një vlerësim për kategori.

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

BlockReason

Specifikon arsyen pse kërkesa u bllokua.

Numërime
BLOCK_REASON_UNSPECIFIED Vlerë e parazgjedhur. Kjo vlerë nuk përdoret.
SAFETY Kërkesa u bllokua për arsye sigurie. Inspektoni safetyRatings për të kuptuar se cila kategori sigurie e bllokoi atë.
OTHER Kërkesa u bllokua për arsye të panjohura.
BLOCKLIST Kërkesa u bllokua për shkak të termave që janë përfshirë 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.

PërdorimiMeta të dhëna

Meta të dhëna mbi përdorimin e tokenit të kërkesës së gjenerimit.

Fushat
integer promptTokenCount

Numri i tokenëve në kërkesë. Kur vendoset cachedContent , kjo është ende madhësia totale efektive e kërkesës, që do të thotë se kjo përfshin numrin e tokenëve në përmbajtjen e ruajtur në memorien e përkohshme.

integer cachedContentTokenCount

Numri i tokenëve në pjesën e ruajtur në memorje të kërkesës (përmbajtja e ruajtur në memorje)

integer candidatesTokenCount

Numri total i tokenëve në të gjithë kandidatët e përgjigjeve të gjeneruara.

integer toolUsePromptTokenCount

Vetëm rezultat. Numri i tokenëve të pranishëm në kërkesën/kërkesat e përdorimit të mjetit.

thoughtsTokenCount integer

Vetëm rezultati. Numri i tokenëve të mendimeve për modelet e të menduarit.

totalTokenCount integer

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

objekt promptTokensDetails[] object ( ModalityTokenCount )

Vetëm rezultati. Lista e modaliteteve që u përpunuan në të dhënat hyrëse të kërkesës.

object ( ModalityTokenCount ) cacheTokensDetails[] (ModalityTokenCount)

Vetëm rezultati. Lista e modaliteteve të përmbajtjes së ruajtur në memorien e përkohshme në të dhënat hyrëse të kërkesës.

objekti candidatesTokensDetails[] object ( ModalityTokenCount )

Vetëm rezultati. Lista e modaliteteve që u kthyen në përgjigje.

object ( ModalityTokenCount ) toolUsePromptTokensDetails[] (ModalityTokenCount)

Vetëm rezultate. Lista e modaliteteve që u përpunuan për hyrjet e kërkesave për përdorimin e mjetit.

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

Kandidat

Një kandidat për përgjigje i gjeneruar nga modeli.

Fushat
objekti content object ( Content )

Vetëm rezultat. Përmbajtja e gjeneruar u kthye nga modeli.

numërimi i finishReason enum ( FinishReason )

Opsionale. Vetëm dalje. Arsyeja pse modeli ndaloi gjenerimin e tokenëve.

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

safetyRatings[] object ( SafetyRating )

Lista e vlerësimeve për sigurinë e një kandidati për përgjigje.

Ka maksimumi një vlerësim për kategori.

object ( CitationMetadata ) citationMetadata (CitationMetadata)

Vetëm rezultate. Informacion mbi citatin për kandidatin e gjeneruar nga modeli.

Kjo fushë mund të mbushet me informacion recitimi për çdo tekst të përfshirë në content . Këto janë pasazhe që "recitohen" nga materiali i mbrojtur me të drejta autori në të dhënat e trajnimit të LLM-së themelore.

integer tokenCount

Vetëm rezultate. Numri i tokenëve për këtë kandidat.

groundingAttributions[] object ( GroundingAttribution )

Vetëm rezultate. Informacion mbi atribuimin për burimet që kontribuan në një përgjigje të bazuar.

Kjo fushë plotësohet për thirrjet GenerateAnswer .

object ( GroundingMetadata ) groundingMetadata (GroundingMetadata)

Vetëm rezultate. Metadata bazë për kandidatin.

Kjo fushë plotësohet për thirrjet GenerateContent .

number avgLogprobs

Vetëm rezultati. Rezultati mesatar i probabilitetit logaritmik të kandidatit.

object ( LogprobsResult ) logprobsResult (LogprobsResult)

Vetëm rezultate. Rezultatet e gjasës logaritmike për tokenët e përgjigjes dhe tokenët kryesorë

object ( UrlContextMetadata ) urlContextMetadata (UrlContextMetadata)

Vetëm rezultate. Meta të dhëna që lidhen me mjetin e rikthimit të kontekstit të url-së.

index integer

Vetëm rezultati. Indeksi i kandidatit në listën e kandidatëve të përgjigjes.

string finishMessage

Opsionale. Vetëm rezultat. Detajon arsyen pse modeli ndaloi gjenerimin e tokenëve. Kjo plotësohet vetëm kur është vendosur finishReason .

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)
  },
  "urlContextMetadata": {
    object (UrlContextMetadata)
  },
  "index": integer,
  "finishMessage": string
}

Arsyeja e Fundit

Përcakton arsyen pse modeli ndaloi gjenerimin e tokenëve.

Numërime
FINISH_REASON_UNSPECIFIED Vlerë e parazgjedhur. Kjo vlerë nuk përdoret.
STOP Pika natyrale e ndalimit të modelit ose sekuenca e dhënë e ndalimit.
MAX_TOKENS U arrit numri maksimal i tokenëve të specifikuar në kërkesë.
SAFETY Përmbajtja e kandidatit për përgjigje u raportua për arsye sigurie.
RECITATION Përmbajtja e kandidatit për përgjigje u sinjalizua për arsye recitimi.
LANGUAGE Përmbajtja e kandidatit për përgjigje u raportua për përdorim të një gjuhe të pambështetur.
OTHER Arsye e panjohur.
BLOCKLIST Gjenerimi i tokenëve ndaloi sepse përmbajtja përmban terma të ndaluar.
PROHIBITED_CONTENT Gjenerimi i tokenëve u ndalua për shkak se përmbante përmbajtje të ndaluar.
SPII Gjenerimi i tokenëve ndaloi sepse përmbajtja potencialisht përmban Informacion Personal të Identifikueshëm të Ndjeshëm (SPII).
MALFORMED_FUNCTION_CALL Thirrja e funksionit e gjeneruar nga modeli është e pavlefshme.
IMAGE_SAFETY Gjenerimi i tokenëve ndaloi sepse imazhet e gjeneruara përmbajnë shkelje të sigurisë.
IMAGE_PROHIBITED_CONTENT Gjenerimi i imazheve ndaloi sepse imazhet e gjeneruara kanë përmbajtje tjetër të ndaluar.
IMAGE_OTHER Gjenerimi i imazheve u ndal për shkak të problemeve të tjera të ndryshme.
NO_IMAGE Modeli pritej të gjeneronte një imazh, por asnjë nuk u gjenerua.
IMAGE_RECITATION Gjenerimi i imazheve u ndal për shkak të recitimit.
UNEXPECTED_TOOL_CALL Modeli gjeneroi një thirrje mjeti, por asnjë mjet nuk u aktivizua në kërkesë.
TOO_MANY_TOOL_CALLS Modeli thirri shumë mjete radhazi, kështu që sistemi doli nga ekzekutimi.

Atribuimi i Tokëzimit

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

Fushat
objekti sourceId object ( AttributionSourceId )

Vetëm rezultati. Identifikues për burimin që kontribuon në këtë atribuim.

objekti content object ( Content )

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

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

ID e Burimit të Atribuimit

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

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

Identifikues për një pasazh të brendshëm.

object ( SemanticRetrieverChunk ) semanticRetrieverChunk (SemanticRetrieverChunk)

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

Përfaqësimi JSON
{

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

Identifikuesi i Kalimit të Tokës

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

Fushat
passageId string -së së pasazhit

Vetëm rezultati. ID e pasazhit që përputhet me GroundingPassage.idGenerateAnswerRequest .

integer partIndex

Vetëm rezultati. Indeksi i pjesës brenda GroundingPassage.contentGenerateAnswerRequest .

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

SemanticRetrieverChunk

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

Fushat
source string

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

chunk string

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

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

Metadata e Grounding

Meta të dhënat 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.

webSearchQueries[] string

Pyetje kërkimi në internet për kërkimin pasues në internet.

objekti searchEntryPoint object ( SearchEntryPoint )

Opsionale. Hyrje kërkimi në Google për kërkimet pasuese në internet.

object ( RetrievalMetadata ) retrievalMetadata (RetrievalMetadata)

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

string googleMapsWidgetContextToken

Opsionale. Emri i burimit të tokenit të kontekstit të vegël Google Maps që mund të përdoret me vegël PlacesContextElement për të paraqitur të dhëna kontekstuale. Plotësohet vetëm në rast se është aktivizuar bazamenti me Google Maps.

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

SearchEntryPoint

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

Fushat
string renderedContent

Opsionale. Fragment përmbajtjeje uebi që mund të integrohet në një faqe uebi ose në një pamje uebi të aplikacionit.

Vargu sdkBlob string ( bytes format)

Opsionale. JSON i koduar me Base64 që përfaqëson një varg të tuple-it <term kërkimi, url kërkimi>.

Një varg i koduar me base64.

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

GroundingChunk

Copë tokëzimi.

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

Një copë tokëzimi nga rrjeti.

object ( RetrievedContext ) retrievedContext (RetrievedContext)

Opsionale. Pjesa e tokëzimit nga konteksti e marrë nga mjeti i kërkimit të skedarëve.

objekti i maps object ( Maps )

Opsionale. Pjesë tokëzimi nga Google Maps.

Përfaqësimi JSON
{

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

Uebi

Pjesë nga uebi.

Fushat
string uri

Referenca URI e copës.

string title

Titulli i pjesës.

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

Konteksti i Marrë

Pjesë nga konteksti e marrë nga mjeti i kërkimit të skedarëve.

Fushat
string uri

Opsionale. Referenca URI e dokumentit të rikthimit semantik.

string title

Opsionale. Titulli i dokumentit.

string text

Opsionale. Teksti i pjesës.

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

Hartat

Një pjesë e lidhjes së tokës nga Google Maps. Një pjesë e Maps korrespondon me një vend të vetëm.

Fushat
string uri

Referenca URI e vendit.

string title

Titulli i vendit.

string text

Përshkrim me tekst i përgjigjes së vendit.

string placeId

Ky ID i vendit, në formatin places/{placeId} . Një përdorues mund ta përdorë këtë ID për të kërkuar atë vend.

object ( PlaceAnswerSources ) placeAnswerSources (PlaceAnswerSources)

Burime që ofrojnë përgjigje rreth karakteristikave të një vendi të caktuar në Google Maps.

Përfaqësimi JSON
{
  "uri": string,
  "title": string,
  "text": string,
  "placeId": string,
  "placeAnswerSources": {
    object (PlaceAnswerSources)
  }
}

Burimet e Përgjigjeve të Vendit

Përmbledhje burimesh që ofrojnë përgjigje rreth karakteristikave të një vendi të caktuar në Google Maps. Çdo mesazh i PlaceAnswerSources korrespondon me një vend specifik në Google Maps. Mjeti Google Maps përdori këto burime për t'iu përgjigjur pyetjeve rreth karakteristikave të vendit (p.sh.: "a ka Bar Foo Wifi" ose "a është Foo Bar i arritshëm për karroca me rrota?"). Aktualisht ne mbështesim vetëm fragmente rishikimesh si burime.

Fushat
objekt reviewSnippets[] object ( ReviewSnippet )

Fragmente të vlerësimeve që përdoren për të gjeneruar përgjigje rreth karakteristikave të një vendi të caktuar në Google Maps.

Përfaqësimi JSON
{
  "reviewSnippets": [
    {
      object (ReviewSnippet)
    }
  ]
}

Fragment Rishikimi

Përmban një fragment të një vlerësimi përdoruesi që përgjigjet një pyetjeje në lidhje me veçoritë e një vendi specifik në Google Maps.

Fushat
string -së së reviewId

ID-ja e fragmentit të rishikimit.

string googleMapsUri

Një lidhje që korrespondon me vlerësimin e përdoruesit në Google Maps.

string title

Titulli i rishikimit.

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

Mbështetje për Tokëzim

Mbështetje për tokëzim.

Fushat
groundingChunkIndices[] integer

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

number confidenceScores[]

Rezultati i besimit të referencave të mbështetjes. Varion nga 0 në 1. 1 është më i besueshmi. Kjo listë duhet të ketë të njëjtën madhësi si groundingChunkIndices.

objekt segment object ( Segment )

Segmenti i përmbajtjes të cilit i përket kjo mbështetje.

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

Segmenti

Segment i përmbajtjes.

Fushat
integer partIndex

Vetëm rezultati. Indeksi i një objekti Part brenda objektit të tij mëmë Content.

integer startIndex

Vetëm dalje. Indeksi fillestar në Pjesën e dhënë, i matur në bajt. Zhvendosje 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. Zhvendosje nga fillimi i Pjesës, përjashtuese, duke filluar nga zero.

string text

Vetëm rezultati. Teksti që korrespondon me segmentin nga përgjigjja.

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

Metadata e Rikthimit

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

Fushat
number googleSearchDynamicRetrievalScore

Opsionale. Rezultati që tregon se sa të mundshme janë informacionet nga kërkimi në Google që mund të ndihmojnë në përgjigjen e pyetjes. Rezultati është në diapazonin [0, 1], ku 0 është më pak e mundshme dhe 1 është më e mundshme. Ky rezultat plotësohet vetëm kur aktivizohet bazamenti i 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ë regjistrimit

Rezultati i Logprobs

Fushat
topCandidates[] object ( TopCandidates )

Gjatësia = numri total i hapave të dekodimit.

objekt chosenCandidates[] object ( Candidate )

Gjatësia = numri total i hapave të dekodimit. Kandidatët e zgjedhur mund të jenë ose jo në listën e kandidatëve kryesorë.

number logProbabilitySum

Shuma e probabiliteteve logaritmike për të gjitha tokenët.

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

Kandidatët Kryesorë

Kandidatët me probabilitete logaritmike më të larta në çdo hap dekodifikimi.

Fushat
candidates[] object ( Candidate )

Renditur sipas probabilitetit logaritmik në rend zbritës.

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

Kandidat

Kandidat për shenjën dhe rezultatin logprobs.

Fushat
string token

Vlera e vargut të tokenit të kandidatit.

integer tokenId

Vlera e identifikimit të tokenit të kandidatit.

number logProbability

Probabiliteti logaritmik i kandidatit.

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

Metadata e Kontekstit Url

Meta të dhëna që lidhen me mjetin e rikthimit të kontekstit të URL-së.

Fushat
objekti urlMetadata[] object ( UrlMetadata )

Lista e kontekstit të URL-së.

Përfaqësimi JSON
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}

Metadata Url

Konteksti i rikthimit të një URL-je të vetme.

Fushat
string retrievedUrl

URL-ja u mor nga mjeti.

urlRetrievalStatus enum ( UrlRetrievalStatus )

Statusi i rikthimit të URL-së.

Përfaqësimi JSON
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}

Statusi i Rikthimit të Url-së

Statusi i rikthimit të URL-së.

Numërime
URL_RETRIEVAL_STATUS_UNSPECIFIED Vlerë e parazgjedhur. Kjo vlerë nuk përdoret.
URL_RETRIEVAL_STATUS_SUCCESS Marrja e URL-së është kryer me sukses.
URL_RETRIEVAL_STATUS_ERROR Marrja e URL-së dështoi për shkak të një gabimi.
URL_RETRIEVAL_STATUS_PAYWALL Marrja e URL-së dështoi sepse përmbajtja është pas murit të pagesës.
URL_RETRIEVAL_STATUS_UNSAFE Marrja e URL-së dështoi sepse përmbajtja është e pasigurt.

Meta të dhënat e citimeve

Një koleksion i atribuimeve të burimit për një pjesë të përmbajtjes.

Fushat
objekti citationSources[] object ( CitationSource )

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

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

Burimi i Citimit

Një citim nga një burim për një pjesë të një përgjigjeje specifike.

Fushat
integer startIndex

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

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

endIndex integer

Opsionale. Fundi i segmentit të atribuuar, përjashtues.

string uri

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

string license

Opsionale. Licencë 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
}

Konfigurimi i Gjeneratës

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

Fushat
string stopSequences[]

Opsionale. Sekuencat e karaktereve (deri në 5) që do të ndalojnë gjenerimin e rezultateve. Nëse specifikohet, API do të ndalet në shfaqjen e parë të një stop_sequence . Sekuenca e ndalimit nuk do të përfshihet si pjesë e përgjigjes.

string responseMimeType

Optional. MIME type of the generated candidate text. Supported MIME types are: text/plain : (default) Text output. application/json : JSON response in the response candidates. text/x.enum : ENUM as a string response in the response candidates. Refer to the docs for a list of all supported text MIME types.

responseSchema object ( Schema )

Optional. Output schema of the generated candidate text. Schemas must be a subset of the OpenAPI schema and can be objects, primitives or arrays.

If set, a compatible responseMimeType must also be set. Compatible MIME types: application/json : Schema for JSON response. Refer to the JSON text generation guide for more details.

_responseJsonSchema value ( Value format)

Optional. Output schema of the generated response. This is an alternative to responseSchema that accepts JSON Schema .

If set, responseSchema must be omitted, but responseMimeType is required.

While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported:

  • $id
  • $defs
  • $ref
  • $anchor
  • type
  • format
  • title
  • description
  • enum (for strings and numbers)
  • items
  • prefixItems
  • minItems
  • maxItems
  • minimum
  • maximum
  • anyOf
  • oneOf (interpreted the same as anyOf )
  • properties
  • additionalProperties
  • required

The non-standard propertyOrdering property may also be set.

Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If $ref is set on a sub-schema, no other properties, except for than those starting as a $ , may be set.

responseJsonSchema value ( Value format)

Optional. An internal detail. Use responseJsonSchema rather than this field.

responseModalities[] enum ( Modality )

Optional. The requested modalities of the response. Represents the set of modalities that the model can return, and should be expected in the response. This is an exact match to the modalities of the response.

A model may have multiple combinations of supported modalities. If the requested modalities do not match any of the supported combinations, an error will be returned.

An empty list is equivalent to requesting only text.

candidateCount integer

Optional. Number of generated responses to return. If unset, this will default to 1. Please note that this doesn't work for previous generation models (Gemini 1.0 family)

maxOutputTokens integer

Optional. The maximum number of tokens to include in a response candidate.

Note: The default value varies by model, see the Model.output_token_limit attribute of the Model returned from the getModel function.

temperature number

Optional. Controls the randomness of the output.

Note: The default value varies by model, see the Model.temperature attribute of the Model returned from the getModel function.

Values can range from [0.0, 2.0].

topP number

Optional. The maximum cumulative probability of tokens to consider when sampling.

The model uses combined Top-k and Top-p (nucleus) sampling.

Tokens are sorted based on their assigned probabilities so that only the most likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while Nucleus sampling limits the number of tokens based on the cumulative probability.

Note: The default value varies by Model and is specified by the Model.top_p attribute returned from the getModel function. An empty topK attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.

topK integer

Optional. The maximum number of tokens to consider when sampling.

Gemini models use Top-p (nucleus) sampling or a combination of Top-k and nucleus sampling. Top-k sampling considers the set of topK most probable tokens. Models running with nucleus sampling don't allow topK setting.

Note: The default value varies by Model and is specified by the Model.top_p attribute returned from the getModel function. An empty topK attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.

seed integer

Optional. Seed used in decoding. If not set, the request uses a randomly generated seed.

presencePenalty number

Optional. Presence penalty applied to the next token's logprobs if the token has already been seen in the response.

This penalty is binary on/off and not dependant on the number of times the token is used (after the first). Use frequencyPenalty for a penalty that increases with each use.

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

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

frequencyPenalty number

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

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

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

responseLogprobs boolean

Optional. If true, export the logprobs results in response.

logprobs integer

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

enableEnhancedCivicAnswers boolean

Optional. Enables enhanced civic answers. It may not be available for all models.

speechConfig object ( SpeechConfig )

Optional. The speech generation config.

thinkingConfig object ( ThinkingConfig )

Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking.

imageConfig object ( ImageConfig )

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

mediaResolution enum ( MediaResolution )

Optional. If specified, the media resolution specified will be used.

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

Modality

Supported modalities of the response.

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

SpeechConfig

The speech generation config.

Fields
voiceConfig object ( VoiceConfig )

The configuration in case of single-voice output.

multiSpeakerVoiceConfig object ( MultiSpeakerVoiceConfig )

Optional. The configuration for the multi-speaker setup. It is mutually exclusive with the voiceConfig field.

languageCode string

Optional. Language code (in BCP 47 format, eg "en-US") for speech synthesis.

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

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

VoiceConfig

The configuration for the voice to use.

Fields
voice_config Union type
The configuration for the speaker to use. voice_config can be only one of the following:
prebuiltVoiceConfig object ( PrebuiltVoiceConfig )

The configuration for the prebuilt voice to use.

JSON representation
{

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

PrebuiltVoiceConfig

The configuration for the prebuilt speaker to use.

Fields
voiceName string

The name of the preset voice to use.

JSON representation
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

The configuration for the multi-speaker setup.

Fields
speakerVoiceConfigs[] object ( SpeakerVoiceConfig )

Required. All the enabled speaker voices.

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

SpeakerVoiceConfig

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

Fields
speaker string

Required. The name of the speaker to use. Should be the same as in the prompt.

voiceConfig object ( VoiceConfig )

Required. The configuration for the voice to use.

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

ThinkingConfig

Config for thinking features.

Fields
includeThoughts boolean

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

thinkingBudget integer

The number of thoughts tokens that the model should generate.

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

ImageConfig

Config for image generation features.

Fields
aspectRatio string

Optional. The aspect ratio of the image to generate. Supported aspect ratios: 1:1, 2:3, 3:2, 3:4, 4:3, 9:16, 16:9, 21:9.

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

JSON representation
{
  "aspectRatio": string
}

MediaResolution

Media resolution for the input media.

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

HarmCategory

The category of a rating.

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

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

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

ModalityTokenCount

Represents token counting info for a single modality.

Fields
modality enum ( Modality )

The modality associated with this token count.

tokenCount integer

Number of tokens.

JSON representation
{
  "modality": enum (Modality),
  "tokenCount": integer
}

Modality

Content Part modality

Enums
MODALITY_UNSPECIFIED Unspecified modality.
TEXT Plain text.
IMAGE Imazh.
VIDEO Video.
AUDIO Audio.
DOCUMENT Document, eg PDF.

SafetyRating

Safety rating for a piece of content.

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

Fields
category enum ( HarmCategory )

Required. The category for this rating.

probability enum ( HarmProbability )

Required. The probability of harm for this content.

blocked boolean

Was this content blocked because of this rating?

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

HarmProbability

The probability that a piece of content is harmful.

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

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

SafetySetting

Safety setting, affecting the safety-blocking behavior.

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

Fields
category enum ( HarmCategory )

Required. The category for this setting.

threshold enum ( HarmBlockThreshold )

Required. Controls the probability threshold at which harm is blocked.

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

HarmBlockThreshold

Block at and beyond a specified harm probability.

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