Generating content

Die Gemini API unterstützt die Generierung von Inhalten mit Bildern, Audio, Code, Tools und mehr. Weitere Informationen zu den einzelnen Funktionen finden Sie unten und im aufgabenorientierten Beispielcode oder in den umfassenden Anleitungen.

Methode: models.generateContent

Generiert eine Modellantwort auf Grundlage einer Eingabe GenerateContentRequest. Ausführliche Informationen zur Verwendung finden Sie im Leitfaden zur Texterstellung. Die Eingabefunktionen unterscheiden sich je nach Modell, auch bei optimierten Modellen. Weitere Informationen finden Sie im Modellleitfaden und im Leitfaden zum Optimieren.

Endpunkt

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

Pfadparameter

model string

Erforderlich. Der Name des Model, der zum Generieren der Vervollständigung verwendet werden soll.

Format: models/{model}. Sie hat die Form models/{model}.

Anfragetext

Der Anfragetext enthält Daten mit folgender Struktur:

Felder
contents[] object (Content)

Erforderlich. Der Inhalt der aktuellen Unterhaltung mit dem Modell.

Bei Einzelabfragen ist dies eine einzelne Instanz. Bei Mehrfachabfragen wie chat ist dies ein wiederkehrendes Feld, das den Unterhaltungsverlauf und die letzte Anfrage enthält.

tools[] object (Tool)

Optional. Eine Liste mit Tools, die Model verwenden kann, um die nächste Antwort zu generieren.

Eine Tool ist ein Code, der es dem System ermöglicht, mit externen Systemen zu interagieren, um eine Aktion oder eine Reihe von Aktionen außerhalb des Wissens und Umfangs der Model auszuführen. Unterstützte Tools sind Function und codeExecution. Weitere Informationen finden Sie in den Anleitungen zu Funktionsaufrufen und Codeausführung.

toolConfig object (ToolConfig)

Optional. Tool-Konfiguration für alle in der Anfrage angegebenen Tool. Ein Anwendungsbeispiel finden Sie im Leitfaden zu Funktionsaufrufen.

safetySettings[] object (SafetySetting)

Optional. Eine Liste mit eindeutigen SafetySetting-Instanzen zum Blockieren unsicherer Inhalte.

Dies wird auf der GenerateContentRequest.contents und der GenerateContentResponse.candidates erzwungen. Es sollte nicht mehr als eine Einstellung für jeden SafetyCategory-Typ geben. Die API blockiert alle Inhalte und Antworten, die die durch diese Einstellungen festgelegten Grenzwerte nicht erreichen. Diese Liste überschreibt die Standardeinstellungen für jede SafetyCategory, die in „safetySettings“ angegeben ist. Wenn für ein bestimmtes SafetyCategory in der Liste kein SafetySetting angegeben ist, verwendet die API die standardmäßige Sicherheitseinstellung für diese Kategorie. Die Kategorien schädlicher Inhalte HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT und HARM_CATEGORY_CIVIC_INTEGRITY werden unterstützt. Hier finden Sie eine Anleitung mit detaillierten Informationen zu den verfügbaren Sicherheitseinstellungen. Sicherheitshinweise

systemInstruction object (Content)

Optional. Der Entwickler hat Systemanweisungen festgelegt. Derzeit nur Text.

generationConfig object (GenerationConfig)

Optional. Konfigurationsoptionen für die Modellgenerierung und ‑ausgabe.

cachedContent string

Optional. Der Name des zwischengespeicherten Inhalts, der als Kontext für die Bereitstellung der Vorhersage verwendet werden soll. Format: cachedContents/{cachedContent}

Beispielanfrage

Text

Python

from google import genai

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

Node.js

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

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

Ok

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)

Muschel

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

Bild

Python

from google import genai
import PIL.Image

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

Node.js

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

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

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

Ok

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)

Muschel

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

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

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

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

Java

Client client = new Client();

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

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

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

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

Audio

Python

from google import genai

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

Node.js

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

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

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

Ok

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)

Muschel

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

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

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

Video

Python

from google import genai
import time

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

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

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

Node.js

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

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

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

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

Ok

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)

Muschel

# 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=}")

Ok

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)

Muschel

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

Chat

Python

from google import genai
from google.genai import types

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

Node.js

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

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

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

Ok

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

Muschel

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)

Node.js

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

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

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

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

Ok

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)

Abgestimmtes Modell

Python

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

JSON-Modus

Python

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

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

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

Node.js

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

Ok

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)

Muschel

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

Codeausführung

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)

Ok

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

Funktionsaufrufe

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)

Ok

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

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

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

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

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

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

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

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

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

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

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

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

printResponse(finalResponse)

Node.js

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Muschel


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

Generierungskonfiguration

Python

from google import genai
from google.genai import types

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

Node.js

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

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

console.log(response.text);

Ok

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)

Muschel

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

Sicherheitseinstellungen

Python

from google import genai
from google.genai import types

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

print(response.candidates[0].safety_ratings)

Node.js

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

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

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

Ok

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

Muschel

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

Systemanweisung

Python

from google import genai
from google.genai import types

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

Node.js

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

Ok

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)

Muschel

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

Antworttext

Wenn der Vorgang erfolgreich abgeschlossen wurde, enthält der Antworttext eine Instanz von GenerateContentResponse.

Methode: models.streamGenerateContent

Generiert eine gestreamte Antwort vom Modell für eine Eingabe GenerateContentRequest.

Endpunkt

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

Pfadparameter

model string

Erforderlich. Der Name des Model, der zum Generieren der Vervollständigung verwendet werden soll.

Format: models/{model}. Sie hat die Form models/{model}.

