Generating content

L'API Gemini permet de générer du contenu avec des images, de l'audio, du code, des outils et plus encore. Pour en savoir plus sur chacune de ces fonctionnalités, lisez la suite et consultez l'exemple de code axé sur les tâches ou les guides complets.

Méthode : models.generateContent

Génère une réponse du modèle à partir d'une entrée GenerateContentRequest. Pour obtenir des informations détaillées sur l'utilisation, consultez le guide de génération de texte. Les capacités d'entrée diffèrent selon les modèles, y compris les modèles ajustés. Pour en savoir plus, consultez le guide du modèle et le guide du réglage.

Point de terminaison

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

Paramètres de chemin d'accès

model string

Obligatoire. Nom du Model à utiliser pour générer la complétion.

Format : models/{model}. Il se présente sous la forme models/{model}.

Corps de la requête

Le corps de la requête contient des données présentant la structure suivante :

Champs
contents[] object (Content)

Obligatoire. Contenu de la conversation en cours avec le modèle.

Pour les requêtes à un seul tour, il s'agit d'une instance unique. Pour les requêtes multitours comme chat, il s'agit d'un champ répété contenant l'historique de la conversation et la dernière requête.

tools[] object (Tool)

Facultatif. Liste de Tools que Model peut utiliser pour générer la réponse suivante.

Un Tool est un morceau de code qui permet au système d'interagir avec des systèmes externes pour effectuer une action ou un ensemble d'actions en dehors du champ d'application et des connaissances du Model. Les Tool acceptés sont Function et codeExecution. Pour en savoir plus, consultez les guides Appel de fonction et Exécution de code.

toolConfig object (ToolConfig)

Facultatif. Configuration de l'outil pour tout Tool spécifié dans la requête. Pour obtenir un exemple d'utilisation, consultez le guide sur l'appel de fonction.

safetySettings[] object (SafetySetting)

Facultatif. Liste d'instances SafetySetting uniques permettant de bloquer le contenu non sécurisé.

Cette règle sera appliquée sur GenerateContentRequest.contents et GenerateContentResponse.candidates. Il ne doit pas y avoir plus d'un paramètre pour chaque type SafetyCategory. L'API bloquera tout contenu et toute réponse qui ne respectent pas les seuils définis par ces paramètres. Cette liste remplace les paramètres par défaut de chaque SafetyCategory spécifié dans safetySettings. Si aucun SafetySetting n'est associé à un SafetyCategory donné dans la liste, l'API utilise le paramètre de sécurité par défaut pour cette catégorie. Les catégories de préjudice HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT et HARM_CATEGORY_CIVIC_INTEGRITY sont acceptées. Pour en savoir plus sur les paramètres de sécurité disponibles, consultez le guide. Consultez également les Consignes de sécurité pour découvrir comment intégrer des considérations de sécurité dans vos applications d'IA.

systemInstruction object (Content)

Facultatif. Le développeur a défini des instructions système. Texte uniquement pour le moment.

generationConfig object (GenerationConfig)

Facultatif. Options de configuration pour la génération et les sorties du modèle.

cachedContent string

Facultatif. Nom du contenu mis en cache à utiliser comme contexte pour diffuser la prédiction. Format : cachedContents/{cachedContent}

Exemple de requête

Texte

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

Go

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)

Coquille Rose

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

Kotlin

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

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

Swift

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

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

Dart

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

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

Java

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

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

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

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

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

Image

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

Go

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)

Coquille Rose

# 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

Kotlin

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

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

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

Swift

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

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

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

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

Dart

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

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

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

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

Java

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

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

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

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

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

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

Audio

Python

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

Go

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)

Coquille Rose

# 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

Vidéo

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

Go

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)

Coquille Rose

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

Go

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)

Coquille Rose

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

Go

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

Coquille Rose

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"

Kotlin

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

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

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

Swift

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

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

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

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

Dart

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

Java

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

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

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

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

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

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

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

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

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

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

Cache

Python

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

Go

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)

Modèle réglé

Python

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

Mode JSON

Python

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

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

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

Node.js

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

Go

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)

Coquille Rose

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

Kotlin

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

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

Swift

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

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

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

Dart

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

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

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

Java

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

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

GenerationConfig generationConfig = configBuilder.build();

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

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

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

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

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

Exécution du code

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)

Go

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

Kotlin


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

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

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

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

Java

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

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

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

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

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

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

Appel de fonction

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)

Go

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

Coquille Rose


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'

Kotlin

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

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

val usableFunctions = listOf(multiplyDefinition)

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

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

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

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

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

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

Swift

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

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

let chat = generativeModel.startChat()

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

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

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

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

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

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

Dart

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

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

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

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

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

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

Java

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

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

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

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

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

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

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

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

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

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

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

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

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

Configuration de la génération

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

Go

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)

Coquille Rose

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"

Kotlin

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

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

Swift

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

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

Dart

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

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

Java

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

GenerationConfig generationConfig = configBuilder.build();

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

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Paramètres de sécurité

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

Go

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

Coquille Rose

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

Kotlin

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

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

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

Swift

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

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

Dart

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

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

