Generating content

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

Metoda: modele.gjenerojë Përmbajtje

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

Pika përfundimtare

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

Parametrat e rrugës

string model

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

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

Trupi i kërkesës

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

Fushat
contents[] object ( Content )

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

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

tools[] object ( Tool )

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

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

Objekti toolConfig object ( ToolConfig )

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

objekti safetySettings[] object ( SafetySetting )

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

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

Sistemi i objektit systemInstruction object ( Content )

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

generationConfig object ( GenerationConfig )

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

string cachedContent

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

Shembull i kërkesës

Teksti

Python

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)

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

Shkoni

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)

Shell

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

Imazhi

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)

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

Shkoni

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)

Shell

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

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

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-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)

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

Shkoni

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)

Shell

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

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${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=}")

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

Shkoni

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)

Shell

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

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${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=}")

Shkoni

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)

Shell

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${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

Biseda

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)

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

Shkoni

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

Shell

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

Cache

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)

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

Shkoni

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)

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

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

Shkoni

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)

Shell

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)

Shkoni

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

Funksioni Thirrja

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)

Shkoni

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)

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

Shell


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 gjeneratës

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)

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

Shkoni

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)

Shell

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)

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

Shkoni

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

Shell

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-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ëzimi i sistemit

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)

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

Shkoni

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)

Shell

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 reagimit

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

Metoda: modele.streamGenerateContent

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

Pika përfundimtare

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

Parametrat e rrugës

string model

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

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

Trupi i kërkesës

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

Fushat
contents[] object ( Content )

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

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

tools[] object ( Tool )

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

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

Objekti toolConfig object ( ToolConfig )

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

objekti safetySettings[] object ( SafetySetting )

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

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

Sistemi i objektit systemInstruction object ( Content )

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

generationConfig object ( GenerationConfig )

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

string cachedContent

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

Shembull i kërkesës

Teksti

Python

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)

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

Shkoni

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

Shell

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

Imazhi

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)

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

Shkoni

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

Shell

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-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)

Shkoni

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

Shell

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

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${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)

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

Shkoni

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

Shell

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

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${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)

Shkoni

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

Shell

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


echo $MIME_TYPE
tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${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

Biseda

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

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

Shkoni

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

Shell

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 reagimit

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

Generate Content Response

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

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

Fushat
candidates[] object ( Candidate )

Përgjigjet e kandidatëve nga modeli.

object ( PromptFeedback ) promptFeedback (PromptFeedback)

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

usageMetadata object ( UsageMetadata )

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

string modelVersion

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

string responseId

Vetëm dalje. përgjigjeId 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
}

PromptFeedback

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

Fushat
blockReason enum ( BlockReason )

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

Objekt safetyRatings[] object ( SafetyRating )

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

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

BlockReason

Përcakton arsyen pse u bllokua kërkesa.

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

Metadata e përdorimit

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

Fushat
promptTokenCount integer

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

cachedContentTokenCount integer

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

candidatesTokenCount integer

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

toolUsePromptTokenCount integer

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

thoughtsTokenCount integer

Vetëm dalje. Numri i argumenteve të mendimeve për modelet e të menduarit.

totalTokenCount integer

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

objekt promptTokensDetails[] object ( ModalityTokenCount )

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

cacheTokensDetails[] object ( ModalityTokenCount )

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

candidatesTokensDetails[] object ( ModalityTokenCount )

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

object ( ModalityTokenCount ) toolUsePromptTokensDetails[] ( ModalityTokenCount )

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

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

Kandidati

Një kandidat përgjigjeje i krijuar nga modeli.

Fushat
objekti content object ( Content )

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

finishReason enum ( FinishReason )

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

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

Objekt safetyRatings[] object ( SafetyRating )

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

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

citationMetadata object ( CitationMetadata )

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

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

tokenCount integer

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

groundingAttributions[] object ( GroundingAttribution )

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

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

object ( GroundingMetadata ) groundingMetadata ( GroundingMetadata )

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

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

number avgLogprobs

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

logprobsResult object ( LogprobsResult )

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

urlContextMetadata object ( UrlContextMetadata )

Vetëm dalje. Të dhënat meta të lidhura me mjetin e rikthimit të kontekstit url.

index integer

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