Anfragetext

Der Anfragetext enthält Daten mit folgender Struktur:

Felder
contents[] object (Content)

Erforderlich. Der Inhalt der aktuellen Unterhaltung mit dem Modell.

Bei Einzelabfragen ist dies eine einzelne Instanz. Bei Mehrfachabfragen wie chat ist dies ein wiederkehrendes Feld, das den Unterhaltungsverlauf und die letzte Anfrage enthält.

tools[] object (Tool)

Optional. Eine Liste mit Tools, die Model verwenden kann, um die nächste Antwort zu generieren.

Eine Tool ist ein Code, der es dem System ermöglicht, mit externen Systemen zu interagieren, um eine Aktion oder eine Reihe von Aktionen außerhalb des Wissens und Umfangs der Model auszuführen. Unterstützte Tools sind Function und codeExecution. Weitere Informationen finden Sie in den Anleitungen zu Funktionsaufrufen und Codeausführung.

toolConfig object (ToolConfig)

Optional. Tool-Konfiguration für alle in der Anfrage angegebenen Tool. Ein Anwendungsbeispiel finden Sie im Leitfaden zu Funktionsaufrufen.

safetySettings[] object (SafetySetting)

Optional. Eine Liste mit eindeutigen SafetySetting-Instanzen zum Blockieren unsicherer Inhalte.

Dies wird auf der GenerateContentRequest.contents und der GenerateContentResponse.candidates erzwungen. Es sollte nicht mehr als eine Einstellung für jeden SafetyCategory-Typ geben. Die API blockiert alle Inhalte und Antworten, die die durch diese Einstellungen festgelegten Grenzwerte nicht erreichen. Diese Liste überschreibt die Standardeinstellungen für jede SafetyCategory, die in „safetySettings“ angegeben ist. Wenn für ein bestimmtes SafetyCategory in der Liste kein SafetySetting angegeben ist, verwendet die API die standardmäßige Sicherheitseinstellung für diese Kategorie. Die Kategorien schädlicher Inhalte HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT und HARM_CATEGORY_CIVIC_INTEGRITY werden unterstützt. Hier finden Sie eine Anleitung mit detaillierten Informationen zu den verfügbaren Sicherheitseinstellungen. Sicherheitshinweise

systemInstruction object (Content)

Optional. Der Entwickler hat Systemanweisungen festgelegt. Derzeit nur Text.

generationConfig object (GenerationConfig)

Optional. Konfigurationsoptionen für die Modellgenerierung und ‑ausgabe.

cachedContent string

Optional. Der Name des zwischengespeicherten Inhalts, der als Kontext für die Bereitstellung der Vorhersage verwendet werden soll. Format: cachedContents/{cachedContent}

Beispielanfrage

Text

Python

from google import genai

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

Node.js

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

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

Ok

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

Muschel

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

Bild

Python

from google import genai
import PIL.Image

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

Node.js

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

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

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

Ok

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

Muschel

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)

Ok

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

Muschel

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

tmp_header_file=upload-header.tmp

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

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

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

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

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

cat response.json
echo

Video

Python

from google import genai
import time

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

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

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

Node.js

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

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

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

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

Ok

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

Muschel

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

Ok

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

Muschel

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

Chat

Python

from google import genai
from google.genai import types

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

print(chat.get_history())

Node.js

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

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

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

console.log(chat.getHistory());

Ok

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

Muschel

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"

Antworttext

Bei Erfolg enthält der Antworttext einen Stream von GenerateContentResponse-Instanzen.

GenerateContentResponse

Antwort des Modells, die mehrere Kandidatenantworten unterstützt.

Sicherheitsbewertungen und Inhaltsfilter werden sowohl für den Prompt in GenerateContentResponse.prompt_feedback als auch für jeden Kandidaten in finishReason und in safetyRatings gemeldet. Die API: – Gibt entweder alle angeforderten Kandidaten oder keinen zurück. – Gibt nur dann keine Kandidaten zurück, wenn mit dem Prompt etwas nicht stimmt (siehe promptFeedback). – Meldet Feedback zu jedem Kandidaten in finishReason und safetyRatings.

Felder
candidates[] object (Candidate)

Kandidatenantworten des Modells.

promptFeedback object (PromptFeedback)

Gibt das Feedback des Prompts zu den Inhaltsfiltern zurück.

usageMetadata object (UsageMetadata)

Nur Ausgabe. Metadaten zur Tokennutzung der Generierungsanfragen.

modelVersion string

Nur Ausgabe. Die Modellversion, die zum Generieren der Antwort verwendet wurde.

responseId string

Nur Ausgabe. responseId wird verwendet, um jede Antwort zu identifizieren.

JSON-Darstellung
{
  "candidates": [
    {
      object (Candidate)
    }
  ],
  "promptFeedback": {
    object (PromptFeedback)
  },
  "usageMetadata": {
    object (UsageMetadata)
  },
  "modelVersion": string,
  "responseId": string
}

PromptFeedback

Eine Reihe von Feedback-Metadaten, die im Prompt in GenerateContentRequest.content angegeben wurden.

Felder
blockReason enum (BlockReason)

Optional. Wenn festgelegt, wurde der Prompt blockiert und es werden keine Kandidaten zurückgegeben. Formulieren Sie den Prompt um.

safetyRatings[] object (SafetyRating)

Bewertungen zur Sicherheit des Prompts. Pro Kategorie gibt es maximal eine Bewertung.

JSON-Darstellung
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

BlockReason

Gibt den Grund an, warum der Prompt blockiert wurde.