Java

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

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

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

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Instruction système

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

Go

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)

Coquille Rose

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"}}}'

Kotlin

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

Swift

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

Dart

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

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

Java

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

Corps de la réponse

Si la requête aboutit, le corps de la réponse contient une instance de GenerateContentResponse.

Méthode : models.streamGenerateContent

Génère une réponse en flux du modèle à partir d'une entrée GenerateContentRequest.

Point de terminaison

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

Paramètres de chemin d'accès

model string

Obligatoire. Nom du Model à utiliser pour générer la complétion.

Format : models/{model}. Il se présente sous la forme models/{model}.

Corps de la requête

Le corps de la requête contient des données présentant la structure suivante :

Champs
contents[] object (Content)

Obligatoire. Contenu de la conversation en cours avec le modèle.

Pour les requêtes à un seul tour, il s'agit d'une instance unique. Pour les requêtes multitours comme chat, il s'agit d'un champ répété contenant l'historique de la conversation et la dernière requête.

tools[] object (Tool)

Facultatif. Liste de Tools que Model peut utiliser pour générer la réponse suivante.

Un Tool est un morceau de code qui permet au système d'interagir avec des systèmes externes pour effectuer une action ou un ensemble d'actions en dehors du champ d'application et des connaissances du Model. Les Tool acceptés sont Function et codeExecution. Pour en savoir plus, consultez les guides Appel de fonction et Exécution de code.

toolConfig object (ToolConfig)

Facultatif. Configuration de l'outil pour tout Tool spécifié dans la requête. Pour obtenir un exemple d'utilisation, consultez le guide sur l'appel de fonction.

safetySettings[] object (SafetySetting)

Facultatif. Liste d'instances SafetySetting uniques permettant de bloquer le contenu non sécurisé.

Cette règle sera appliquée sur GenerateContentRequest.contents et GenerateContentResponse.candidates. Il ne doit pas y avoir plus d'un paramètre pour chaque type SafetyCategory. L'API bloquera tout contenu et toute réponse qui ne respectent pas les seuils définis par ces paramètres. Cette liste remplace les paramètres par défaut de chaque SafetyCategory spécifié dans safetySettings. Si aucun SafetySetting n'est associé à un SafetyCategory donné dans la liste, l'API utilise le paramètre de sécurité par défaut pour cette catégorie. Les catégories de préjudice HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT et HARM_CATEGORY_CIVIC_INTEGRITY sont acceptées. Pour en savoir plus sur les paramètres de sécurité disponibles, consultez le guide. Consultez également les Consignes de sécurité pour découvrir comment intégrer des considérations de sécurité dans vos applications d'IA.

systemInstruction object (Content)

Facultatif. Le développeur a défini des instructions système. Texte uniquement pour le moment.

generationConfig object (GenerationConfig)

Facultatif. Options de configuration pour la génération et les sorties du modèle.

cachedContent string

Facultatif. Nom du contenu mis en cache à utiliser comme contexte pour diffuser la prédiction. Format : cachedContents/{cachedContent}

Exemple de requête

Texte

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

Go

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

Coquille Rose

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."}]}]}'

Kotlin

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

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

Swift

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

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

Dart

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

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

Java

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

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

Image

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

Go

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

Coquille Rose

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

Kotlin

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

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

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

Swift

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

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

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

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

Dart

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

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

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

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

Java

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

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

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

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

Audio

Python

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)

Go

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

Coquille Rose

# 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

Vidéo

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

Go

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

Coquille Rose

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

Go

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

Coquille Rose

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

Go

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

Coquille Rose

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"

Kotlin

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

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

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

Swift

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

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

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

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

Dart

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

Java

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

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

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

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

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

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

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

StringBuilder outputContent = new StringBuilder();

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

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

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

      @Override
      public void onError(Throwable t) {}

    });

Corps de la réponse

Si la requête aboutit, le corps de la réponse contient un flux d'instances GenerateContentResponse.

GenerateContentResponse

Réponse du modèle acceptant plusieurs réponses candidates.

Les classifications de sécurité et le filtrage du contenu sont indiqués à la fois pour l'invite dans GenerateContentResponse.prompt_feedback et pour chaque candidat dans finishReason et dans safetyRatings. L'API : - renvoie tous les candidats demandés ou aucun d'eux ; - ne renvoie aucun candidat uniquement si la requête est incorrecte (vérifiez promptFeedback) ; - signale les commentaires sur chaque candidat dans finishReason et safetyRatings.

Champs
candidates[] object (Candidate)

Réponses candidates du modèle.

promptFeedback object (PromptFeedback)

Renvoie les commentaires de la requête liés aux filtres de contenu.

usageMetadata object (UsageMetadata)

Uniquement en sortie. Métadonnées sur l'utilisation des jetons pour les requêtes de génération.

modelVersion string

Uniquement en sortie. Version du modèle utilisée pour générer la réponse.

responseId string

Sortie uniquement. responseId permet d'identifier chaque réponse.

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

PromptFeedback

Ensemble des métadonnées de commentaires que l'invite a spécifiées dans GenerateContentRequest.content.

Champs
blockReason enum (BlockReason)