Përfaqësimi JSON
{
  "content": {
    object (Content)
  },
  "finishReason": enum (FinishReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ],
  "citationMetadata": {
    object (CitationMetadata)
  },
  "tokenCount": integer,
  "groundingAttributions": [
    {
      object (GroundingAttribution)
    }
  ],
  "groundingMetadata": {
    object (GroundingMetadata)
  },
  "avgLogprobs": number,
  "logprobsResult": {
    object (LogprobsResult)
  },
  "urlContextMetadata": {
    object (UrlContextMetadata)
  },
  "index": integer
}

PërfundoArsyeja

Përcakton arsyen pse modeli ndaloi gjenerimin e argumenteve.

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

Atribuimi i themelimit

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

Fushat
objekti sourceId object ( AttributionSourceId )

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

objekti content object ( Content )

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

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

AttributionSourceId

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

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

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

objekt semanticRetrieverChunk object ( SemanticRetrieverChunk )

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

Përfaqësimi JSON
{

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

GroundingPassageId

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

Fushat
string passageId

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

partIndex integer

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

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

SemanticRetrieverChunk

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

Fushat
source string

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

string chunk

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

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

GroundingMetadata

Metadatat i kthehen klientit kur aktivizohet tokëzimi.

Fushat
object ( GroundingChunk ) groundingChunks[] ( GroundingChunk )

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

objekti groundingSupports[] object ( GroundingSupport )

Lista e mbështetjes së tokëzimit.

string webSearchQueries[]

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

objekt searchEntryPoint object ( SearchEntryPoint )

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

retrievalMetadata object ( RetrievalMetadata )

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

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

SearchEntryPoint

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

Fushat
renderedContent string përmbajtjes

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

vargu sdkBlob string ( bytes format)

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

Një varg i koduar me bazë 64.

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

GroundingChunk

Copë e tokëzimit.

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

Një pjesë e tokëzimit nga uebi.

Përfaqësimi JSON
{

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

Web

Pjesë nga uebi.

Fushat
string uri

Referenca URI e pjesës.

string title

Titulli i pjesës.

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

Mbështetja e Tokës

Mbështetja e tokëzimit.

Fushat
groundingChunkIndices[] integer

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

number confidenceScores[]

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

objekt segment object ( Segment )

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

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

Segmenti

Segmenti i përmbajtjes.

Fushat
partIndex integer

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

startIndex integer

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

endIndex integer

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

string text

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

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

RetrievalMetadata

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

Fushat
number googleSearchDynamicRetrievalScore

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

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

Rezultati i problemeve të ditarit

Rezultati i problemit të ditarit

Fushat
topCandidates[] object ( TopCandidates )

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

chosenCandidates[] object ( Candidate )

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

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

Top Kandidatët

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

Fushat
candidates[] object ( Candidate )

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

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

Kandidati

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

Fushat
string token

Vlera e vargut token të kandidatit.

integer tokenId

Vlera e ID-së së kandidatit.

log number logProbability

Probabiliteti i regjistrit të kandidatit.

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

UrlContextMetadata

Të dhënat meta të lidhura me mjetin e rikthimit të kontekstit url.

Fushat
urlMetadata[] object ( UrlMetadata )

Lista e kontekstit url.

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

UrlMetadata

Konteksti i rikthimit të një url të vetëm.

Fushat
vargu i retrievedUrl string

Url-ja e marrë nga mjeti.

urlRetrievalStatus enum ( UrlRetrievalStatus )

Statusi i marrjes së URL-së.

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

UrlRetrieval Status

Statusi i marrjes së URL-së.

Enums
URL_RETRIEVAL_STATUS_UNSPECIFIED Vlera e paracaktuar. Kjo vlerë është e papërdorur.
URL_RETRIEVAL_STATUS_SUCCESS Rikthimi i URL-së është i suksesshëm.
URL_RETRIEVAL_STATUS_ERROR Rikthimi i URL-së dështoi për shkak të gabimit.
URL_RETRIEVAL_STATUS_PAYWALL Rikthimi i URL-së dështoi sepse përmbajtja është prapa murit të pagesës.
URL_RETRIEVAL_STATUS_UNSAFE Rikthimi i URL-së dështoi sepse përmbajtja është e pasigurt.

Metadatat e Citimit

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

Fushat
citationSources[] object ( CitationSource )

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

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

Burimi i Citimit

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

Fushat
startIndex integer

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

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

endIndex integer

Fakultative. Fundi i segmentit të atribuar, ekskluziv.

string uri

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

string license

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

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

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

GenerationConfig

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

Fushat
string stopSequences[]

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

string responseMimeType

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

responseSchema object ( Schema )

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

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

Vlera responseJsonSchema value ( Value format)

Fakultative. Skema e daljes së përgjigjes së gjeneruar. Kjo është një alternativë ndaj responseSchema që pranon skemën JSON .

Nëse caktohet, responseSchema duhet të hiqet, por responseMimeType kërkohet.

Ndërsa skema e plotë JSON mund të dërgohet, jo të gjitha veçoritë mbështeten. Në mënyrë të veçantë, mbështeten vetëm vetitë e mëposhtme:

  • $id
  • $defs
  • $ref
  • $anchor
  • type
  • format
  • title
  • description
  • enum (për vargjet dhe numrat)
  • items
  • prefixItems
  • minItems
  • maxItems
  • minimum
  • maximum
  • anyOf
  • oneOf (interpretuar njësoj si anyOf )
  • properties
  • additionalProperties
  • required

Mund të vendoset gjithashtu edhe vetia jo standarde propertyOrdering .

Referencat ciklike janë shpalosur në një shkallë të kufizuar dhe, si të tilla, mund të përdoren vetëm brenda veçorive jo të kërkuara. (Vetitë e pavlefshme nuk janë të mjaftueshme.) Nëse $ref vendoset në një nën-skema, nuk mund të vendosen veçori të tjera, përveç atyre që fillojnë si $ .

responseModalities[] enum ( Modality )

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

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

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

candidateCount integer

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

maxOutputTokens integer

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

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

number temperature

Fakultative. Kontrollon rastësinë e daljes.

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

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

number topP

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

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

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

Shënim: Vlera e paracaktuar ndryshon sipas Model dhe specifikohet nga atributi Model.top_p i kthyer nga funksioni getModel . Një atribut bosh topK tregon që modeli nuk aplikon marrjen e mostrave të Top-K dhe nuk lejon vendosjen e topK në kërkesat.

integer topK

Fakultative. Numri maksimal i shenjave që duhet të merren parasysh gjatë marrjes së mostrave.

Modelet e Binjakëve përdorin marrjen e mostrave TOP-P (Bërthama) ose një kombinim të marrjes së mostrave të Top-K dhe Bërthamave. Kampionimi i Top-K konsideron grupin e shenjave më të mundshme topK . Modelet që funksionojnë me marrjen e mostrave të bërthamës nuk lejojnë vendosjen e Topk.

Shënim: Vlera e paracaktuar ndryshon sipas Model dhe specifikohet nga atributi Model.top_p i kthyer nga funksioni getModel . Një atribut bosh topK tregon që modeli nuk aplikon marrjen e mostrave të Top-K dhe nuk lejon vendosjen e topK në kërkesat.

integer seed

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

number presencePenalty

Fakultative. Dënimi i pranisë zbatohet në logProbs e Token -it tjetër nëse shenja tashmë është parë në përgjigje.

Ky dënim është binar/fikur dhe nuk varet nga numri i herë që përdoret shenja (pas së parës). Përdorni frequencyPenalty për një dënim që rritet me secilën përdorim.

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

Një dënim negativ do të inkurajojë përdorimin e shenjave që janë përdorur tashmë në përgjigje, duke zvogëluar fjalorin.

number frequencyPenalty

Fakultative. Dënimi i frekuencës i aplikuar në logProbs e Token -it tjetër, shumëzuar me numrin e herë që çdo shenjë është parë në përgjigje deri më tani.

Një dënim pozitiv do të dekurajojë përdorimin e shenjave që janë përdorur tashmë, proporcionale me numrin e herë që është përdorur shenja: sa më shumë të përdoret një shenjë, aq më e vështirë është që modeli të përdorë atë shenjë përsëri duke rritur fjalorin e përgjigjeve.

KUJDES: Një dënim negativ do të inkurajojë modelin të ripërdorë shenjat proporcionale me numrin e herë që është përdorur shenja. Vlerat e vogla negative do të zvogëlojnë fjalorin e një përgjigje. Vlerat më të mëdha negative do të bëjnë që modeli të fillojë të përsërisë një shenjë të zakonshme derisa të godasë kufirin e maxOutputTokens .

responseLogprobs boolean

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

logprobs integer

Fakultative. Vetëm e vlefshme nëse responseLogprobs=True . Kjo vendos numrin e logprobs më të mirë për t'u kthyer në çdo hap deshifrimi në Candidate.logprobs_result .

enableEnhancedCivicAnswers boolean

Fakultative. Mundëson përgjigje të zgjeruara qytetare. Mund të mos jetë në dispozicion për të gjitha modelet.

object ( SpeechConfig ) speechConfig (FjalimiConfig)

Fakultative. Konfigurimi i gjenerimit të fjalës.

Objekti thinkingConfig object ( ThinkingConfig )

Fakultative. Konfiguroni për tiparet e të menduarit. Do të kthehet një gabim nëse kjo fushë është vendosur për modele që nuk e mbështesin të menduarit.

mediaResolution enum ( MediaResolution )

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

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

Modalitet

Modalitetet e mbështetura të përgjigjes.

Gypi
MODALITY_UNSPECIFIED Vlera e paracaktuar.
TEXT Tregon se modeli duhet të kthejë tekstin.
IMAGE Tregon se modeli duhet të kthejë imazhet.
AUDIO Tregon se modeli duhet të kthejë audio.

Fjala e konfigurimit

Konfigurimi i gjenerimit të fjalës.

Fusha
Objekti voiceConfig object ( VoiceConfig )

Konfigurimin në rast të daljes me një zër.

objekt multiSpeakerVoiceConfig object ( MultiSpeakerVoiceConfig )

Fakultative. Konfigurimi për konfigurimin me shumë folës. Isshtë reciprokisht ekskluzive me fushën VoiceConfig.

string languageCode

Fakultative. Kodi gjuhësor (në formatin BCP 47, p.sh. "en-us") për sintezën e të folurit.

Vlerat e vlefshme janë: de-de, en-au, en-gb, en-in, en-us, es-u, 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, te-in, te-in, NL-NL, KO-KR, CMN-CN, PL-PL, RU-RU dhe TH-TH.

Përfaqësimi JSON
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}

Zëri i zërit

Konfigurimin për të përdorur zërin.

Fusha
Union type voice_config
Konfigurimin që altoparlanti të përdorë. voice_config mund të jetë vetëm një nga sa vijon:
prebuiltVoiceConfig object ( PrebuiltVoiceConfig )

Konfigurimin për të përdorur zërin e paracaktuar.

Përfaqësimi JSON
{

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

Prebuiltvoiceconfig

Konfigurimi për përdorimin e altoparlantit të paracaktuar.

Fusha
voiceName string

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

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

Multispeakervoiceconfig

Konfigurimi për konfigurimin me shumë folës.

Fusha
object ( SpeakerVoiceConfig ) speakerVoiceConfigs[]

Kërkohet. Të gjithë zërat e altoparlantëve të aktivizuar.

Përfaqësimi JSON
{
  "speakerVoiceConfigs": [
    {
      object (SpeakerVoiceConfig)
    }
  ]
}

Foleservoiceconfig

Konfigurimi për një altoparlant të vetëm në një konfigurim të shumë altoparlantëve.

Fusha
string speaker

Kërkohet. Emri i altoparlantit për të përdorur. Duhet të jetë e njëjtë me atë të shpejtë.

Objekti voiceConfig object ( VoiceConfig )

Kërkohet. Konfigurimin për të përdorur zërin.

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

MendimiConfig

Konfiguroni për tiparet e të menduarit.

Fusha
includeThoughts boolean

Tregon nëse do të përfshijë mendime në përgjigje. Nëse është e vërtetë, mendimet kthehen vetëm kur janë në dispozicion.

integer thinkingBudget

Numri i shenjave të mendimeve që modeli duhet të gjenerojë.

Përfaqësimi JSON
{
  "includeThoughts": boolean,
  "thinkingBudget": integer
}

Mesatare

Rezolucioni i mediave për mediat hyrëse.

Gypi
MEDIA_RESOLUTION_UNSPECIFIED Rezolucioni i mediave nuk është caktuar.
MEDIA_RESOLUTION_LOW Rezolucioni i mediave i vendosur në të ulët (64 shenja).
MEDIA_RESOLUTION_MEDIUM Rezolucioni i mediave i vendosur në medium (256 shenja).
MEDIA_RESOLUTION_HIGH Rezolucioni i mediave i vendosur në të lartë (rifreskim i zmadhuar me 256 shenja).

Kategori

Kategoria e një vlerësimi.

Këto kategori mbulojnë lloje të ndryshme të dëmeve që zhvilluesit mund të dëshirojnë të rregullojnë.

Gypi
HARM_CATEGORY_UNSPECIFIED Kategoria është e paspecifikuar.
HARM_CATEGORY_DEROGATORY PALM - Komente negative ose të dëmshme që synojnë identitetin dhe/ose atributin e mbrojtur.
HARM_CATEGORY_TOXICITY Palm - Përmbajtja që është e pasjellshme, mosrespektuese ose e përlotur.
HARM_CATEGORY_VIOLENCE Palm - përshkruan skenarët që përshkruajnë dhunën ndaj një individi ose grupi, ose përshkrimet e përgjithshme të Gore.
HARM_CATEGORY_SEXUAL Palma - Përmban referenca për aktet seksuale ose përmbajtjen tjetër të dobët.
HARM_CATEGORY_MEDICAL Palm - Promovon këshilla mjekësore të pakontrolluara.
HARM_CATEGORY_DANGEROUS Palm - përmbajtje e rrezikshme që promovon, lehtëson ose inkurajon veprime të dëmshme.
HARM_CATEGORY_HARASSMENT Binjakët - Përmbajtja e ngacmimit.
HARM_CATEGORY_HATE_SPEECH Binjakët - Fjala e urrejtjes dhe përmbajtja.
HARM_CATEGORY_SEXUALLY_EXPLICIT Binjakët - Përmbajtja e qartë seksuale.
HARM_CATEGORY_DANGEROUS_CONTENT Binjakët - përmbajtje e rrezikshme.
HARM_CATEGORY_CIVIC_INTEGRITY

Binjakët - Përmbajtja që mund të përdoret për të dëmtuar integritetin qytetar. Zhvlerësuar: Përdorni EnableNHancedCivicansWers në vend.

Modaliteti

Përfaqëson informacione për llogaritjen e shenjave për një modalitet të vetëm.

Fusha
modality enum ( Modality )

Modaliteti i lidhur me këtë numër të shenjave.

integer tokenCount

Numri i shenjave.

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

Modalitet

Modaliteti i pjesës së përmbajtjes

Gypi
MODALITY_UNSPECIFIED Modaliteti i paspecifikuar.
TEXT Tekst i thjeshtë.
IMAGE Imazh.
VIDEO Video
AUDIO Audio
DOCUMENT Dokument, p.sh. PDF.

Rafetirues

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

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

Fusha
category enum ( HarmCategory )

Kërkohet. Kategoria për këtë vlerësim.

Enum i probability enum ( HarmProbability )

Kërkohet. Probabiliteti i dëmtimit për këtë përmbajtje.

blocked boolean

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

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

Person i dëmshëm

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

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

Gypi
HARM_PROBABILITY_UNSPECIFIED Probabiliteti është i paspecifikuar.
NEGLIGIBLE Përmbajtja ka një shans të papërfillshëm për të qenë i pasigurt.
LOW Përmbajtja ka një shans të ulët për të qenë i pasigurt.
MEDIUM Përmbajtja ka një shans të mesëm për të qenë i pasigurt.
HIGH Përmbajtja ka një shans të lartë për të qenë i pasigurt.

Mbrojtje

Vendosja e sigurisë, duke ndikuar në sjelljen e bllokimit të sigurisë.

Kalimi i një cilësie sigurie për një kategori ndryshon probabilitetin e lejuar që përmbajtja të bllokohet.

Fusha
category enum ( HarmCategory )

Kërkohet. Kategoria për këtë cilësim.

threshold enum ( HarmBlockThreshold )

Kërkohet. Kontrollon pragun e probabilitetit në të cilin bllokohet dëmi.

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

I dëmtuar

Bllokoni në dhe përtej një probabiliteti të caktuar të dëmit.

Gypi
HARM_BLOCK_THRESHOLD_UNSPECIFIED Pragu është i paspecifikuar.
BLOCK_LOW_AND_ABOVE Përmbajtja me të papërfillshme do të lejohet.
BLOCK_MEDIUM_AND_ABOVE Përmbajtja me të papërfillshme dhe të ulët do të lejohet.
BLOCK_ONLY_HIGH Përmbajtja me të papërfillshme, të ulët dhe të mesme do të lejohet.
BLOCK_NONE E gjithë përmbajtja do të lejohet.
OFF Fikni filtrin e sigurisë.