Enums
BLOCK_REASON_UNSPECIFIED Standardwert Dieser Wert wird nicht verwendet.
SAFETY Der Prompt wurde aus Sicherheitsgründen blockiert. Sehen Sie sich safetyRatings an, um herauszufinden, durch welche Sicherheitskategorie die Blockierung erfolgt ist.
OTHER Der Prompt wurde aus unbekannten Gründen blockiert.
BLOCKLIST Der Prompt wurde aufgrund der Begriffe blockiert, die in der Sperrliste für Begriffe enthalten sind.
PROHIBITED_CONTENT Der Prompt wurde aufgrund unzulässiger Inhalte blockiert.
IMAGE_SAFETY Kandidaten, die aufgrund unsicherer Inhalte für die Bildgenerierung blockiert wurden.

UsageMetadata

Metadaten zur Tokennutzung der Generierungsanfrage.

Felder
promptTokenCount integer

Anzahl der Tokens im Prompt. Wenn cachedContent festgelegt ist, ist dies weiterhin die effektive Gesamtgröße des Prompts, d. h., sie umfasst die Anzahl der Tokens im Cache-Inhalt.

cachedContentTokenCount integer

Anzahl der Tokens im im Cache gespeicherten Teil des Prompts (im Cache gespeicherte Inhalte)

candidatesTokenCount integer

Gesamtzahl der Tokens für alle generierten Antwortkandidaten.

toolUsePromptTokenCount integer

Nur Ausgabe. Anzahl der Tokens in den Tool-Nutzungs-Prompts.

thoughtsTokenCount integer

Nur Ausgabe. Anzahl der Tokens für Überlegungen für Denkmodelle.

totalTokenCount integer

Gesamtzahl der Tokens für die Generierungsanfrage (Prompt + Antwortkandidaten).

promptTokensDetails[] object (ModalityTokenCount)

Nur Ausgabe. Liste der Modalitäten, die in der Anfrageeingabe verarbeitet wurden.

cacheTokensDetails[] object (ModalityTokenCount)

Nur Ausgabe. Liste der Modalitäten der im Cache gespeicherten Inhalte in der Anfrageeingabe.

candidatesTokensDetails[] object (ModalityTokenCount)

Nur Ausgabe. Liste der Modalitäten, die in der Antwort zurückgegeben wurden.

toolUsePromptTokensDetails[] object (ModalityTokenCount)

Nur Ausgabe. Liste der Modalitäten, die für Eingaben von Tool-Use-Anfragen verarbeitet wurden.

JSON-Darstellung
{
  "promptTokenCount": integer,
  "cachedContentTokenCount": integer,
  "candidatesTokenCount": integer,
  "toolUsePromptTokenCount": integer,
  "thoughtsTokenCount": integer,
  "totalTokenCount": integer,
  "promptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "cacheTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "candidatesTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ],
  "toolUsePromptTokensDetails": [
    {
      object (ModalityTokenCount)
    }
  ]
}

Kandidat

Ein vom Modell generierter Antwortkandidat.

Felder
content object (Content)

Nur Ausgabe. Vom Modell zurückgegebene generierte Inhalte.

finishReason enum (FinishReason)

Optional. Nur Ausgabe. Der Grund, warum das Modell keine Tokens mehr generiert.

Wenn leer, wird das Modell weiterhin die Tokens generieren.

safetyRatings[] object (SafetyRating)

Liste der Bewertungen für die Sicherheit eines Antwortkandidaten.

Pro Kategorie gibt es maximal eine Bewertung.

citationMetadata object (CitationMetadata)

Nur Ausgabe. Zitierinformationen für vom Modell generierte Kandidaten.

Dieses Feld kann Rezitationsinformationen für jeden Text enthalten, der in content enthalten ist. Das sind Passagen, die aus urheberrechtlich geschütztem Material in den Trainingsdaten des zugrunde liegenden LLM „rezitiert“ werden.

tokenCount integer

Nur Ausgabe. Anzahl der Tokens für diesen Kandidaten.

groundingAttributions[] object (GroundingAttribution)

Nur Ausgabe. Angaben zur Quellenangabe für Quellen, die zu einer fundierten Antwort beigetragen haben.

Dieses Feld wird für GenerateAnswer-Aufrufe ausgefüllt.

groundingMetadata object (GroundingMetadata)

Nur Ausgabe. Grounding-Metadaten für den Kandidaten.

Dieses Feld wird für GenerateContent-Aufrufe ausgefüllt.

avgLogprobs number

Nur Ausgabe. Durchschnittlicher Log-Wahrscheinlichkeitswert des Kandidaten.

logprobsResult object (LogprobsResult)

Nur Ausgabe. Log-Likelihood-Werte für die Antwort-Tokens und Top-Tokens

urlContextMetadata object (UrlContextMetadata)

Nur Ausgabe. Metadaten im Zusammenhang mit dem Tool zum Abrufen des URL-Kontexts.

index integer

Nur Ausgabe. Index des Kandidaten in der Liste der Antwortkandidaten.

JSON-Darstellung
{
  "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
}

FinishReason

Gibt den Grund an, warum das Modell keine Tokens mehr generiert.