Facultatif. Si cette valeur est définie, cela signifie que la requête a été bloquée et qu'aucun candidat n'a été renvoyé. Reformulez la requête.

safetyRatings[] object (SafetyRating)

Évaluations de la sécurité de la requête. Il ne peut y avoir qu'une seule note par catégorie.

Représentation JSON
{
  "blockReason": enum (BlockReason),
  "safetyRatings": [
    {
      object (SafetyRating)
    }
  ]
}

BlockReason

Indique la raison pour laquelle la requête a été bloquée.

Enums
BLOCK_REASON_UNSPECIFIED Valeur par défaut. Cette valeur n'est pas utilisée.
SAFETY La requête a été bloquée pour des raisons de sécurité. Inspectez safetyRatings pour comprendre la catégorie de sécurité qui l'a bloqué.
OTHER La requête a été bloquée pour des raisons inconnues.
BLOCKLIST La requête a été bloquée en raison des termes inclus dans la liste de blocage de terminologie.
PROHIBITED_CONTENT La requête a été bloquée en raison de contenu interdit.
IMAGE_SAFETY Candidats bloqués en raison de contenus dangereux pour la génération d'images.

UsageMetadata

Métadonnées sur l'utilisation des jetons de la requête de génération.

Champs
promptTokenCount integer

Nombre de jetons dans la requête. Lorsque cachedContent est défini, il s'agit toujours de la taille totale effective de la requête, ce qui signifie qu'il inclut le nombre de jetons dans le contenu mis en cache.

cachedContentTokenCount integer

Nombre de jetons dans la partie mise en cache de la requête (le contenu mis en cache)

candidatesTokenCount integer

Nombre total de jetons pour tous les candidats de réponse générés.

toolUsePromptTokenCount integer

Uniquement en sortie. Nombre de jetons présents dans la ou les invites d'utilisation d'outils.

thoughtsTokenCount integer

Uniquement en sortie. Nombre de jetons de pensées pour les modèles à raisonnement.

totalTokenCount integer

Nombre total de jetons pour la requête de génération (candidats de requête + réponse).

promptTokensDetails[] object (ModalityTokenCount)

Uniquement en sortie. Liste des modalités traitées dans l'entrée de la requête.

cacheTokensDetails[] object (ModalityTokenCount)

Uniquement en sortie. Liste des modalités du contenu mis en cache dans l'entrée de la requête.

candidatesTokensDetails[] object (ModalityTokenCount)

Uniquement en sortie. Liste des modalités renvoyées dans la réponse.

toolUsePromptTokensDetails[] object (ModalityTokenCount)

Uniquement en sortie. Liste des modalités traitées pour les entrées de demande d'utilisation d'outils.

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

Candidat

Réponse candidate générée par le modèle.

Champs
content object (Content)

Uniquement en sortie. Contenu généré renvoyé par le modèle.

finishReason enum (FinishReason)

Facultatif. Uniquement en sortie. Raison pour laquelle le modèle a cessé de générer des jetons.

Si ce champ est vide, le modèle n'a pas cessé de générer des jetons.

safetyRatings[] object (SafetyRating)

Liste des évaluations de sécurité d'une réponse candidate.

Il ne peut y avoir qu'une seule note par catégorie.

citationMetadata object (CitationMetadata)

Uniquement en sortie. Informations de citation pour le candidat généré par le modèle.

Ce champ peut être renseigné avec des informations sur la récitation pour tout texte inclus dans content. Il s'agit de passages "récités" à partir de contenus protégés par des droits d'auteur dans les données d'entraînement du LLM de base.

tokenCount integer

Uniquement en sortie. Nombre de jetons pour ce candidat.

groundingAttributions[] object (GroundingAttribution)

Uniquement en sortie. Informations sur l'attribution des sources ayant contribué à une réponse ancrée.

Ce champ est renseigné pour les appels GenerateAnswer.

groundingMetadata object (GroundingMetadata)

Uniquement en sortie. Métadonnées d'ancrage pour le candidat.

Ce champ est renseigné pour les appels GenerateContent.

avgLogprobs number

Uniquement en sortie. Score de probabilité logarithmique moyen du candidat.

logprobsResult object (LogprobsResult)

Uniquement en sortie. Scores de log-vraisemblance pour les jetons de réponse et les jetons les plus fréquents

urlContextMetadata object (UrlContextMetadata)

Uniquement en sortie. Métadonnées associées à l'outil de récupération du contexte d'URL.

index integer

Uniquement en sortie. Index du candidat dans la liste des candidats de la réponse.

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

FinishReason

Définit la raison pour laquelle le modèle a cessé de générer des jetons.