Enums
FINISH_REASON_UNSPECIFIED Standardwert Dieser Wert wird nicht verwendet.
STOP Natürlicher Stopppunkt des Modells oder angegebene Stoppsequenz.
MAX_TOKENS Die in der Anfrage angegebene maximale Anzahl von Tokens wurde erreicht.
SAFETY Der Inhalt des Antwortkandidaten wurde aus Sicherheitsgründen gemeldet.
RECITATION Der Inhalt des Antwortvorschlags wurde aus Rezitationsgründen gemeldet.
LANGUAGE Der Inhalt des Antwortvorschlags wurde als nicht unterstützte Sprache gekennzeichnet.
OTHER Unbekannter Grund.
BLOCKLIST Die Tokengenerierung wurde gestoppt, weil die Inhalte verbotene Begriffe enthalten.
PROHIBITED_CONTENT Die Tokengenerierung wurde gestoppt, weil sie möglicherweise verbotene Inhalte enthält.
SPII Die Tokengenerierung wurde gestoppt, da die Inhalte möglicherweise vertrauliche personenidentifizierbare Informationen enthalten.
MALFORMED_FUNCTION_CALL Der vom Modell generierte Funktionsaufruf ist ungültig.
IMAGE_SAFETY Die Tokengenerierung wurde gestoppt, da die generierten Bilder gegen die Sicherheitsrichtlinien verstoßen.
UNEXPECTED_TOOL_CALL Das Modell hat einen Tool-Aufruf generiert, aber in der Anfrage waren keine Tools aktiviert.
TOO_MANY_TOOL_CALLS Das Modell hat zu viele Tools nacheinander aufgerufen. Die Ausführung wurde daher beendet.

GroundingAttribution

Quellenangabe für eine Quelle, die zu einer Antwort beigetragen hat.

Felder
sourceId object (AttributionSourceId)

Nur Ausgabe. Kennung für die Quelle, die zu dieser Zuordnung beiträgt.

content object (Content)

Quellinhalte, die dieser Quellenangabe zugrunde liegen.

JSON-Darstellung
{
  "sourceId": {
    object (AttributionSourceId)
  },
  "content": {
    object (Content)
  }
}

AttributionSourceId

Kennung für die Quelle, die zu dieser Zuordnung beiträgt.

Felder
source Union type
Für source ist nur einer der folgenden Werte zulässig:
groundingPassage object (GroundingPassageId)

Kennung für einen Inline-Abschnitt.

semanticRetrieverChunk object (SemanticRetrieverChunk)

Kennung für ein Chunk, das über Semantic Retriever abgerufen wurde.

JSON-Darstellung
{

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

GroundingPassageId

Kennung für einen Teil innerhalb eines GroundingPassage.

Felder
passageId string

Nur Ausgabe. ID des Abschnitts, der der GroundingPassage.id des GenerateAnswerRequest entspricht.

partIndex integer

Nur Ausgabe. Index des Teils im GroundingPassage.content von GenerateAnswerRequest.

JSON-Darstellung
{
  "passageId": string,
  "partIndex": integer
}

SemanticRetrieverChunk

Kennung für ein Chunk, das über Semantic Retriever abgerufen und in GenerateAnswerRequest mit SemanticRetrieverConfig angegeben wurde.

Felder
source string

Nur Ausgabe. Name der Quelle, die dem SemanticRetrieverConfig.source der Anfrage entspricht. Beispiel: corpora/123 oder corpora/123/documents/abc

chunk string

Nur Ausgabe. Name des Chunk, der den zugeordneten Text enthält. Beispiel: corpora/123/documents/abc/chunks/xyz

JSON-Darstellung
{
  "source": string,
  "chunk": string
}

GroundingMetadata

Metadaten, die an den Client zurückgegeben werden, wenn Grounding aktiviert ist.

Felder
groundingChunks[] object (GroundingChunk)

Liste der unterstützenden Referenzen, die aus der angegebenen Fundierungsquelle abgerufen wurden.

groundingSupports[] object (GroundingSupport)

Liste der unterstützten Fundierungen.

webSearchQueries[] string

Websuchanfragen für die anschließende Websuche.

searchEntryPoint object (SearchEntryPoint)

Optional. Google-Sucheintrag für die nachfolgenden Websuchen.

retrievalMetadata object (RetrievalMetadata)

Metadaten im Zusammenhang mit dem Abrufen im Grounding-Ablauf.

JSON-Darstellung
{
  "groundingChunks": [
    {
      object (GroundingChunk)
    }
  ],
  "groundingSupports": [
    {
      object (GroundingSupport)
    }
  ],
  "webSearchQueries": [
    string
  ],
  "searchEntryPoint": {
    object (SearchEntryPoint)
  },
  "retrievalMetadata": {
    object (RetrievalMetadata)
  }
}

SearchEntryPoint

Einstiegspunkt für die Google Suche.

Felder
renderedContent string

Optional. Webinhalts-Snippet, das in eine Webseite oder eine App-Webview eingebettet werden kann.

sdkBlob string (bytes format)

Optional. Base64-codiertes JSON, das ein Array von Tupeln aus <Suchbegriff, Such-URL> darstellt.

Ein base64-codierter String.

JSON-Darstellung
{
  "renderedContent": string,
  "sdkBlob": string
}

GroundingChunk

Fundierungs-Chunk.

Felder
chunk_type Union type
Chunk-Typ. Für chunk_type ist nur einer der folgenden Werte zulässig:
web object (Web)

Fundierungs-Chunk aus dem Web.

JSON-Darstellung
{

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

Web

Chunk aus dem Web.

Felder
uri string

URI-Referenz des Chunks.

title string

Titel des Chunks.

JSON-Darstellung
{
  "uri": string,
  "title": string
}

GroundingSupport

Unterstützung für die Fundierung

Felder
groundingChunkIndices[] integer

Eine Liste von Indexen (in „grounding_chunk“), die die mit dem Anspruch verknüpften Zitationen angeben. [1,3,4] bedeutet beispielsweise, dass grounding_chunk[1], grounding_chunk[3] und grounding_chunk[4] die abgerufenen Inhalte sind, die der Behauptung zugeordnet werden.

confidenceScores[] number

Konfidenzwert der Supportreferenzen. Liegt im Bereich von 0 bis 1. 1 ist die höchste Zuversicht. Diese Liste muss dieselbe Größe wie die groundingChunkIndices haben.

segment object (Segment)

Segment des Inhalts, zu dem dieser Support gehört.

JSON-Darstellung
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

Segment

Segment des Inhalts.

Felder
partIndex integer

Nur Ausgabe. Der Index eines Part-Objekts innerhalb des übergeordneten Content-Objekts.

startIndex integer

Nur Ausgabe. Startindex im angegebenen Teil, gemessen in Byte. Offset vom Beginn des Teils, einschließlich, beginnend mit null.

endIndex integer

Nur Ausgabe. Endindex im angegebenen Teil, gemessen in Byte. Offset vom Beginn des Teils, exklusiv, beginnend bei null.

text string

Nur Ausgabe. Der Text, der dem Segment aus der Antwort entspricht.

JSON-Darstellung
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

RetrievalMetadata

Metadaten im Zusammenhang mit dem Abrufen im Grounding-Ablauf.

Felder
googleSearchDynamicRetrievalScore number

Optional. Wert, der angibt, wie wahrscheinlich es ist, dass Informationen aus der Google Suche helfen können, den Prompt zu beantworten. Der Wert liegt im Bereich [0, 1], wobei 0 die geringste und 1 die höchste Wahrscheinlichkeit darstellt. Dieser Wert wird nur ausgegeben, wenn die Fundierung mit der Google Suche und die dynamische Abfrage aktiviert sind. Er wird mit dem Schwellenwert verglichen, um zu entscheiden, ob die Google Suche ausgelöst werden soll.

JSON-Darstellung
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

Logprobs-Ergebnis

Felder
topCandidates[] object (TopCandidates)

Länge = Gesamtzahl der Decodierungsschritte.

chosenCandidates[] object (Candidate)

Länge = Gesamtzahl der Decodierungsschritte. Die ausgewählten Kandidaten sind möglicherweise in „topCandidates“ enthalten.

JSON-Darstellung
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ]
}

TopCandidates

Kandidaten mit den höchsten Log-Wahrscheinlichkeiten bei jedem Decodierungsschritt.

Felder
candidates[] object (Candidate)

Absteigend nach Log-Wahrscheinlichkeit sortiert.

JSON-Darstellung
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

Kandidat

Kandidat für das Logprobs-Token und den Logprobs-Score.

Felder
token string

Der Token-Stringwert des Kandidaten.

tokenId integer

Der Token-ID-Wert des Kandidaten.

logProbability number

Die Logwahrscheinlichkeit des Kandidaten.

JSON-Darstellung
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

UrlContextMetadata

Metadaten im Zusammenhang mit dem Tool zum Abrufen des URL-Kontexts.

Felder
urlMetadata[] object (UrlMetadata)

Liste des URL-Kontexts.

JSON-Darstellung
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}

UrlMetadata

Kontext des Abrufs einer einzelnen URL.

Felder
retrievedUrl string

Vom Tool abgerufene URL.

urlRetrievalStatus enum (UrlRetrievalStatus)

Status des URL-Abrufs.

JSON-Darstellung
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}

UrlRetrievalStatus

Status des URL-Abrufs.

Enums
URL_RETRIEVAL_STATUS_UNSPECIFIED Standardwert Dieser Wert wird nicht verwendet.
URL_RETRIEVAL_STATUS_SUCCESS Der Abruf der URL war erfolgreich.
URL_RETRIEVAL_STATUS_ERROR Das Abrufen der URL ist aufgrund eines Fehlers fehlgeschlagen.
URL_RETRIEVAL_STATUS_PAYWALL Der Abruf der URL ist fehlgeschlagen, da sich der Inhalt hinter einer Paywall befindet.
URL_RETRIEVAL_STATUS_UNSAFE Der Abruf der URL ist fehlgeschlagen, da die Inhalte unsicher sind.

Zitat-MetadatenS

Eine Sammlung von Quellenangaben für einen Inhalt.

Felder
citationSources[] object (CitationSource)

Quellenangaben für eine bestimmte Antwort.

JSON-Darstellung
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}

CitationSource

Eine Quellenangabe für einen Teil einer bestimmten Antwort.

Felder
startIndex integer

Optional. Beginn des Antwortsegments, das dieser Quelle zugeordnet wird.

Der Index gibt den Anfang des Segments in Byte an.

endIndex integer

Optional. Ende des zugeordneten Segments (ausschließlich).

uri string

Optional. URI, der als Quelle für einen Teil des Texts angegeben wird.

license string

Optional. Lizenz für das GitHub-Projekt, das als Quelle für das Segment angegeben wird.

Für Code-Zitationen sind Lizenzinformationen erforderlich.

JSON-Darstellung
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}

GenerationConfig

Konfigurationsoptionen für die Modellgenerierung und ‑ausgabe. Nicht alle Parameter sind für jedes Modell konfigurierbar.

Felder
stopSequences[] string

Optional. Die Menge der Zeichenfolgen (bis zu 5), die die Ausgabegenerierung stoppen. Falls angegeben, wird die API beim ersten Auftreten von stop_sequence beendet. Die Stoppsequenz ist nicht Teil der Antwort.

responseMimeType string

Optional. MIME-Typ des generierten Kandidatentextes. Unterstützte MIME-Typen: text/plain (Standard): Textausgabe. application/json: JSON-Antwort in den Antwortkandidaten. text/x.enum: ENUM als String-Antwort in den Antwortkandidaten. Eine Liste aller unterstützten Text-MIME-Typen finden Sie in der Dokumentation.