Enums
FINISH_REASON_UNSPECIFIED Valeur par défaut. Cette valeur n'est pas utilisée.
STOP Point d'arrêt naturel du modèle ou séquence d'arrêt fournie.
MAX_TOKENS Le nombre maximal de jetons spécifié dans la requête a été atteint.
SAFETY Le contenu de la réponse candidate a été signalé pour des raisons de sécurité.
RECITATION Le contenu de la réponse candidate a été signalé pour des raisons de récitation.
LANGUAGE Le contenu de la réponse candidate a été signalé pour utilisation d'une langue non acceptée.
OTHER Raison inconnue.
BLOCKLIST La génération de jetons a été arrêtée, car le contenu contient des termes interdits.
PROHIBITED_CONTENT La génération de jetons a été arrêtée, car elle est susceptible de contenir du contenu interdit.
SPII La génération de jetons a été arrêtée, car le contenu est susceptible de contenir des informations permettant d'identifier personnellement l'utilisateur (SPII).
MALFORMED_FUNCTION_CALL L'appel de fonction généré par le modèle n'est pas valide.
IMAGE_SAFETY La génération de jetons a été interrompue, car les images générées contiennent des cas de non-respect des consignes de sécurité.
UNEXPECTED_TOOL_CALL Le modèle a généré un appel d'outil, mais aucun outil n'était activé dans la requête.

GroundingAttribution

Attribution pour une source ayant contribué à une réponse.

Champs
sourceId object (AttributionSourceId)

Uniquement en sortie. Identifiant de la source contribuant à cette attribution.

content object (Content)

Contenu source d'ancrage qui constitue cette attribution.

Représentation JSON
{
  "sourceId": {
    object (AttributionSourceId)
  },
  "content": {
    object (Content)
  }
}

AttributionSourceId

Identifiant de la source contribuant à cette attribution.

Champs
source Union type
source ne peut être qu'un des éléments suivants :
groundingPassage object (GroundingPassageId)

Identifiant d'un passage intégré.

semanticRetrieverChunk object (SemanticRetrieverChunk)

Identifiant d'un Chunk récupéré via Semantic Retriever.