responseSchema object (Schema)

Optional. Ausgabeschema des generierten Kandidatentextes. Schemas müssen eine Teilmenge des OpenAPI-Schemas sein und können Objekte, Primitiven oder Arrays sein.

Wenn dieser Wert festgelegt ist, muss auch ein kompatibler responseMimeType-Wert festgelegt werden. Kompatible MIME-Typen: application/json: Schema für JSON-Antwort. Weitere Informationen finden Sie im Leitfaden zur JSON-Texterstellung.

responseJsonSchema value (Value format)

Optional. Ausgabeschema der generierten Antwort. Dies ist eine Alternative zu responseSchema, die JSON-Schema akzeptiert.

Wenn festgelegt, muss responseSchema weggelassen werden, responseMimeType ist jedoch erforderlich.

Das vollständige JSON-Schema wird zwar möglicherweise gesendet, aber nicht alle Funktionen werden unterstützt. Es werden nur die folgenden Eigenschaften unterstützt:

  • $id
  • $defs
  • $ref
  • $anchor
  • type
  • format
  • title
  • description
  • enum (für Strings und Zahlen)
  • items
  • prefixItems
  • minItems
  • maxItems
  • minimum
  • maximum
  • anyOf
  • oneOf (wird genauso interpretiert wie anyOf)
  • properties
  • additionalProperties
  • required

Die nicht standardmäßige Property propertyOrdering kann ebenfalls festgelegt werden.

Zyklische Verweise werden nur bis zu einem gewissen Grad entrollt und dürfen daher nur in nicht erforderlichen Properties verwendet werden. (Nullable-Eigenschaften reichen nicht aus.) Wenn $ref für ein Unterschema festgelegt ist, dürfen keine anderen Attribute als die, die mit $ beginnen, festgelegt werden.

responseModalities[] enum (Modality)

Optional. Die angeforderten Modalitäten der Antwort. Stellt die Menge der Modalitäten dar, die das Modell zurückgeben kann und die in der Antwort erwartet werden sollten. Das ist eine genaue Übereinstimmung mit den Modalitäten der Antwort.

Ein Modell kann mehrere Kombinationen unterstützter Modalitäten haben. Wenn die angeforderten Modalitäten mit keiner der unterstützten Kombinationen übereinstimmen, wird ein Fehler zurückgegeben.

Eine leere Liste entspricht einer Anfrage nur nach Text.

candidateCount integer

Optional. Anzahl der generierten Antworten, die zurückgegeben werden sollen. Wenn kein Wert festgelegt ist, wird standardmäßig 1 verwendet. Das funktioniert nicht bei Modellen der vorherigen Generation (Gemini 1.0-Familie).

maxOutputTokens integer

Optional. Die maximale Anzahl von Tokens, die in einem Antwortvorschlag enthalten sein dürfen.

Hinweis: Der Standardwert variiert je nach Modell. Weitere Informationen finden Sie im Attribut Model.output_token_limit des Model, das von der Funktion getModel zurückgegeben wird.

temperature number

Optional. Steuert die Zufälligkeit der Ausgabe.

Hinweis: Der Standardwert variiert je nach Modell. Weitere Informationen finden Sie im Attribut Model.temperature des Model, das von der Funktion getModel zurückgegeben wird.

Die Werte können zwischen [0,0, 2,0] liegen.

topP number

Optional. Die maximale kumulative Wahrscheinlichkeit der Tokens, die beim Sampling berücksichtigt werden sollen.

Das Modell verwendet eine kombinierte Top-k- und Top-p-Stichprobenerhebung (Nucleus).

Tokens werden nach ihren zugewiesenen Wahrscheinlichkeiten sortiert, sodass nur die wahrscheinlichsten Tokens berücksichtigt werden. Beim Top-k-Sampling wird die maximale Anzahl der zu berücksichtigenden Tokens direkt begrenzt, während beim Nucleus-Sampling die Anzahl der Tokens auf der Grundlage der kumulativen Wahrscheinlichkeit begrenzt wird.

Hinweis: Der Standardwert variiert je nach Model und wird durch das Attribut Model.top_p angegeben, das von der Funktion getModel zurückgegeben wird. Ein leeres topK-Attribut gibt an, dass das Modell kein Top‑K-Sampling verwendet und das Festlegen von topK für Anfragen nicht zulässt.

topK integer

Optional. Die maximale Anzahl von Tokens, die beim Sampling berücksichtigt werden sollen.

Gemini-Modelle verwenden Top-P-Sampling (Nucleus Sampling) oder eine Kombination aus Top-K- und Nucleus Sampling. Beim Top-K-Sampling wird die Menge der topK wahrscheinlichsten Tokens berücksichtigt. Bei Modellen, die mit Nucleus-Sampling ausgeführt werden, ist keine TopK-Einstellung möglich.

Hinweis: Der Standardwert variiert je nach Model und wird durch das Attribut Model.top_p angegeben, das von der Funktion getModel zurückgegeben wird. Ein leeres topK-Attribut gibt an, dass das Modell kein Top‑K-Sampling verwendet und das Festlegen von topK für Anfragen nicht zulässt.

seed integer

Optional. Seed, der beim Decodieren verwendet wird. Wenn nicht festgelegt, wird für die Anfrage ein zufällig generiertes Seed verwendet.

presencePenalty number

Optional. Die Anwesenheitsstrafe, die auf die Log-Wahrscheinlichkeiten des nächsten Tokens angewendet wird, wenn das Token bereits in der Antwort enthalten ist.

Diese Strafe ist binär (an/aus) und hängt nicht davon ab, wie oft das Token nach dem ersten Mal verwendet wird. Verwenden Sie frequencyPenalty für eine Strafe, die mit jeder Nutzung steigt.

Eine positive Strafe soll die Verwendung von Tokens verhindern, die bereits in der Antwort verwendet wurden, und so den Wortschatz erweitern.

Eine negative Strafe fördert die Verwendung von Tokens, die bereits in der Antwort verwendet wurden, wodurch der Wortschatz verringert wird.

frequencyPenalty number

Optional. Die Häufigkeitsstrafe, die auf die Log-Wahrscheinlichkeiten des nächsten Tokens angewendet wird, multipliziert mit der Anzahl der Male, die jedes Token bisher in der Antwort gesehen wurde.

Eine positive Strafe soll die Verwendung von Tokens, die bereits verwendet wurden, proportional zur Anzahl der Verwendungen des Tokens verhindern: Je häufiger ein Token verwendet wird, desto schwieriger ist es für das Modell, dieses Token wieder zu verwenden, wodurch das Vokabular der Antworten erweitert wird.

Achtung: Eine negative Strafe führt dazu, dass das Modell Tokens proportional zur Anzahl der Verwendungen wiederverwendet. Kleine negative Werte verringern den Wortschatz einer Antwort. Bei größeren negativen Werten wiederholt das Modell ein gemeinsames Token, bis das maxOutputTokens-Limit erreicht ist.

responseLogprobs boolean

Optional. Bei „true“ werden die Ergebnisse von „logprobs“ in der Antwort exportiert.

logprobs integer

Optional. Nur gültig, wenn responseLogprobs=True. Damit wird die Anzahl der Top-Log-Wahrscheinlichkeiten festgelegt, die bei jedem Decodierungsschritt in Candidate.logprobs_result zurückgegeben werden sollen. Die Zahl muss im Bereich [1, 5] liegen.

enableEnhancedCivicAnswers boolean

Optional. Aktiviert verbesserte zivilgesellschaftliche Antworten. Möglicherweise ist sie nicht für alle Modelle verfügbar.

speechConfig object (SpeechConfig)

Optional. Die Konfiguration für die Spracherzeugung.

thinkingConfig object (ThinkingConfig)

Optional. Konfiguration für Denkfunktionen. Ein Fehler wird zurückgegeben, wenn dieses Feld für Modelle festgelegt ist, die keine Denkprozesse unterstützen.

mediaResolution enum (MediaResolution)

Optional. Wenn angegeben, wird die angegebene Media-Auflösung verwendet.

JSON-Darstellung
{
  "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)
}

Modalität

Unterstützte Antworttypen.

Enums
MODALITY_UNSPECIFIED Standardwert.
TEXT Gibt an, dass das Modell Text zurückgeben soll.
IMAGE Gibt an, dass das Modell Bilder zurückgeben soll.
AUDIO Gibt an, dass das Modell Audio zurückgeben soll.

SpeechConfig

Die Konfiguration für die Spracherzeugung.

Felder
voiceConfig object (VoiceConfig)

Die Konfiguration bei der Ausgabe mit einer Stimme.

multiSpeakerVoiceConfig object (MultiSpeakerVoiceConfig)

Optional. Die Konfiguration für die Einrichtung mit mehreren Lautsprechern. Sie schließt sich mit dem Feld „voiceConfig“ gegenseitig aus.

languageCode string

Optional. Sprachcode (im BCP 47-Format, z.B. „en-US“) für die Sprachsynthese.

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

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

VoiceConfig

Die Konfiguration für die zu verwendende Stimme.

Felder
voice_config Union type
Die Konfiguration für den zu verwendenden Lautsprecher. Für voice_config ist nur einer der folgenden Werte zulässig:
prebuiltVoiceConfig object (PrebuiltVoiceConfig)

Die Konfiguration für die zu verwendende vordefinierte Stimme.