Représentation JSON
{

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

GroundingPassageId

Identifiant d'une partie dans un GroundingPassage.

Champs
passageId string

Uniquement en sortie. ID du passage correspondant à l'GroundingPassage.id de l'GenerateAnswerRequest.

partIndex integer

Uniquement en sortie. Index de la partie dans les GroundingPassage.content de GenerateAnswerRequest.

Représentation JSON
{
  "passageId": string,
  "partIndex": integer
}

SemanticRetrieverChunk

Identifiant d'un Chunk récupéré via Semantic Retriever spécifié dans GenerateAnswerRequest à l'aide de SemanticRetrieverConfig.

Champs
source string

Uniquement en sortie. Nom de la source correspondant au SemanticRetrieverConfig.source de la requête. Exemple : corpora/123 ou corpora/123/documents/abc

chunk string

Uniquement en sortie. Nom du Chunk contenant le texte attribué. Exemple : corpora/123/documents/abc/chunks/xyz

Représentation JSON
{
  "source": string,
  "chunk": string
}

GroundingMetadata

Métadonnées renvoyées au client lorsque l'ancrage est activé.

Champs
groundingChunks[] object (GroundingChunk)

Liste des références d'appui récupérées à partir de la source d'ancrage spécifiée.

groundingSupports[] object (GroundingSupport)

Liste des supports d'ancrage.

webSearchQueries[] string

Requêtes de recherche sur le Web pour la recherche sur le Web de suivi.

searchEntryPoint object (SearchEntryPoint)

Facultatif. Résultat de recherche Google pour les recherches sur le Web de suivi.

retrievalMetadata object (RetrievalMetadata)

Métadonnées liées à la récupération dans le flux d'ancrage.

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

SearchEntryPoint

Point d'entrée de la recherche Google.

Champs
renderedContent string

Facultatif. Extrait de contenu Web pouvant être intégré à une page Web ou à une WebView d'application.

sdkBlob string (bytes format)

Facultatif. JSON encodé en base64 représentant un tableau de tuples <terme de recherche, URL de recherche>.

Chaîne encodée en base64.

Représentation JSON
{
  "renderedContent": string,
  "sdkBlob": string
}

GroundingChunk

Bloc d'ancrage.

Champs
chunk_type Union type
Type de fragment. chunk_type ne peut être qu'un des éléments suivants :
web object (Web)

Bloc d'ancrage provenant du Web.

Représentation JSON
{

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

Web

Extrait du Web.

Champs
uri string

Référence URI du bloc.

title string

Titre du fragment.

Représentation JSON
{
  "uri": string,
  "title": string
}

GroundingSupport

Support d'ancrage.

Champs
groundingChunkIndices[] integer

Liste d'index (dans "grounding_chunk") spécifiant les citations associées à l'affirmation. Par exemple, [1,3,4] signifie que grounding_chunk[1], grounding_chunk[3] et grounding_chunk[4] sont les contenus récupérés attribués à l'affirmation.

confidenceScores[] number

Score de confiance des références d'assistance. Les valeurs vont de 0 à 1. 1 correspond au niveau de confiance le plus élevé. Cette liste doit avoir la même taille que groundingChunkIndices.

segment object (Segment)

Segment du contenu auquel appartient cette assistance.

Représentation JSON
{
  "groundingChunkIndices": [
    integer
  ],
  "confidenceScores": [
    number
  ],
  "segment": {
    object (Segment)
  }
}

Segment

Segment du contenu.

Champs
partIndex integer

Uniquement en sortie. Index d'un objet Part dans son objet Content parent.

startIndex integer

Uniquement en sortie. Index de début dans la partie donnée, mesuré en octets. Décalage par rapport au début de la partie (inclus), en commençant par zéro.

endIndex integer

Uniquement en sortie. Index de fin de la partie donnée, mesuré en octets. Décalage par rapport au début de la partie, exclusif, en commençant par zéro.

text string

Uniquement en sortie. Texte correspondant au segment de la réponse.

Représentation JSON
{
  "partIndex": integer,
  "startIndex": integer,
  "endIndex": integer,
  "text": string
}

RetrievalMetadata

Métadonnées liées à la récupération dans le flux d'ancrage.

Champs
googleSearchDynamicRetrievalScore number

Facultatif. Score indiquant la probabilité que les informations de la recherche Google puissent aider à répondre à la requête. Le score est compris dans la plage [0, 1], où 0 correspond à la probabilité la plus faible et 1 à la probabilité la plus élevée. Ce score n'est renseigné que lorsque l'ancrage dans la recherche Google et la récupération dynamique sont activés. Il sera comparé au seuil pour déterminer s'il faut déclencher la recherche Google.

Représentation JSON
{
  "googleSearchDynamicRetrievalScore": number
}

LogprobsResult

Résultat Logprobs

Champs
topCandidates[] object (TopCandidates)

Longueur = nombre total d'étapes de décodage.

chosenCandidates[] object (Candidate)

Longueur = nombre total d'étapes de décodage. Les candidats choisis peuvent se trouver ou non dans topCandidates.

Représentation JSON
{
  "topCandidates": [
    {
      object (TopCandidates)
    }
  ],
  "chosenCandidates": [
    {
      object (Candidate)
    }
  ]
}

TopCandidates

Candidats avec les probabilités logarithmiques les plus élevées à chaque étape de décodage.

Champs
candidates[] object (Candidate)

Triées par probabilité logarithmique dans l'ordre décroissant.

Représentation JSON
{
  "candidates": [
    {
      object (Candidate)
    }
  ]
}

Candidat

Candidat pour le jeton et le score logprobs.

Champs
token string

Valeur de la chaîne du jeton du candidat.

tokenId integer

Valeur de l'ID du jeton du candidat.

logProbability number

Probabilité logarithmique du candidat.

Représentation JSON
{
  "token": string,
  "tokenId": integer,
  "logProbability": number
}

UrlContextMetadata

Métadonnées associées à l'outil de récupération du contexte d'URL.

Champs
urlMetadata[] object (UrlMetadata)

Liste du contexte d'URL.

Représentation JSON
{
  "urlMetadata": [
    {
      object (UrlMetadata)
    }
  ]
}

UrlMetadata

Contexte de la récupération d'une seule URL.

Champs
retrievedUrl string

URL récupérée par l'outil.

urlRetrievalStatus enum (UrlRetrievalStatus)

État de la récupération de l'URL.

Représentation JSON
{
  "retrievedUrl": string,
  "urlRetrievalStatus": enum (UrlRetrievalStatus)
}

UrlRetrievalStatus

État de la récupération de l'URL.

Enums
URL_RETRIEVAL_STATUS_UNSPECIFIED Valeur par défaut. Cette valeur n'est pas utilisée.
URL_RETRIEVAL_STATUS_SUCCESS La récupération de l'URL a réussi.
URL_RETRIEVAL_STATUS_ERROR Échec de la récupération de l'URL en raison d'une erreur.

CitationMetadata

Ensemble d'attributions de source pour un contenu.

Champs
citationSources[] object (CitationSource)

Citations des sources pour une réponse spécifique.

Représentation JSON
{
  "citationSources": [
    {
      object (CitationSource)
    }
  ]
}

CitationSource

Citation d'une source pour une partie d'une réponse spécifique.

Champs
startIndex integer

Facultatif. Début du segment de la réponse attribué à cette source.

L'index indique le début du segment, mesuré en octets.

endIndex integer

Facultatif. Fin du segment attribué (exclusif).

uri string

Facultatif. URI attribué comme source pour une partie du texte.

license string

Facultatif. Licence du projet GitHub attribué en tant que source pour le segment.

Les informations sur la licence sont obligatoires pour les citations de code.

Représentation JSON
{
  "startIndex": integer,
  "endIndex": integer,
  "uri": string,
  "license": string
}

GenerationConfig

Options de configuration pour la génération et les sorties du modèle. Tous les paramètres ne sont pas configurables pour tous les modèles.

Champs
stopSequences[] string

Facultatif. Ensemble de séquences de caractères (jusqu'à cinq) qui arrêteront la génération de sortie. Si cette valeur est spécifiée, l'API s'arrête à la première occurrence d'un stop_sequence. La séquence d'arrêt ne sera pas incluse dans la réponse.

responseMimeType string

Facultatif. Type MIME du texte candidat généré. Les types MIME acceptés sont les suivants : text/plain (par défaut) : sortie de texte. application/json : réponse JSON dans les candidats de réponse. text/x.enum : ENUM en tant que réponse de chaîne dans les candidats de réponse. Consultez la documentation pour obtenir la liste de tous les types MIME de texte compatibles.

responseSchema object (Schema)

Facultatif. Schéma de sortie du texte candidat généré. Les schémas doivent être un sous-ensemble du schéma OpenAPI et peuvent être des objets, des primitives ou des tableaux.

Si cette option est définie, un responseMimeType compatible doit également être défini. Types MIME compatibles : application/json : schéma pour la réponse JSON. Pour en savoir plus, consultez le guide de génération de texte JSON.

responseJsonSchema value (Value format)

Facultatif. Schéma de sortie de la réponse générée. Il s'agit d'une alternative à responseSchema qui accepte le schéma JSON.

Si cette option est définie, responseSchema doit être omis, mais responseMimeType est obligatoire.

Bien que le schéma JSON complet puisse être envoyé, toutes les fonctionnalités ne sont pas prises en charge. Plus précisément, seules les propriétés suivantes sont acceptées :

  • $id
  • $defs
  • $ref
  • $anchor
  • type
  • format
  • title
  • description
  • enum (pour les chaînes et les nombres)
  • items
  • prefixItems
  • minItems
  • maxItems
  • minimum
  • maximum
  • anyOf
  • oneOf (interprété de la même manière que anyOf)
  • properties
  • additionalProperties
  • required

La propriété non standard propertyOrdering peut également être définie.

Les références cycliques sont déroulées dans une certaine mesure et ne peuvent donc être utilisées que dans des propriétés non obligatoires. (Les propriétés pouvant être nulles ne suffisent pas.) Si $ref est défini sur un sous-schéma, aucune autre propriété ne peut être définie, à l'exception de celles commençant par $.

responseModalities[] enum (Modality)

Facultatif. Modalités de réponse demandées. Représente l'ensemble des modalités que le modèle peut renvoyer et qui doivent être attendues dans la réponse. Il s'agit d'une correspondance exacte avec les modalités de la réponse.

Un modèle peut comporter plusieurs combinaisons de modalités compatibles. Si les modalités demandées ne correspondent à aucune des combinaisons acceptées, une erreur est renvoyée.

Une liste vide équivaut à demander uniquement du texte.

candidateCount integer

Facultatif. Nombre de réponses générées à renvoyer. Si cette valeur n'est pas définie, la valeur par défaut est 1. Veuillez noter que cela ne fonctionne pas pour les modèles de génération précédente (famille Gemini 1.0).

maxOutputTokens integer

Facultatif. Nombre maximal de jetons à inclure dans une réponse candidate.

Remarque : La valeur par défaut varie selon le modèle. Consultez l'attribut Model.output_token_limit de Model renvoyé par la fonction getModel.

temperature number

Facultatif. Contrôle le caractère aléatoire de la sortie.

Remarque : La valeur par défaut varie selon le modèle. Consultez l'attribut Model.temperature de Model renvoyé par la fonction getModel.

Les valeurs peuvent être comprises entre 0,0 et 2,0.

topP number

Facultatif. Probabilité cumulée maximale des jetons à prendre en compte lors de l'échantillonnage.

Le modèle utilise un échantillonnage combiné Top-k et Top-p (nucleus).

Les jetons sont triés en fonction des probabilités qui leur sont attribuées, de sorte que seuls les jetons les plus probables sont pris en compte. L'échantillonnage Top-k limite directement le nombre maximal de jetons à prendre en compte, tandis que l'échantillonnage Nucleus limite le nombre de jetons en fonction de la probabilité cumulée.

Remarque : La valeur par défaut varie selon Model et est spécifiée par l'attribut Model.top_p renvoyé par la fonction getModel. Un attribut topK vide indique que le modèle n'applique pas l'échantillonnage top-k et ne permet pas de définir topK dans les requêtes.

topK integer

Facultatif. Nombre maximal de jetons à prendre en compte lors de l'échantillonnage.

Les modèles Gemini utilisent l'échantillonnage Top-p (noyau) ou une combinaison d'échantillonnage Top-k et de noyau. L'échantillonnage top-k prend en compte l'ensemble des topK jetons les plus probables. Les modèles exécutés avec l'échantillonnage du noyau ne permettent pas de définir topK.

Remarque : La valeur par défaut varie selon Model et est spécifiée par l'attribut Model.top_p renvoyé par la fonction getModel. Un attribut topK vide indique que le modèle n'applique pas l'échantillonnage top-k et ne permet pas de définir topK dans les requêtes.

seed integer

Facultatif. Graine utilisée dans le décodage. Si elle n'est pas définie, la requête utilise une graine générée de manière aléatoire.

presencePenalty number

Facultatif. Pénalité de présence appliquée aux logprobs du jeton suivant si le jeton a déjà été vu dans la réponse.

Cette pénalité est binaire (activée/désactivée) et ne dépend pas du nombre de fois où le jeton est utilisé (après la première fois). Utilisez frequencyPenalty pour une pénalité qui augmente à chaque utilisation.

Une pénalité positive dissuadera l'utilisation de jetons déjà utilisés dans la réponse, ce qui augmentera le vocabulaire.

Une pénalité négative encouragera l'utilisation de jetons déjà utilisés dans la réponse, ce qui réduira le vocabulaire.

frequencyPenalty number

Facultatif. Pénalité de fréquence appliquée aux logprobs du jeton suivant, multipliée par le nombre de fois où chaque jeton a été vu dans la réponse jusqu'à présent.

Une pénalité positive découragera l'utilisation de jetons déjà utilisés, proportionnellement au nombre de fois où le jeton a été utilisé : plus un jeton est utilisé, plus il est difficile pour le modèle de l'utiliser à nouveau, ce qui augmente le vocabulaire des réponses.

Attention : Une pénalité négative encouragera le modèle à réutiliser les jetons proportionnellement au nombre de fois où ils ont été utilisés. De petites valeurs négatives réduisent le vocabulaire d'une réponse. Des valeurs négatives plus importantes entraîneront la répétition d'un jeton commun par le modèle jusqu'à ce qu'il atteigne la limite maxOutputTokens.

responseLogprobs boolean

Facultatif. Si la valeur est "true", les résultats logprobs sont exportés dans la réponse.

logprobs integer

Facultatif. Valide uniquement si responseLogprobs=True. Cela définit le nombre de logprobs les plus élevés à renvoyer à chaque étape de décodage dans Candidate.logprobs_result.

enableEnhancedCivicAnswers boolean

Facultatif. Active les réponses civiques améliorées. Il est possible qu'elle ne soit pas disponible pour tous les modèles.

speechConfig object (SpeechConfig)

Facultatif. Configuration de la génération vocale.

thinkingConfig object (ThinkingConfig)

Facultatif. Configuration des fonctionnalités de réflexion. Une erreur sera renvoyée si ce champ est défini pour des modèles qui ne prennent pas en charge la réflexion.

mediaResolution enum (MediaResolution)

Facultatif. Si une résolution est spécifiée, elle sera utilisée.

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

Modalité

Modalités de réponse acceptées.

Enums
MODALITY_UNSPECIFIED Valeur par défaut.
TEXT Indique que le modèle doit renvoyer du texte.
IMAGE Indique que le modèle doit renvoyer des images.
AUDIO Indique que le modèle doit renvoyer de l'audio.

SpeechConfig

Configuration de la génération vocale.

Champs
voiceConfig object (VoiceConfig)

Configuration en cas de sortie à une seule voix.

multiSpeakerVoiceConfig object (MultiSpeakerVoiceConfig)

Facultatif. Configuration de la configuration multispeaker. Il s'exclut mutuellement avec le champ voiceConfig.

languageCode string

Facultatif. Code de langue (au format BCP 47, par exemple "en-US") pour la synthèse vocale.

Les valeurs valides sont les suivantes : 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 et th-TH.

Représentation JSON
{
  "voiceConfig": {
    object (VoiceConfig)
  },
  "multiSpeakerVoiceConfig": {
    object (MultiSpeakerVoiceConfig)
  },
  "languageCode": string
}

VoiceConfig

Configuration de la voix à utiliser.

Champs
voice_config Union type
Configuration à utiliser par l'enceinte. voice_config ne peut être qu'un des éléments suivants :
prebuiltVoiceConfig object (PrebuiltVoiceConfig)

Configuration de la voix prédéfinie à utiliser.

Représentation JSON
{

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

PrebuiltVoiceConfig

Configuration à utiliser pour le haut-parleur prédéfini.

Champs
voiceName string

Nom de la voix prédéfinie à utiliser.

Représentation JSON
{
  "voiceName": string
}

MultiSpeakerVoiceConfig

Configuration de la configuration multispeaker.

Champs
speakerVoiceConfigs[] object (SpeakerVoiceConfig)

Obligatoire. Toutes les voix d'enceinte activées.

Représentation JSON
{
  "speakerVoiceConfigs": [
    {
      object (SpeakerVoiceConfig)
    }
  ]
}

SpeakerVoiceConfig

Configuration d'une seule enceinte dans une configuration à plusieurs enceintes.

Champs
speaker string

Obligatoire. Nom du locuteur à utiliser. Doit être identique à celui de la requête.

voiceConfig object (VoiceConfig)

Obligatoire. Configuration de la voix à utiliser.

Représentation JSON
{
  "speaker": string,
  "voiceConfig": {
    object (VoiceConfig)
  }
}

ThinkingConfig

Configuration des fonctionnalités de réflexion.

Champs
includeThoughts boolean

Indique s'il faut inclure les réflexions dans la réponse. Si la valeur est "true", les réflexions ne sont renvoyées que lorsqu'elles sont disponibles.

thinkingBudget integer

Nombre de jetons de réflexion que le modèle doit générer.

Représentation JSON
{
  "includeThoughts": boolean,
  "thinkingBudget": integer
}

MediaResolution

Résolution du contenu multimédia d'entrée.

Enums
MEDIA_RESOLUTION_UNSPECIFIED La résolution du contenu multimédia n'a pas été définie.
MEDIA_RESOLUTION_LOW La résolution des contenus multimédias est définie sur "basse" (64 jetons).
MEDIA_RESOLUTION_MEDIUM Résolution média définie sur moyenne (256 jetons).
MEDIA_RESOLUTION_HIGH Résolution du contenu multimédia définie sur "Élevée" (recadrage zoomé avec 256 jetons).

HarmCategory

Catégorie d'une note.

Ces catégories couvrent différents types de préjudices que les développeurs peuvent souhaiter ajuster.

Enums
HARM_CATEGORY_UNSPECIFIED La catégorie n'est pas spécifiée.
HARM_CATEGORY_DEROGATORY PaLM : commentaires négatifs ou offensants ciblant l'identité et/ou les attributs protégés.
HARM_CATEGORY_TOXICITY PaLM : contenu offensant, irrespectueux ou grossier.
HARM_CATEGORY_VIOLENCE PaLM : descriptions de scénarios représentant des actes de violence contre un individu ou un groupe, ou descriptions générales de contenus sanglants.
HARM_CATEGORY_SEXUAL PaLM : contient des références à des actes sexuels ou à d'autres contenus obscènes.
HARM_CATEGORY_MEDICAL PaLM : promeut des conseils médicaux non vérifiés.
HARM_CATEGORY_DANGEROUS PaLM : contenu dangereux qui promeut, facilite ou encourage des actes dangereux.
HARM_CATEGORY_HARASSMENT Gemini : contenu relevant du harcèlement.
HARM_CATEGORY_HATE_SPEECH Gemini : incitation à la haine et contenu haineux
HARM_CATEGORY_SEXUALLY_EXPLICIT Gemini : contenu à caractère sexuel explicite
HARM_CATEGORY_DANGEROUS_CONTENT Gemini : contenu dangereux.
HARM_CATEGORY_CIVIC_INTEGRITY Gemini : contenu susceptible de nuire à l'intégrité civique.

ModalityTokenCount

Représente les informations de comptage des jetons pour une seule modalité.

Champs
modality enum (Modality)

Modalité associée à ce nombre de jetons.

tokenCount integer

Nombre de jetons.

Représentation JSON
{
  "modality": enum (Modality),
  "tokenCount": integer
}

Modalité

Modalité de la partie du contenu

Enums
MODALITY_UNSPECIFIED Modalité non spécifiée.
TEXT Texte brut.
IMAGE Image.
VIDEO Vidéo.
AUDIO Audio.
DOCUMENT Document, par exemple au format PDF.

SafetyRating

Classification de sécurité d'un contenu.

L'évaluation de sécurité contient la catégorie de préjudice et le niveau de probabilité de préjudice dans cette catégorie pour un contenu. Le contenu est classé en fonction de la sécurité dans plusieurs catégories de préjudices. La probabilité de la classification des préjudices est également indiquée.

Champs
category enum (HarmCategory)

Obligatoire. Catégorie de cette note.

probability enum (HarmProbability)

Obligatoire. Probabilité de préjudice pour ce contenu.

blocked boolean

Ce contenu a-t-il été bloqué en raison de cette classification ?

Représentation JSON
{
  "category": enum (HarmCategory),
  "probability": enum (HarmProbability),
  "blocked": boolean
}

HarmProbability

Probabilité qu'un contenu soit nuisible.

Le système de classification indique la probabilité que le contenu soit non sécurisé. Cela n'indique pas la gravité du préjudice causé par un contenu.

Enums
HARM_PROBABILITY_UNSPECIFIED La probabilité n'est pas spécifiée.
NEGLIGIBLE Le contenu présente une probabilité négligeable d'être non sécurisé.
LOW Le contenu présente peu de risques d'être non sécurisé.
MEDIUM Le contenu présente une probabilité moyenne d'être non sécurisé.
HIGH Le contenu présente une probabilité élevée d'être non sécurisé.

SafetySetting

Paramètre de sécurité qui affecte le comportement de blocage de la sécurité.

Si vous transmettez un paramètre de sécurité pour une catégorie, la probabilité autorisée de blocage du contenu est modifiée.

Champs
category enum (HarmCategory)

Obligatoire. Catégorie de ce paramètre.

threshold enum (HarmBlockThreshold)

Obligatoire. Contrôle le seuil de probabilité à partir duquel les contenus nuisibles sont bloqués.

Représentation JSON
{
  "category": enum (HarmCategory),
  "threshold": enum (HarmBlockThreshold)
}

HarmBlockThreshold

Bloquer les contenus dont la probabilité de préjudice est supérieure ou égale à un seuil spécifié.

Enums
HARM_BLOCK_THRESHOLD_UNSPECIFIED Le seuil n'est pas spécifié.
BLOCK_LOW_AND_ABOVE Les contenus présentant un risque NÉGLIGEABLE seront autorisés.
BLOCK_MEDIUM_AND_ABOVE Les contenus présentant un risque NÉGLIGEABLE ou FAIBLE seront autorisés.
BLOCK_ONLY_HIGH Les contenus classés comme NEGLIGEABLES, FAIBLES et MOYENS seront autorisés.
BLOCK_NONE Tous les contenus seront autorisés.
OFF Désactivez le filtre de sécurité.