JSON-Darstellung
{

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

PrebuiltVoiceConfig

Die Konfiguration für den vordefinierten Lautsprecher.

Felder
voiceName string

Der Name der voreingestellten Stimme, die verwendet werden soll.

JSON-Darstellung
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

Die Konfiguration für die Einrichtung mit mehreren Lautsprechern.

Felder
speakerVoiceConfigs[] object (SpeakerVoiceConfig)

Erforderlich. Alle aktivierten Sprecherstimmen.

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

SpeakerVoiceConfig

Die Konfiguration für einen einzelnen Lautsprecher in einem Setup mit mehreren Lautsprechern.

Felder
speaker string

Erforderlich. Der Name des zu verwendenden Lautsprechers. Sollte mit dem Prompt übereinstimmen.

voiceConfig object (VoiceConfig)

Erforderlich. Die Konfiguration für die zu verwendende Stimme.

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

ThinkingConfig

Konfiguration für Denkfunktionen.

Felder
includeThoughts boolean

Gibt an, ob Überlegungen in die Antwort einbezogen werden sollen. Bei „true“ werden Gedanken nur zurückgegeben, wenn sie verfügbar sind.

thinkingBudget integer

Die Anzahl der „Gedanken“-Tokens, die das Modell generieren soll.

JSON-Darstellung
{
  "includeThoughts": boolean,
  "thinkingBudget": integer
}

MediaResolution

Die Auflösung der Eingabemedien.

Enums
MEDIA_RESOLUTION_UNSPECIFIED Die Media-Auflösung wurde nicht festgelegt.
MEDIA_RESOLUTION_LOW Die Medienauflösung ist auf „Niedrig“ eingestellt (64 Tokens).
MEDIA_RESOLUTION_MEDIUM Die Medienauflösung ist auf „Mittel“ (256 Tokens) eingestellt.
MEDIA_RESOLUTION_HIGH Die Medienauflösung ist auf „Hoch“ eingestellt (herangezoomtes Reframing mit 256 Tokens).

HarmCategory

Die Kategorie einer Bewertung.

Diese Kategorien umfassen verschiedene Arten von Schäden, die Entwickler möglicherweise anpassen möchten.

Enums
HARM_CATEGORY_UNSPECIFIED Die Kategorie ist nicht angegeben.
HARM_CATEGORY_DEROGATORY PaLM – Negative oder schädliche Kommentare, die auf Identität und/oder geschützte Merkmale ausgerichtet sind.
HARM_CATEGORY_TOXICITY PaLM: Unhöfliche, respektlose oder vulgäre Inhalte.
HARM_CATEGORY_VIOLENCE PaLM: Beschreibt Szenarien, in denen Gewalt gegen eine Person oder Gruppe dargestellt wird, oder allgemein blutrünstige Inhalte.
HARM_CATEGORY_SEXUAL PaLM: Enthält Verweise auf sexuelle Handlungen oder andere vulgäre Inhalte.
HARM_CATEGORY_MEDICAL PaLM – Fördert ungeprüfte medizinische Ratschläge.
HARM_CATEGORY_DANGEROUS PaLM: Gefährliche Inhalte, die schädliche Handlungen fördern, erleichtern oder begünstigen.
HARM_CATEGORY_HARASSMENT Gemini – Belästigende Inhalte.
HARM_CATEGORY_HATE_SPEECH Gemini – Hassrede und Inhalte.
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini – Sexuell explizite Inhalte.
HARM_CATEGORY_DANGEROUS_CONTENT Gemini – Gefährliche Inhalte.
HARM_CATEGORY_CIVIC_INTEGRITY

Gemini: Inhalte, die verwendet werden können, um die bürgerliche Integrität zu schädigen. VERWORFEN: Verwenden Sie stattdessen „enableEnhancedCivicAnswers“.

ModalityTokenCount

Stellt Informationen zur Tokenzählung für eine einzelne Modalität dar.

Felder
modality enum (Modality)

Die Modalität, die mit dieser Tokenanzahl verknüpft ist.

tokenCount integer

Anzahl der Tokens.

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

Modalität

Modalität des Inhaltsteils

Enums
MODALITY_UNSPECIFIED Nicht angegebene Modalität.
TEXT Nur Text
IMAGE Bild.
VIDEO Video.
AUDIO Audio.
DOCUMENT Dokument, z.B. PDF.

SafetyRating

Sicherheitsbewertung für einen Inhalt.

Die Sicherheitsbewertung enthält die Schadenskategorie und die Wahrscheinlichkeit des Schadens in dieser Kategorie für einen Inhalt. Inhalte werden anhand einer Reihe von Schadenskategorien auf Sicherheit hin klassifiziert. Die Wahrscheinlichkeit der Klassifizierung als schädlich ist hier enthalten.

Felder
category enum (HarmCategory)

Erforderlich. Die Kategorie für diese Altersfreigabe.

probability enum (HarmProbability)

Erforderlich. Die Wahrscheinlichkeit von Schäden bei diesen Inhalten.

blocked boolean

Wurde dieser Inhalt aufgrund dieser Altersfreigabe blockiert?

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

HarmProbability

Die Wahrscheinlichkeit, dass ein Inhalt schädlich ist.

Das Klassifizierungssystem gibt die Wahrscheinlichkeit an, dass die Inhalte unsicher sind. Diese Zahl gibt nicht an, wie schwerwiegend der Schaden ist, der durch die Inhalte verursacht wird.

Enums
HARM_PROBABILITY_UNSPECIFIED Die Wahrscheinlichkeit ist nicht angegeben.
NEGLIGIBLE Inhalte haben eine vernachlässigbare Wahrscheinlichkeit, unsicher zu sein.
LOW Inhalte haben eine geringe Wahrscheinlichkeit, unsicher zu sein.
MEDIUM Inhalte haben eine mittlere Wahrscheinlichkeit, unsicher zu sein.
HIGH Inhalte haben eine hohe Wahrscheinlichkeit, unsicher zu sein.

SafetySetting

Sicherheitseinstellung, die sich auf das Verhalten bei Sicherheitsblockierungen auswirkt.

Wenn Sie eine Sicherheitseinstellung für eine Kategorie festlegen, ändert sich die zulässige Wahrscheinlichkeit, dass Inhalte blockiert werden.

Felder
category enum (HarmCategory)

Erforderlich. Die Kategorie für diese Einstellung.

threshold enum (HarmBlockThreshold)

Erforderlich. Steuert den Wahrscheinlichkeitsschwellenwert, ab dem Schäden blockiert werden.

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

HarmBlockThreshold

Blockieren bei und über einer bestimmten Wahrscheinlichkeit für Schäden.

Enums
HARM_BLOCK_THRESHOLD_UNSPECIFIED Der Grenzwert ist nicht angegeben.
BLOCK_LOW_AND_ABOVE Inhalte mit der Kennzeichnung NEGLIGIBLE sind zulässig.
BLOCK_MEDIUM_AND_ABOVE Inhalte mit den Kennzeichnungen NEGLIGIBLE und LOW sind zulässig.
BLOCK_ONLY_HIGH Inhalte mit den Werten NEGLIGIBLE, LOW und MEDIUM sind zulässig.
BLOCK_NONE Alle Inhalte sind zulässig.
OFF Deaktivieren Sie den Sicherheitsfilter.