You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Gemini API can generate text output from text, images, video, and audio
inputs.
Here's a basic example:
Python
fromgoogleimportgenaiclient=genai.Client()
response=client.models.generate_content(
model="gemini-3.6-flash",
contents="How does AI work?"
)
print(response.text)
JavaScript
import{GoogleGenAI}from"@google/genai";constai=newGoogleGenAI({});asyncfunctionmain(){constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: "How does AI work?",});console.log(response.text);}awaitmain();
Go
package main
import (
"context""fmt""os""google.golang.org/genai"
)
funcmain() {
ctx:=context.Background()
client, err:=genai.NewClient(ctx, nil)
iferr!=nil {
log.Fatal(err)
}
result, _:=client.Models.GenerateContent(
ctx,
"gemini-3.6-flash",
genai.Text("Explain how AI works in a few words"),
nil,
)
fmt.Println(result.Text())
}
// See https://developers.google.com/apps-script/guides/properties// for instructions on how to set the API key.constapiKey=PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');functionmain(){constpayload={contents: [{parts: [{text: 'How AI does work?'},],},],};consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent';constoptions={method: 'POST',contentType: 'application/json',headers: {'x-goog-api-key': apiKey,},payload: JSON.stringify(payload)};constresponse=UrlFetchApp.fetch(url,options);constdata=JSON.parse(response);constcontent=data['candidates'][0]['content']['parts'][0]['text'];console.log(content);}
Thinking with Gemini
Gemini models often have "thinking" enabled by default
which allows the model to reason before responding to a request.
Each model supports different thinking configurations which gives you control
over cost, latency, and intelligence. For more details, see the
thinking guide.
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
response=client.models.generate_content(
model="gemini-3.6-flash",
contents="How does AI work?",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(thinking_level="low")
),
)
print(response.text)
JavaScript
import{GoogleGenAI,ThinkingLevel}from"@google/genai";constai=newGoogleGenAI({});asyncfunctionmain(){constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: "How does AI work?",config: {thinkingConfig: {thinkingLevel: ThinkingLevel.LOW,},}});console.log(response.text);}awaitmain();
// See https://developers.google.com/apps-script/guides/properties// for instructions on how to set the API key.constapiKey=PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');functionmain(){constpayload={contents: [{parts: [{text: 'How AI does work?'},],},],generationConfig: {thinkingConfig: {thinkingLevel: 'low'}}};consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent';constoptions={method: 'POST',contentType: 'application/json',headers: {'x-goog-api-key': apiKey,},payload: JSON.stringify(payload)};constresponse=UrlFetchApp.fetch(url,options);constdata=JSON.parse(response);constcontent=data['candidates'][0]['content']['parts'][0]['text'];console.log(content);}
System instructions and other configurations
You can guide the behavior of Gemini models with system instructions. To do so,
pass a GenerateContentConfig
object.
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
response=client.models.generate_content(
model="gemini-3.6-flash",
config=types.GenerateContentConfig(
system_instruction="You are a cat. Your name is Neko."),
contents="Hello there"
)
print(response.text)
JavaScript
import{GoogleGenAI}from"@google/genai";constai=newGoogleGenAI({});asyncfunctionmain(){constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: "Hello there",config: {systemInstruction: "You are a cat. Your name is Neko.",},});console.log(response.text);}awaitmain();
Go
package main
import (
"context""fmt""os""google.golang.org/genai"
)
funcmain() {
ctx:=context.Background()
client, err:=genai.NewClient(ctx, nil)
iferr!=nil {
log.Fatal(err)
}
config:=&genai.GenerateContentConfig{
SystemInstruction: genai.NewContentFromText("You are a cat. Your name is Neko.", genai.RoleUser),
}
result, _:=client.Models.GenerateContent(
ctx,
"gemini-3.6-flash",
genai.Text("Hello there"),
config,
)
fmt.Println(result.Text())
}
Java
importcom.google.genai.Client;
importcom.google.genai.types.Content;
importcom.google.genai.types.GenerateContentConfig;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.Part;
publicclassGenerateContentWithSystemInstruction {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
GenerateContentConfigconfig =
GenerateContentConfig.builder()
.systemInstruction(
Content.fromParts(Part.fromText("You are a cat. Your name is Neko.")))
.build();
GenerateContentResponseresponse =
client.models.generateContent("gemini-3.6-flash", "Hello there", config);
System.out.println(response.text());
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent" \
-H "x-goog-api-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" } ] } ] }'
Apps Script
// See https://developers.google.com/apps-script/guides/properties// for instructions on how to set the API key.constapiKey=PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');functionmain(){constsystemInstruction={parts: [{text: 'You are a cat. Your name is Neko.'}]};constpayload={
systemInstruction,contents: [{parts: [{text: 'Hello there'},],},],};consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent';constoptions={method: 'POST',contentType: 'application/json',headers: {'x-goog-api-key': apiKey,},payload: JSON.stringify(payload)};constresponse=UrlFetchApp.fetch(url,options);constdata=JSON.parse(response);constcontent=data['candidates'][0]['content']['parts'][0]['text'];console.log(content);}
The temperature, top_p, and top_k parameters control how the model
generates responses. Although you can modify these parameters, we strongly
recommend keeping them at their default values for Gemini 3.x models. Changing
these parameters (for example, setting the temperature below 1.0) can cause
unexpected behavior, such as looping or degraded performance, particularly in
complex mathematical or reasoning tasks.
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
response=client.models.generate_content(
model="gemini-3.6-flash",
contents=["Explain how AI works"],
config=types.GenerateContentConfig(
max_output_tokens=1000
)
)
print(response.text)
JavaScript
import{GoogleGenAI}from"@google/genai";constai=newGoogleGenAI({});asyncfunctionmain(){constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: "Explain how AI works",config: {maxOutputTokens: 1000,},});console.log(response.text);}awaitmain();
Go
package main
import (
"context""fmt""log""google.golang.org/genai"
)
funcmain() {
ctx:=context.Background()
client, err:=genai.NewClient(ctx, nil)
iferr!=nil {
log.Fatal(err)
}
config:=&genai.GenerateContentConfig{
MaxOutputTokens: 1000,
ResponseMIMEType: "application/json",
}
result, _:=client.Models.GenerateContent(
ctx,
"gemini-3.6-flash",
genai.Text("What is the average size of a swallow?"),
config,
)
fmt.Println(result.Text())
}
// See https://developers.google.com/apps-script/guides/properties// for instructions on how to set the API key.constapiKey=PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');functionmain(){constgenerationConfig={maxOutputTokens: 1000,responseFormat: {text: {mimeType: "text/plain"}},};constpayload={
generationConfig,contents: [{parts: [{text: 'Explain how AI works in a few words'},],},],};consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent';constoptions={method: 'POST',contentType: 'application/json',headers: {'x-goog-api-key': apiKey,},payload: JSON.stringify(payload)};constresponse=UrlFetchApp.fetch(url,options);constdata=JSON.parse(response);constcontent=data['candidates'][0]['content']['parts'][0]['text'];console.log(content);}
Refer to the GenerateContentConfig
in our API reference for a complete list of configurable parameters and their
descriptions.
Multimodal inputs
The Gemini API supports multimodal inputs, allowing you to combine text with
media files. The following example demonstrates providing an image:
Python
fromPILimportImagefromgoogleimportgenaiclient=genai.Client()
image=Image.open("/path/to/organ.png")
response=client.models.generate_content(
model="gemini-3.6-flash",
contents=[image, "Tell me about this instrument"]
)
print(response.text)
JavaScript
import{GoogleGenAI,createUserContent,createPartFromUri,}from"@google/genai";constai=newGoogleGenAI({});asyncfunctionmain(){constimage=awaitai.files.upload({file: "/path/to/organ.png",});constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: [createUserContent(["Tell me about this instrument",createPartFromUri(image.uri,image.mimeType),]),],});console.log(response.text);}awaitmain();
importcom.google.genai.Client;
importcom.google.genai.Content;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.Part;
publicclassGenerateContentWithMultiModalInputs {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
Contentcontent =
Content.fromParts(
Part.fromText("Tell me about this instrument"),
Part.fromUri("/path/to/organ.jpg", "image/jpeg"));
GenerateContentResponseresponse =
client.models.generateContent("gemini-3.6-flash", content, null);
System.out.println(response.text());
}
}
REST
# 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-3.6-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d "@$TEMP_JSON"
Apps Script
// See https://developers.google.com/apps-script/guides/properties// for instructions on how to set the API key.constapiKey=PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');functionmain(){constimageUrl='https://example.com/image.jpg';constimage=getImageData(imageUrl);constpayload={contents: [{parts: [{ image },{text: 'Tell me about this instrument'},],},],};consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent';constoptions={method: 'POST',contentType: 'application/json',headers: {'x-goog-api-key': apiKey,},payload: JSON.stringify(payload)};constresponse=UrlFetchApp.fetch(url,options);constdata=JSON.parse(response);constcontent=data['candidates'][0]['content']['parts'][0]['text'];console.log(content);}functiongetImageData(url){constblob=UrlFetchApp.fetch(url).getBlob();return{mimeType: blob.getContentType(),data: Utilities.base64Encode(blob.getBytes())};}
For alternative methods of providing images and more advanced image processing,
see our image understanding guide.
The API also supports document, video, and audio
inputs and understanding.
Streaming responses
By default, the model returns a response only after the entire generation
process is complete.
For more fluid interactions, use streaming to receive GenerateContentResponse instances incrementally
as they're generated.
Python
fromgoogleimportgenaiclient=genai.Client()
response=client.models.generate_content_stream(
model="gemini-3.6-flash",
contents=["Explain how AI works"]
)
forchunkinresponse:
print(chunk.text, end="")
JavaScript
import{GoogleGenAI}from"@google/genai";constai=newGoogleGenAI({});asyncfunctionmain(){constresponse=awaitai.models.generateContentStream({model: "gemini-3.6-flash",contents: "Explain how AI works",});forawait(constchunkofresponse){console.log(chunk.text);}}awaitmain();
Go
package main
import (
"context""fmt""os""google.golang.org/genai"
)
funcmain() {
ctx:=context.Background()
client, err:=genai.NewClient(ctx, nil)
iferr!=nil {
log.Fatal(err)
}
stream:=client.Models.GenerateContentStream(
ctx,
"gemini-3.6-flash",
genai.Text("Write a story about a magic backpack."),
nil,
)
forchunk, _:=rangestream {
part:=chunk.Candidates[0].Content.Parts[0]
fmt.Print(part.Text)
}
}
Java
importcom.google.genai.Client;
importcom.google.genai.ResponseStream;
importcom.google.genai.types.GenerateContentResponse;
publicclassGenerateContentStream {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
ResponseStream<GenerateContentResponse> responseStream =
client.models.generateContentStream(
"gemini-3.6-flash", "Write a story about a magic backpack.", null);
for (GenerateContentResponseres : responseStream) {
System.out.print(res.text());
}
// To save resources and avoid connection leaks, it is recommended to close the response// stream after consumption (or using try block to get the response stream).responseStream.close();
}
}
// See https://developers.google.com/apps-script/guides/properties// for instructions on how to set the API key.constapiKey=PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');functionmain(){constpayload={contents: [{parts: [{text: 'Explain how AI works'},],},],};consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:streamGenerateContent';constoptions={method: 'POST',contentType: 'application/json',headers: {'x-goog-api-key': apiKey,},payload: JSON.stringify(payload)};constresponse=UrlFetchApp.fetch(url,options);constdata=JSON.parse(response);constcontent=data['candidates'][0]['content']['parts'][0]['text'];console.log(content);}
Multi-turn conversations (chat)
Our SDKs provide functionality to collect multiple rounds of prompts and
responses into a chat, giving you an easy way to keep track of the conversation
history.
Note: Chat functionality is only implemented as part of the SDKs. Behind the
scenes, it still uses the generateContent API. For multi-turn
conversations, the full conversation history is sent to the model with each
follow-up turn.
Python
fromgoogleimportgenaiclient=genai.Client()
chat=client.chats.create(model="gemini-3.6-flash")
response=chat.send_message("I have 2 dogs in my house.")
print(response.text)
response=chat.send_message("How many paws are in my house?")
print(response.text)
formessageinchat.get_history():
print(f'role - {message.role}',end=": ")
print(message.parts[0].text)
JavaScript
import{GoogleGenAI}from"@google/genai";constai=newGoogleGenAI({});asyncfunctionmain(){constchat=ai.chats.create({model: "gemini-3.6-flash",history: [{role: "user",parts: [{text: "Hello"}],},{role: "model",parts: [{text: "Great to meet you. What would you like to know?"}],},],});constresponse1=awaitchat.sendMessage({message: "I have 2 dogs in my house.",});console.log("Chat response 1:",response1.text);constresponse2=awaitchat.sendMessage({message: "How many paws are in my house?",});console.log("Chat response 2:",response2.text);}awaitmain();
Go
package main
import (
"context""fmt""os""google.golang.org/genai"
)
funcmain() {
ctx:=context.Background()
client, err:=genai.NewClient(ctx, nil)
iferr!=nil {
log.Fatal(err)
}
history:= []*genai.Content{
genai.NewContentFromText("Hi nice to meet you! I have 2 dogs in my house.", genai.RoleUser),
genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),
}
chat, _:=client.Chats.Create(ctx, "gemini-3.6-flash", nil, history)
res, _:=chat.SendMessage(ctx, genai.Part{Text: "How many paws are in my house?"})
iflen(res.Candidates) >0 {
fmt.Println(res.Candidates[0].Content.Parts[0].Text)
}
}
Java
importcom.google.genai.Chat;
importcom.google.genai.Client;
importcom.google.genai.types.Content;
importcom.google.genai.types.GenerateContentResponse;
publicclassMultiTurnConversation {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
ChatchatSession = client.chats.create("gemini-3.6-flash");
GenerateContentResponseresponse =
chatSession.sendMessage("I have 2 dogs in my house.");
System.out.println("First response: " + response.text());
response = chatSession.sendMessage("How many paws are in my house?");
System.out.println("Second response: " + response.text());
// Get the history of the chat session.// Passing 'true' to getHistory() returns the curated history, which excludes// empty or invalid parts.// Passing 'false' here would return the comprehensive history, including// empty or invalid parts.ImmutableList<Content> history = chatSession.getHistory(true);
System.out.println("History: " + history);
}
}
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent \
-H "x-goog-api-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?" } ] } ] }'
Apps Script
// See https://developers.google.com/apps-script/guides/properties// for instructions on how to set the API key.constapiKey=PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');functionmain(){constpayload={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?'},],},],};consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent';constoptions={method: 'POST',contentType: 'application/json',headers: {'x-goog-api-key': apiKey,},payload: JSON.stringify(payload)};constresponse=UrlFetchApp.fetch(url,options);constdata=JSON.parse(response);constcontent=data['candidates'][0]['content']['parts'][0]['text'];console.log(content);}
Streaming can also be used for multi-turn conversations.
Python
fromgoogleimportgenaiclient=genai.Client()
chat=client.chats.create(model="gemini-3.6-flash")
response=chat.send_message_stream("I have 2 dogs in my house.")
forchunkinresponse:
print(chunk.text, end="")
response=chat.send_message_stream("How many paws are in my house?")
forchunkinresponse:
print(chunk.text, end="")
formessageinchat.get_history():
print(f'role - {message.role}', end=": ")
print(message.parts[0].text)
JavaScript
import{GoogleGenAI}from"@google/genai";constai=newGoogleGenAI({});asyncfunctionmain(){constchat=ai.chats.create({model: "gemini-3.6-flash",history: [{role: "user",parts: [{text: "Hello"}],},{role: "model",parts: [{text: "Great to meet you. What would you like to know?"}],},],});conststream1=awaitchat.sendMessageStream({message: "I have 2 dogs in my house.",});forawait(constchunkofstream1){console.log(chunk.text);console.log("_".repeat(80));}conststream2=awaitchat.sendMessageStream({message: "How many paws are in my house?",});forawait(constchunkofstream2){console.log(chunk.text);console.log("_".repeat(80));}}awaitmain();
Go
package main
import (
"context""fmt""os""google.golang.org/genai"
)
funcmain() {
ctx:=context.Background()
client, err:=genai.NewClient(ctx, nil)
iferr!=nil {
log.Fatal(err)
}
history:= []*genai.Content{
genai.NewContentFromText("Hi nice to meet you! I have 2 dogs in my house.", genai.RoleUser),
genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),
}
chat, _:=client.Chats.Create(ctx, "gemini-3.6-flash", nil, history)
stream:=chat.SendMessageStream(ctx, genai.Part{Text: "How many paws are in my house?"})
forchunk, _:=rangestream {
part:=chunk.Candidates[0].Content.Parts[0]
fmt.Print(part.Text)
}
}
Java
importcom.google.genai.Chat;
importcom.google.genai.Client;
importcom.google.genai.ResponseStream;
importcom.google.genai.types.GenerateContentResponse;
publicclassMultiTurnConversationWithStreaming {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
ChatchatSession = client.chats.create("gemini-3.6-flash");
ResponseStream<GenerateContentResponse> responseStream =
chatSession.sendMessageStream("I have 2 dogs in my house.", null);
for (GenerateContentResponseresponse : responseStream) {
System.out.print(response.text());
}
responseStream = chatSession.sendMessageStream("How many paws are in my house?", null);
for (GenerateContentResponseresponse : responseStream) {
System.out.print(response.text());
}
// Get the history of the chat session. History is added after the stream// is consumed and includes the aggregated response from the stream.System.out.println("History: " + chatSession.getHistory(false));
}
}
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:streamGenerateContent?alt=sse \
-H "x-goog-api-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?" } ] } ] }'
Apps Script
// See https://developers.google.com/apps-script/guides/properties// for instructions on how to set the API key.constapiKey=PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');functionmain(){constpayload={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?'},],},],};consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:streamGenerateContent';constoptions={method: 'POST',contentType: 'application/json',headers: {'x-goog-api-key': apiKey,},payload: JSON.stringify(payload)};constresponse=UrlFetchApp.fetch(url,options);constdata=JSON.parse(response);constcontent=data['candidates'][0]['content']['parts'][0]['text'];console.log(content);}
This is the central endpoint for sending prompts to the model. There are two
endpoints for generating content, the key difference is how you receive the
response:
generateContent
(REST):
Receives a request and provides a
single response after the model has finished its entire generation.
streamGenerateContent
(SSE): Receives the exact same
request, but the model streams back chunks of the response as they are
generated. This provides a better user experience for interactive
applications as it lets you display partial results immediately.
Request body structure
The request body is a JSON object that is
identical for both standard and streaming modes and is built from a few core
objects:
Content object: Represents a single turn in a
conversation.
Part object: A piece of data within a Content turn
(like text or an image).
inline_data (Blob): A container for raw media bytes
and their MIME type.
At the highest level, the request body contains a contents object, which is a
list of Content objects, each representing turns in conversation. In most
cases, for basic text generation, you will have a single Content object, but
if you'd like to maintain conversation history, you can use multiple Content
objects.
The following shows a typical generateContent request body:
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{ "contents": [ { "role": "user", "parts": [ // A list of Part objects goes here ] }, { "role": "model", "parts": [ // A list of Part objects goes here ] } ] }'
Response body structure
The response body is similar for both
the streaming and standard modes except for the following:
At a high level, the response body contains a candidates object, which is a
list of Candidate objects. The Candidate object contains a Content
object that has the generated response returned from the model.
REST API Examples
Multimodal prompt (text and image)
To provide both text and an image in a prompt, the parts array should contain
two Part objects: one for the text, and one for the image inline_data.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{ "contents": [{ "parts":[ { "inline_data": { "mime_type":"image/jpeg", "data": "/9j/4AAQSkZJRgABAQ... (base64-encoded image)" } }, {"text": "What is in this picture?"}, ] }] }'
Multi-turn conversations (chat)
To build a conversation with multiple turns, you define the contents array
with multiple Content objects. The API will use this entire history as context
for the next response. The role for each Content object should alternate
between user and model.
Note: The client SDKs provide a chat interface that manages this list for you
automatically. When using the REST API, you are responsible for maintaining the
conversation history.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{ "contents": [ { "role": "user", "parts": [ { "text": "Hello." } ] }, { "role": "model", "parts": [ { "text": "Hello! How can I help you today?" } ] }, { "role": "user", "parts": [ { "text": "Please write a four-line poem about the ocean." } ] } ] }'
Key takeaways
Content is the envelope: It's the top-level container for a message turn,
whether it's from the user or the model.
Part enables multimodality: Use multiple Part objects within a single
Content
object to combine different types of data (text, image, video URI, etc.).
Choose your data method:
For small, directly embedded media (like most images), use a Part with
inline_data.
For larger files or files you want to reuse across requests, use the
File API to upload the file and reference it with a file_data part.
Manage conversation history: For chat applications using the REST API, build
the contents array by appending Content objects for each turn,
alternating between "user" and "model" roles. If you're using an SDK,
refer to the SDK documentation for the recommended way to manage
conversation history.
Response examples
The following examples show how these components come together for different
types of requests.
Text-only response
A default text response consists of a candidates array with one or more
content objects that contain the model's response.
The following is an example of a standard response:
{
"candidates": [
{
"content": {
"parts": [
{
"text": "At its core, Artificial Intelligence works by learning from vast amounts of data ..."
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 1
}
],
}
The following is series of streaming responses. Each response contains a
responseId that ties the full response together:
Live API offers a stateful WebSocket based API for bi-directional streaming to
enable real-time streaming use cases. You can review
Live API guide and the Live API reference
for more details.
Specialized models
In addition to the Gemini family of models, Gemini API offers endpoints for
specialized models such as Imagen,
Lyria and
embedding models. You can check out
these guides under the Models section.
Platform APIs
The rest of the endpoints enable additional capabilities to use with the main
endpoints described so far. Check out topics
Batch mode and
File API in the Guides section to learn more.
What's next
If you're just getting started, check out the following guides, which will help
you understand the Gemini API programming model:
The Gemini API supports content generation with images, audio, code, tools, and more. For details on each of these features, read on and check out the task-focused sample code, or read the comprehensive guides.
Generates a model response given an input GenerateContentRequest. Refer to the text generation guide for detailed usage information. Input capabilities differ between models, including tuned models. Refer to the model guide and tuning guide for details.
Endpoint
POST https://generativelanguage.googleapis.com/v1beta/{model=models/*}:generateContent
Path parameters
model | string
Required. The name of the Model to use for generating the completion.
Format: models/{model}. It takes the form models/{model}.
Request body
The request body contains data with the following structure:
Fields
contents[] | object (Content)
Required. The content of the current conversation with the model.
For single-turn queries, this is a single instance. For multi-turn queries like chat, this is a repeated field that contains the conversation history and the latest request.
Optional. A list of Tools the Model may use to generate the next response.
A Tool is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the Model. Supported Tools are Function and codeExecution. Refer to the Function calling and the Code execution guides to learn more.
Optional. A list of unique SafetySetting instances for blocking unsafe content.
This will be enforced on the GenerateContentRequest.contents and GenerateContentResponse.candidates. There should not be more than one setting for each SafetyCategory type. The API will block any contents and responses that fail to meet the thresholds set by these settings. This list overrides the default settings for each SafetyCategory specified in the safetySettings. If there is no SafetySetting for a given SafetyCategory provided in the list, the API will use the default safety setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY, HARM_CATEGORY_JAILBREAK are supported. Refer to the guide for detailed information on available safety settings. Also refer to the Safety guidance to learn how to incorporate safety considerations in your AI applications.
Optional. Configuration options for model generation and outputs.
cachedContent | string
Optional. The name of the content cached to use as context to serve the prediction. Format: cachedContents/{cachedContent}
serviceTier | enum (ServiceTier)
Optional. The service tier of the request.
store | boolean
Optional. Configures the logging behavior for a given request. If set, it takes precedence over the project-level logging config.
Example request
Text
Python
fromgoogleimportgenaiclient=genai.Client()
response=client.models.generateContent(
model="gemini-3.6-flash", contents="Write a story about a magic backpack."
)
print(response.text)
text_generation.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: "Write a story about a magic backpack.",});console.log(response.text);text_generation.js
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=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-3.6-flash", contents, nil)
iferr!=nil {
log.Fatal(err)
}
printResponse(response)
text_generation.go
Shell
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{ "contents": [{ "parts":[{"text": "Write a story about a magic backpack."}] }] }'2> /dev/null
text_generation.sh
Java
Clientclient = newClient();
GenerateContentResponseresponse =
client.models.generateContent(
"gemini-3.6-flash",
"Write a story about a magic backpack.",
null);
System.out.println(response.text());
TextGeneration.java
Image
Python
fromgoogleimportgenaiimportPIL.Imageclient=genai.Client()
organ=PIL.Image.open(media/"organ.jpg")
response=client.models.generate_content(
model="gemini-3.6-flash", contents=["Tell me about this instrument", organ]
)
print(response.text)
text_generation.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constorgan=awaitai.files.upload({file: path.join(media,"organ.jpg"),});constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: [createUserContent(["Tell me about this instrument",createPartFromUri(organ.uri,organ.mimeType)]),],});console.log(response.text);text_generation.js
# 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
text_generation.sh
Java
Clientclient = newClient();
Stringpath = media_path + "organ.jpg";
byte[] imageData = Files.readAllBytes(Paths.get(path));
Contentcontent =
Content.fromParts(
Part.fromText("Tell me about this instrument."),
Part.fromBytes(imageData, "image/jpeg"));
GenerateContentResponseresponse = client.models.generateContent("gemini-3.6-flash", content, null);
System.out.println(response.text());
TextGeneration.java
Audio
Python
fromgoogleimportgenaiclient=genai.Client()
sample_audio=client.files.upload(file=media/"sample.mp3")
response=client.models.generate_content(
model="gemini-3.6-flash",
contents=["Give me a summary of this audio file.", sample_audio],
)
print(response.text)
text_generation.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constaudio=awaitai.files.upload({file: path.join(media,"sample.mp3"),});constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: [createUserContent(["Give me a summary of this audio file.",createPartFromUri(audio.uri,audio.mimeType),]),],});console.log(response.text);text_generation.js
# 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
text_generation.sh
Video
Python
fromgoogleimportgenaiimporttimeclient=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).whilenotmyfile.stateormyfile.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-3.6-flash", contents=[myfile, "Describe this video clip"]
)
print(f"{response.text=}")
text_generation.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});letvideo=awaitai.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);awaitsleep(5000);video=awaitai.files.get({name: video.name});}constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: [createUserContent(["Describe this video clip",createPartFromUri(video.uri,video.mimeType),]),],});console.log(response.text);text_generation.js
# 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=$namewhile [[ "($state)"=*"PROCESSING"* ]];doecho"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
text_generation.sh
PDF
Python
fromgoogleimportgenaiclient=genai.Client()
sample_pdf=client.files.upload(file=media/"test.pdf")
response=client.models.generate_content(
model="gemini-3.6-flash",
contents=["Give me a summary of this document:", sample_pdf],
)
print(f"{response.text=}")
text_generation.py
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
text_generation.sh
Chat
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
# Pass initial history using the "history" argumentchat=client.chats.create(
model="gemini-3.6-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)
chat.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constchat=ai.chats.create({model: "gemini-3.6-flash",history: [{role: "user",parts: [{text: "Hello"}],},{role: "model",parts: [{text: "Great to meet you. What would you like to know?"}],},],});constresponse1=awaitchat.sendMessage({message: "I have 2 dogs in my house.",});console.log("Chat response 1:",response1.text);constresponse2=awaitchat.sendMessage({message: "How many paws are in my house?",});console.log("Chat response 2:",response2.text);chat.js
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=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-3.6-flash", nil, history)
iferr!=nil {
log.Fatal(err)
}
firstResp, err:=chat.SendMessage(ctx, genai.Part{Text: "I have 2 dogs in my house."})
iferr!=nil {
log.Fatal(err)
}
fmt.Println(firstResp.Text())
secondResp, err:=chat.SendMessage(ctx, genai.Part{Text: "How many paws are in my house?"})
iferr!=nil {
log.Fatal(err)
}
fmt.Println(secondResp.Text())
chat.go
Shell
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
-H 'Content-Type: application/json' \
-X POST \
-d '{ "contents": [ {"role":"user", "parts":[{ "text": "Hello"}]}, {"role": "model", "parts":[{ "text": "Great to meet you. What would you like to know?"}]}, {"role":"user", "parts":[{ "text": "I have two dogs in my house. How many paws are in my house?"}]}, ] }'2> /dev/null | grep "text"
chat.sh
Java
Clientclient = newClient();
ContentuserContent = Content.fromParts(Part.fromText("Hello"));
ContentmodelContent =
Content.builder()
.role("model")
.parts(
Collections.singletonList(
Part.fromText("Great to meet you. What would you like to know?")
)
).build();
Chatchat = client.chats.create(
"gemini-3.6-flash",
GenerateContentConfig.builder()
.systemInstruction(userContent)
.systemInstruction(modelContent)
.build()
);
GenerateContentResponseresponse1 = chat.sendMessage("I have 2 dogs in my house.");
System.out.println(response1.text());
GenerateContentResponseresponse2 = chat.sendMessage("How many paws are in my house?");
System.out.println(response2.text());
ChatSession.java
Cache
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
document=client.files.upload(file=media/"a11.txt")
model_name="gemini-3.6-flash"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)
cache.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constfilePath=path.join(media,"a11.txt");constdocument=awaitai.files.upload({file: filePath,config: {mimeType: "text/plain"},});console.log("Uploaded file name:",document.name);constmodelName="gemini-3.6-flash";constcontents=[createUserContent(createPartFromUri(document.uri,document.mimeType)),];constcache=awaitai.caches.create({model: modelName,config: {contents: contents,systemInstruction: "You are an expert analyzing transcripts.",},});console.log("Cache created:",cache);constresponse=awaitai.models.generateContent({model: modelName,contents: "Please summarize this transcript",config: {cachedContent: cache.name},});console.log("Response text:",response.text);cache.js
# With Gemini 2 we're launching a new SDK. See the following doc for details.# https://ai.google.dev/gemini-api/docs/migrateREADME.md
JSON Mode
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesfromtyping_extensionsimportTypedDictclassRecipe(TypedDict):
recipe_name: stringredients: list[str]
client=genai.Client()
result=client.models.generate_content(
model="gemini-3.6-flash",
contents="List a few popular cookie recipes.",
config=types.GenerateContentConfig(
response_mime_type="application/json", response_schema=list[Recipe]
),
)
print(result)
controlled_generation.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constresponse=awaitai.models.generateContent({model: "gemini-3.6-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);controlled_generation.js
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
response=client.models.generate_content(
model="gemini-3.6-flash",
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.forpartinresponse.candidates[0].content.parts:
print(part, "\n")
print("-"*80)
# The .text accessor concatenates the parts into a markdown-formatted text.print("\n", response.text)
code_execution.py
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=nil {
log.Fatal(err)
}
response, err:=client.Models.GenerateContent(
ctx,
"gemini-3.6-flash",
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{},
)
iferr!=nil {
log.Fatal(err)
}
// Print the response.printResponse(response)
fmt.Println("--------------------------------------------------------------------------------")
fmt.Println(response.Text())
code_execution.go
Java
Clientclient = newClient();
Stringprompt = """ 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. """;
GenerateContentResponseresponse =
client.models.generateContent(
"gemini-3.6-flash",
prompt,
null);
for (Partpart : response.candidates().get().getFirst().content().get().parts().get()) {
System.out.println(part + "\n");
}
System.out.println("-".repeat(80));
System.out.println(response.text());
CodeExecution.java
Function Calling
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
defadd(a: float, b: float) ->float:
"""returns a + b."""returna+bdefsubtract(a: float, b: float) ->float:
"""returns a - b."""returna-bdefmultiply(a: float, b: float) ->float:
"""returns a * b."""returna*bdefdivide(a: float, b: float) ->float:
"""returns a / b."""returna/b# Create a chat session; function calling (via tools) is enabled in the config.chat=client.chats.create(
model="gemini-3.6-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)
function_calling.py
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=nil {
log.Fatal(err)
}
modelName:="gemini-3.6-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)
iferr!=nil {
log.Fatal(err)
}
// Assume the response includes a list of function calls.iflen(genContentResp.FunctionCalls()) ==0 {
log.Println("No function call returned from the AI.")
returnnil
}
functionCall:=genContentResp.FunctionCalls()[0]
log.Printf("Function call: %+v\n", functionCall)
// Marshal the Args map into JSON bytes.argsMap, err:=json.Marshal(functionCall.Args)
iferr!=nil {
log.Fatal(err)
}
// Unmarshal the JSON bytes into the ArithmeticArgs struct.varargsArithmeticArgsiferr:=json.Unmarshal(argsMap, &args); err!=nil {
log.Fatal(err)
}
// Map the function name to the actual arithmetic function.varresultfloat64switchfunctionCall.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:
returnfmt.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{})
iferr!=nil {
log.Fatal(err)
}
printResponse(finalResponse)
function_calling.go
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});/** * The add function returns the sum of two numbers. * @param {number} a * @param {number} b * @returns {number} */functionadd(a,b){returna+b;}/** * The subtract function returns the difference (a - b). * @param {number} a * @param {number} b * @returns {number} */functionsubtract(a,b){returna-b;}/** * The multiply function returns the product of two numbers. * @param {number} a * @param {number} b * @returns {number} */functionmultiply(a,b){returna*b;}/** * The divide function returns the quotient of a divided by b. * @param {number} a * @param {number} b * @returns {number} */functiondivide(a,b){returna/b;}constaddDeclaration={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"],},};constsubtractDeclaration={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"],},};constmultiplyDeclaration={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"],},};constdivideDeclaration={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.constgenerateContentResponse=awaitai.models.generateContent({model: "gemini-3.6-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.constfunctionCall=generateContentResponse.functionCalls&&generateContentResponse.functionCalls[0];console.log(functionCall);// Parse the arguments.constargs=functionCall.args;// Expected args format: { firstParam: number, secondParam: number }// Step 3: Invoke the actual function based on the function name.constfunctionMapping={addNumbers: add,subtractNumbers: subtract,multiplyNumbers: multiply,divideNumbers: divide,};constfunc=functionMapping[functionCall.name];if(!func){console.error("Unimplemented error:",functionCall.name);returngenerateContentResponse;}constresultValue=func(args.firstParam,args.secondParam);console.log("Function result:",resultValue);// Step 4: Use the chat API to send the result as the final answer.constchat=ai.chats.create({model: "gemini-3.6-flash"});constchatResponse=awaitchat.sendMessage({message: "The final result is "+resultValue,});console.log(chatResponse.text);returnchatResponse;}function_calling.js
Shell
cat > tools.json <<EOF{ "function_declarations": [ { "name": "enable_lights", "description": "Turn on the lighting system." }, { "name": "set_light_color", "description": "Set the light color. Lights must be enabled for this to work.", "parameters": { "type": "object", "properties": { "rgb_hex": { "type": "string", "description": "The light color as a 6-digit hex string, e.g. ff0000 for red." } }, "required": [ "rgb_hex" ] } }, { "name": "stop_lights", "description": "Turn off the lighting system." } ]}EOF
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d @<(echo ' { "system_instruction": { "parts": { "text": "You are a helpful lighting system bot. You can turn lights on and off, and you can set the color. Do not perform any other tasks." } }, "tools": ['$(cat tools.json)'], "tool_config": { "function_calling_config": {"mode": "auto"} }, "contents": { "role": "user", "parts": { "text": "Turn on the lights please." } } }')2>/dev/null |sed -n '/"content"/,/"finishReason"/p'
function_calling.sh
Java
Clientclient = newClient();
FunctionDeclarationaddFunction =
FunctionDeclaration.builder()
.name("addNumbers")
.parameters(
Schema.builder()
.type("object")
.properties(Map.of(
"firstParam", Schema.builder().type("number").description("First number").build(),
"secondParam", Schema.builder().type("number").description("Second number").build()))
.required(Arrays.asList("firstParam", "secondParam"))
.build())
.build();
FunctionDeclarationsubtractFunction =
FunctionDeclaration.builder()
.name("subtractNumbers")
.parameters(
Schema.builder()
.type("object")
.properties(Map.of(
"firstParam", Schema.builder().type("number").description("First number").build(),
"secondParam", Schema.builder().type("number").description("Second number").build()))
.required(Arrays.asList("firstParam", "secondParam"))
.build())
.build();
FunctionDeclarationmultiplyFunction =
FunctionDeclaration.builder()
.name("multiplyNumbers")
.parameters(
Schema.builder()
.type("object")
.properties(Map.of(
"firstParam", Schema.builder().type("number").description("First number").build(),
"secondParam", Schema.builder().type("number").description("Second number").build()))
.required(Arrays.asList("firstParam", "secondParam"))
.build())
.build();
FunctionDeclarationdivideFunction =
FunctionDeclaration.builder()
.name("divideNumbers")
.parameters(
Schema.builder()
.type("object")
.properties(Map.of(
"firstParam", Schema.builder().type("number").description("First number").build(),
"secondParam", Schema.builder().type("number").description("Second number").build()))
.required(Arrays.asList("firstParam", "secondParam"))
.build())
.build();
GenerateContentConfigconfig = GenerateContentConfig.builder()
.toolConfig(ToolConfig.builder().functionCallingConfig(
FunctionCallingConfig.builder().mode("ANY").build()
).build())
.tools(
Collections.singletonList(
Tool.builder().functionDeclarations(
Arrays.asList(
addFunction,
subtractFunction,
divideFunction,
multiplyFunction
)
).build()
)
)
.build();
GenerateContentResponseresponse =
client.models.generateContent(
"gemini-3.6-flash",
"I have 57 cats, each owns 44 mittens, how many mittens is that in total?",
config);
if (response.functionCalls() == null || response.functionCalls().isEmpty()) {
System.err.println("No function call received");
returnnull;
}
varfunctionCall = response.functionCalls().getFirst();
StringfunctionName = functionCall.name().get();
vararguments = functionCall.args();
Map<String, BiFunction<Double, Double, Double>> functionMapping = newHashMap<>();
functionMapping.put("addNumbers", (a, b) -> a + b);
functionMapping.put("subtractNumbers", (a, b) -> a - b);
functionMapping.put("multiplyNumbers", (a, b) -> a * b);
functionMapping.put("divideNumbers", (a, b) -> b != 0 ? a / b : Double.NaN);
BiFunction<Double, Double, Double> function = functionMapping.get(functionName);
NumberfirstParam = (Number) arguments.get().get("firstParam");
NumbersecondParam = (Number) arguments.get().get("secondParam");
Doubleresult = function.apply(firstParam.doubleValue(), secondParam.doubleValue());
System.out.println(result);
FunctionCalling.java
Generation config
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
response=client.models.generate_content(
model="gemini-3.6-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)
configure_model_parameters.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: "Tell me a story about a magic backpack.",config: {candidateCount: 1,stopSequences: ["x"],maxOutputTokens: 20,temperature: 1.0,},});console.log(response.text);configure_model_parameters.js
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=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-3.6-flash",
genai.Text("Tell me a story about a magic backpack."),
&genai.GenerateContentConfig{
CandidateCount: candidateCount,
StopSequences: []string{"x"},
MaxOutputTokens: maxOutputTokens,
Temperature: &temperature,
},
)
iferr!=nil {
log.Fatal(err)
}
printResponse(response)
configure_model_parameters.go
Clientclient = newClient();
GenerateContentConfigconfig =
GenerateContentConfig.builder()
.candidateCount(1)
.stopSequences(List.of("x"))
.maxOutputTokens(20)
.temperature(1.0F)
.build();
GenerateContentResponseresponse =
client.models.generateContent(
"gemini-3.6-flash",
"Tell me a story about a magic backpack.",
config);
System.out.println(response.text());
ConfigureModelParameters.java
Safety Settings
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=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-3.6-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)
exceptException:
print("No information generated by the model.")
print(response.candidates[0].safety_ratings)
safety_settings.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constunsafePrompt="I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them including expletives.";constresponse=awaitai.models.generateContent({model: "gemini-3.6-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);returnresponse;}safety_settings.js
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=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-3.6-flash", contents, config)
iferr!=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.iflen(response.Candidates) >0 {
fmt.Println("Finish reason:", response.Candidates[0].FinishReason)
safetyRatings, err:=json.MarshalIndent(response.Candidates[0].SafetyRatings, "", " ")
iferr!=nil {
returnerr
}
fmt.Println("Safety ratings:", string(safetyRatings))
} else {
fmt.Println("No candidate returned.")
}
safety_settings.go
Shell
echo'{ "safetySettings": [ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"}, {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"} ], "contents": [{ "parts":[{ "text": "'I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them.'"}]}]}'> request.json
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d @request.json 2> /dev/null
safety_settings.sh
Java
Clientclient = newClient();
StringunsafePrompt = """ I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them including expletives. """;
GenerateContentConfigconfig =
GenerateContentConfig.builder()
.safetySettings(Arrays.asList(
SafetySetting.builder()
.category("HARM_CATEGORY_HATE_SPEECH")
.threshold("BLOCK_MEDIUM_AND_ABOVE")
.build(),
SafetySetting.builder()
.category("HARM_CATEGORY_HARASSMENT")
.threshold("BLOCK_ONLY_HIGH")
.build()
)).build();
GenerateContentResponseresponse =
client.models.generateContent(
"gemini-3.6-flash",
unsafePrompt,
config);
try {
System.out.println(response.text());
} catch (Exceptione) {
System.out.println("No information generated by the model");
}
System.out.println(response.candidates().get().getFirst().safetyRatings());
SafetySettings.java
System Instruction
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
response=client.models.generate_content(
model="gemini-3.6-flash",
contents="Good morning! How are you?",
config=types.GenerateContentConfig(
system_instruction="You are a cat. Your name is Neko."
),
)
print(response.text)
system_instruction.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constresponse=awaitai.models.generateContent({model: "gemini-3.6-flash",contents: "Good morning! How are you?",config: {systemInstruction: "You are a cat. Your name is Neko.",},});console.log(response.text);system_instruction.js
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=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-3.6-flash", contents, config)
iferr!=nil {
log.Fatal(err)
}
printResponse(response)
system_instruction.go
Shell
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "system_instruction": { "parts": { "text": "You are a cat. Your name is Neko."}}, "contents": { "parts": { "text": "Hello there"}}}'
system_instruction.sh
Java
Clientclient = newClient();
ParttextPart = Part.builder().text("You are a cat. Your name is Neko.").build();
Contentcontent = Content.builder().role("system").parts(ImmutableList.of(textPart)).build();
GenerateContentConfigconfig = GenerateContentConfig.builder()
.systemInstruction(content)
.build();
GenerateContentResponseresponse =
client.models.generateContent(
"gemini-3.6-flash",
"Good morning! How are you?",
config);
System.out.println(response.text());
SystemInstruction.java
Generates a streamed response from the model given an input GenerateContentRequest.
Endpoint
POST https://generativelanguage.googleapis.com/v1beta/{model=models/*}:streamGenerateContent
Path parameters
model | string
Required. The name of the Model to use for generating the completion.
Format: models/{model}. It takes the form models/{model}.
Request body
The request body contains data with the following structure:
Fields
contents[] | object (Content)
Required. The content of the current conversation with the model.
For single-turn queries, this is a single instance. For multi-turn queries like chat, this is a repeated field that contains the conversation history and the latest request.
Optional. A list of Tools the Model may use to generate the next response.
A Tool is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the Model. Supported Tools are Function and codeExecution. Refer to the Function calling and the Code execution guides to learn more.
Optional. A list of unique SafetySetting instances for blocking unsafe content.
This will be enforced on the GenerateContentRequest.contents and GenerateContentResponse.candidates. There should not be more than one setting for each SafetyCategory type. The API will block any contents and responses that fail to meet the thresholds set by these settings. This list overrides the default settings for each SafetyCategory specified in the safetySettings. If there is no SafetySetting for a given SafetyCategory provided in the list, the API will use the default safety setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY, HARM_CATEGORY_JAILBREAK are supported. Refer to the guide for detailed information on available safety settings. Also refer to the Safety guidance to learn how to incorporate safety considerations in your AI applications.
Optional. Configuration options for model generation and outputs.
cachedContent | string
Optional. The name of the content cached to use as context to serve the prediction. Format: cachedContents/{cachedContent}
serviceTier | enum (ServiceTier)
Optional. The service tier of the request.
store | boolean
Optional. Configures the logging behavior for a given request. If set, it takes precedence over the project-level logging config.
Example request
Text
Python
fromgoogleimportgenaiclient=genai.Client()
response=client.models.generate_content_stream(
model="gemini-3.6-flash", contents="Write a story about a magic backpack."
)
forchunkinresponse:
print(chunk.text)
print("_"*80)
text_generation.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constresponse=awaitai.models.generateContentStream({model: "gemini-3.6-flash",contents: "Write a story about a magic backpack.",});lettext="";forawait(constchunkofresponse){console.log(chunk.text);text+=chunk.text;}text_generation.js
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=nil {
log.Fatal(err)
}
contents:= []*genai.Content{
genai.NewContentFromText("Write a story about a magic backpack.", genai.RoleUser),
}
forresponse, err:=rangeclient.Models.GenerateContentStream(
ctx,
"gemini-3.6-flash",
contents,
nil,
) {
iferr!=nil {
log.Fatal(err)
}
fmt.Print(response.Candidates[0].Content.Parts[0].Text)
}
text_generation.go
Shell
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \
-H 'Content-Type: application/json' \
--no-buffer \
-d '{ "contents":[{"parts":[{"text": "Write a story about a magic backpack."}]}]}'
text_generation.sh
Java
Clientclient = newClient();
ResponseStream<GenerateContentResponse> responseStream =
client.models.generateContentStream(
"gemini-3.6-flash",
"Write a story about a magic backpack.",
null);
StringBuilderresponse = newStringBuilder();
for (GenerateContentResponseres : responseStream) {
System.out.print(res.text());
response.append(res.text());
}
responseStream.close();
TextGeneration.java
Image
Python
fromgoogleimportgenaiimportPIL.Imageclient=genai.Client()
organ=PIL.Image.open(media/"organ.jpg")
response=client.models.generate_content_stream(
model="gemini-3.6-flash", contents=["Tell me about this instrument", organ]
)
forchunkinresponse:
print(chunk.text)
print("_"*80)
text_generation.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constorgan=awaitai.files.upload({file: path.join(media,"organ.jpg"),});constresponse=awaitai.models.generateContentStream({model: "gemini-3.6-flash",contents: [createUserContent(["Tell me about this instrument",createPartFromUri(organ.uri,organ.mimeType)]),],});lettext="";forawait(constchunkofresponse){console.log(chunk.text);text+=chunk.text;}text_generation.js
fromgoogleimportgenaiclient=genai.Client()
sample_audio=client.files.upload(file=media/"sample.mp3")
response=client.models.generate_content_stream(
model="gemini-3.6-flash",
contents=["Give me a summary of this audio file.", sample_audio],
)
forchunkinresponse:
print(chunk.text)
print("_"*80)
text_generation.py
# 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
text_generation.sh
Video
Python
fromgoogleimportgenaiimporttimeclient=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).whilenotmyfile.stateormyfile.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-3.6-flash", contents=[myfile, "Describe this video clip"]
)
forchunkinresponse:
print(chunk.text)
print("_"*80)
text_generation.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});letvideo=awaitai.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);awaitsleep(5000);video=awaitai.files.get({name: video.name});}constresponse=awaitai.models.generateContentStream({model: "gemini-3.6-flash",contents: [createUserContent(["Describe this video clip",createPartFromUri(video.uri,video.mimeType),]),],});lettext="";forawait(constchunkofresponse){console.log(chunk.text);text+=chunk.text;}text_generation.js
# 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=$statewhile [[ "($state)"=*"PROCESSING"* ]];doecho"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
text_generation.sh
PDF
Python
fromgoogleimportgenaiclient=genai.Client()
sample_pdf=client.files.upload(file=media/"test.pdf")
response=client.models.generate_content_stream(
model="gemini-3.6-flash",
contents=["Give me a summary of this document:", sample_pdf],
)
forchunkinresponse:
print(chunk.text)
print("_"*80)
text_generation.py
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
text_generation.sh
Chat
Python
fromgoogleimportgenaifromgoogle.genaiimporttypesclient=genai.Client()
chat=client.chats.create(
model="gemini-3.6-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.")
forchunkinresponse:
print(chunk.text)
print("_"*80)
response=chat.send_message_stream(message="How many paws are in my house?")
forchunkinresponse:
print(chunk.text)
print("_"*80)
print(chat.get_history())
chat.py
Node.js
// Make sure to include the following import:// import {GoogleGenAI} from '@google/genai';constai=newGoogleGenAI({apiKey: process.env.GEMINI_API_KEY});constchat=ai.chats.create({model: "gemini-3.6-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:");conststream1=awaitchat.sendMessageStream({message: "I have 2 dogs in my house.",});forawait(constchunkofstream1){console.log(chunk.text);console.log("_".repeat(80));}console.log("Streaming response for second message:");conststream2=awaitchat.sendMessageStream({message: "How many paws are in my house?",});forawait(constchunkofstream2){console.log(chunk.text);console.log("_".repeat(80));}console.log(chat.getHistory());chat.js
Go
ctx:=context.Background()
client, err:=genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
iferr!=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-3.6-flash", nil, history)
iferr!=nil {
log.Fatal(err)
}
forchunk, err:=rangechat.SendMessageStream(ctx, genai.Part{Text: "I have 2 dogs in my house."}) {
iferr!=nil {
log.Fatal(err)
}
fmt.Println(chunk.Text())
fmt.Println(strings.Repeat("_", 64))
}
forchunk, err:=rangechat.SendMessageStream(ctx, genai.Part{Text: "How many paws are in my house?"}) {
iferr!=nil {
log.Fatal(err)
}
fmt.Println(chunk.Text())
fmt.Println(strings.Repeat("_", 64))
}
fmt.Println(chat.History(false))
chat.go
Shell
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \
-H 'Content-Type: application/json' \
-X POST \
-d '{ "contents": [ {"role":"user", "parts":[{ "text": "Hello"}]}, {"role": "model", "parts":[{ "text": "Great to meet you. What would you like to know?"}]}, {"role":"user", "parts":[{ "text": "I have two dogs in my house. How many paws are in my house?"}]}, ] }'2> /dev/null | grep "text"
chat.sh
Response from the model supporting multiple candidate responses.
Safety ratings and content filtering are reported for both prompt in GenerateContentResponse.prompt_feedback and for each candidate in finishReason and in safetyRatings. The API: - Returns either all requested candidates or none of them - Returns no candidates at all only if there was something wrong with the prompt (check promptFeedback) - Reports feedback on each candidate in finishReason and safetyRatings.
Prompt was blocked due to safety reasons. Inspect safetyRatings to understand which safety category blocked it.
OTHER
Prompt was blocked due to unknown reasons.
BLOCKLIST
Prompt was blocked due to the terms which are included from the terminology blocklist.
PROHIBITED_CONTENT
Prompt was blocked due to prohibited content.
IMAGE_SAFETY
Candidates blocked due to unsafe image generation content.
UsageMetadata
Metadata on the generation request's token usage.
Fields
promptTokenCount | integer
Number of tokens in the prompt. When cachedContent is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content.
cachedContentTokenCount | integer
Number of tokens in the cached part of the prompt (the cached content)
candidatesTokenCount | integer
Total number of tokens across all the generated response candidates.
toolUsePromptTokenCount | integer
Output only. Number of tokens present in tool-use prompt(s).
thoughtsTokenCount | integer
Output only. Number of tokens of thoughts for thinking models.
totalTokenCount | integer
Total token count for the generation request (prompt + thoughts + response candidates).
Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30".
Output only. Citation information for model-generated candidate.
This field may be populated with recitation information for any text included in the content. These are passages that are "recited" from copyrighted material in the foundational LLM's training data.
List of supporting references retrieved from specified grounding source. When streaming, this only contains the grounding chunks that have not been included in the grounding metadata of previous responses.
Metadata related to retrieval in the grounding flow.
googleMapsWidgetContextToken | string
Optional. Resource name of the Google Maps widget context token that can be used with the PlacesContextElement widget in order to render contextual data. Only populated in the case that grounding with Google Maps is enabled.
A GroundingChunk represents a segment of supporting evidence that grounds the model's response. It can be a chunk from the web, a retrieved context from a file, or information from Google Maps.
Fields
chunk_type
Chunk type. chunk_type can be only one of the following:
Collection of sources that provide answers about the features of a given place in Google Maps. Each PlaceAnswerSources message corresponds to a specific place in Google Maps. The Google Maps tool used these sources in order to answer questions about features of the place (e.g: "does Bar Foo have Wifi" or "is Foo Bar wheelchair accessible?"). Currently we only support review snippets as sources.
Optional. A list of indices (into 'grounding_chunk' in response.candidate.grounding_metadata) specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. If the response is streaming, the groundingChunkIndices refer to the indices across all responses. It is the client's responsibility to accumulate the grounding chunks from all responses (while maintaining the same order).
confidenceScores[] | number
Optional. Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. This list must have the same size as the groundingChunkIndices.
renderedParts[] | integer
Output only. Indices into the parts field of the candidate's content. These indices specify which rendered parts are associated with this support source.
Metadata related to retrieval in the grounding flow.
Fields
googleSearchDynamicRetrievalScore | number
Optional. Score indicating how likely information from google search could help answer the prompt. The score is in the range [0, 1], where 0 is the least likely and 1 is the most likely. This score is only populated when google search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger google search.
The safety rating contains the category of harm and the harm probability level in that category for a piece of content. Content is classified for safety across a number of harm categories and the probability of the harm classification is included here.
The agent's environment lives on the client connection: its built-in environment operations (filesystem ops and running commands) are yielded to the client to execute, instead of running in a server-managed sandbox. Mutually exclusive with remoteEnvironment. (Independent of any client-declared function tools, which are always executed on the client regardless of this field.)
Optional task mode for video generation. If not specified, the model automatically determines the appropriate mode based on the provided text prompt and input media.
A network egress rule that controls which external domains the environment is allowed to reach. Each rule identifies a target domain and, optionally, a set of HTTP headers to inject into every matching outbound request.
Fields
domain | string
The domain pattern to match for this rule. Use an exact hostname (e.g., github.com), a wildcard prefix (e.g., *.googleapis.com), or * to match all domains.
transform | map (key: string, value: string)
Headers to inject into requests matching this rule. Key: header name (e.g., "Authorization"). Value: header value (e.g., "Bearer your-token").
An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.
Configuration for an environment that lives on the client connection rather than in a server-managed sandbox.
When set (via Interaction.local_environment), the agent's filesystem and shell are treated as living on the client: the agent's built-in environment operations (e.g. reading/listing/editing files and running commands) are suspended on the server and yielded back to the client to execute, with their results returned on a subsequent turn. This is mutually exclusive with a server-managed EnvironmentConfig (remoteEnvironment), since the environment is either on the client or in a server sandbox, never both.
This governs only the agent's built-in environment. Client-declared function tools are always executed on the client regardless of this field.
Tool
A tool that can be used by the model.
Fields
type
The tool to use. type can be only one of the following:
A safety setting that affects the safety-blocking behavior.
A [SafetySetting][google.cloud.aiplatform.master.SafetySetting] consists of a harm [category][google.cloud.aiplatform.master.SafetySetting.category] and a [threshold][google.cloud.aiplatform.master.SafetySetting.threshold] for that category.
The Schema object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an OpenAPI 3.0 schema object.
Optional. The format of the data. Any value is allowed, but most do not trigger any special functionality.
title | string
Optional. The title of the schema.
description | string
Optional. A brief description of the parameter. This could contain examples of use. Parameter description may be formatted as Markdown.
nullable | boolean
Optional. Indicates if the value may be null.
enum[] | string
Optional. Possible values of the element of Type.STRING with enum format. For example we can define an Enum Direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]}
Optional. Default value of the field. Per JSON Schema, this field is intended for documentation generators and doesn't affect validation. Thus it's included here and ignored so that developers who send schemas with a default field don't get unknown-field errors.
Tool details that the model may use to generate response.
A Tool is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the model.
Optional. A list of FunctionDeclarations available to the model that can be used for function calling.
The model or system does not execute the function. Instead the defined function may be returned as a FunctionCall with arguments to the client side for execution. The model may decide to call a subset of these functions by populating FunctionCall in the response. The next conversation turn may contain a FunctionResponse with the Content.role "function" generation context for the next model turn.
Optional. Tool to support the model interacting directly with the computer. If enabled, it automatically populates computer-use specific Function Declarations.
Structured representation of a function declaration as defined by the OpenAPI 3.03 specification. Included in this declaration are the function name and parameters. This FunctionDeclaration is a representation of a block of code that can be used as a Tool by the model and executed by the client.
Fields
name | string
Required. The name of the function. Must be a-z, A-Z, 0-9, or contain underscores, colons, dots, and dashes, with a maximum length of 128.
Optional. Describes the parameters to this function. Reflects the Open API 3.03 Parameter Object string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter.
Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example:
Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function.
Defines the function behavior. Defaults to BLOCKING.
Enums
UNSPECIFIED
This value is unused.
BLOCKING
If set, the system will wait to receive the function response before continuing the conversation.
NON_BLOCKING
If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.
GoogleSearchRetrieval
Tool to retrieve public web data for grounding, powered by Google.
Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp end (exclusive).
The start must be less than or equal to the end. When the start equals the end, the interval is empty (matches no time). When both start and end are unspecified, the interval matches any time.
If specified, a Timestamp matching this interval will have to be the same or after the start.
Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30".
If specified, a Timestamp matching this interval will have to be before the end.
Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30".
JSON representation
{
"startTime": string,
"endTime": string
}
SearchTypes
Different types of search that can be enabled on the GoogleSearch tool.
Optional. By default, predefined functions are included in the final model call. Some of them can be explicitly excluded from being automatically included. This can serve two purposes: 1. Using a more restricted / different action space. 2. Improving the definitions / instructions of predefined functions.
enablePromptInjectionDetection | boolean
Optional. Whether enable the prompt injection detection check on computer-use request.
Represents the environment being operated, such as a web browser.
Enums
ENVIRONMENT_UNSPECIFIED
Defaults to browser.
ENVIRONMENT_BROWSER
Operates in a web browser.
ENVIRONMENT_MOBILE
Operates in a mobile environment.
ENVIRONMENT_DESKTOP
Operates in a desktop environment.
SafetyPolicy
Predefined safety policies for computer use.
Enums
SAFETY_POLICY_UNSPECIFIED
Unspecified safety policy.
FINANCIAL_TRANSACTIONS
Safety policy for financial transactions.
SENSITIVE_DATA_MODIFICATION
Safety policy for sensitive data modification.
COMMUNICATION_TOOL
Safety policy for communication tools (e.g. Gmail, Chat, Meet).
ACCOUNT_CREATION
Safety policy for account creation.
DATA_MODIFICATION
Safety policy for data modification.
USER_CONSENT_MANAGEMENT
Safety policy for user consent management.
LEGAL_TERMS_AND_AGREEMENTS
Safety policy for legal terms and agreements.
UrlContext
This type has no fields.
Tool to support URL context retrieval.
FileSearch
The FileSearch tool that retrieves knowledge from Semantic Retrieval corpora. Files are imported to Semantic Retrieval corpora using the ImportFile API.
Fields
fileSearchStoreNames[] | string
Required. The names of the fileSearchStores to retrieve from. Example: fileSearchStores/my-file-search-store-123
metadataFilter | string
Optional. Metadata filter to apply to the semantic retrieval documents and chunks.
topK | integer
Optional. The number of semantic retrieval chunks to retrieve.
The GoogleMaps Tool that provides geospatial context for the user's query.
Fields
enableWidget | boolean
Optional. Whether to return a widget context token in the GroundingMetadata of the response. Developers can use the widget context token to render a Google Maps widget with geospatial context related to the places that the model references in the response.
Value represents a dynamically typed value which can be either null, a number, a string, a boolean, a recursive struct value, or a list of values. A producer of value is expected to set one of these variants. Absence of any variant indicates an error.
Fields
kind
The kind of value. kind can be only one of the following:
Enum for visualization mode. Eventually we will support an interactive mode where the user can choose whether to include HTML visualizations in the response.
Enums
UNSPECIFIED
The default visualization mode. Will default to AUTO.
Optional. Input only. Immutable. An optional time after which, when using the resulting token, messages in BidiGenerateContent sessions will be rejected. (Gemini may preemptively close the session after this time.)
If not set then this defaults to 30 minutes in the future. If set, this value must be less than 20 hours in the future.
Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30".
Optional. Input only. Immutable. The time after which new Live API sessions using the token resulting from this request will be rejected.
If not set this defaults to 60 seconds in the future. If set, this value must be less than 20 hours in the future.
Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30".
Optional. Input only. Immutable. If fieldMask is empty, and bidiGenerateContentSetup is not present, then the effective BidiGenerateContentSetup message is taken from the Live API connection.
If fieldMask is empty, and bidiGenerateContentSetupis present, then the effective BidiGenerateContentSetup message is taken entirely from bidiGenerateContentSetup in this request. The setup message from the Live API connection is ignored.
If fieldMask is not empty, then the corresponding fields from bidiGenerateContentSetup will overwrite the fields from the setup message in the Live API connection.
This is a comma-separated list of fully qualified names of fields. Example: "user.displayName,photo".
config
The method-specific configuration for the resulting token. config can be only one of the following:
Optional. Input only. Immutable. Configuration specific to BidiGenerateContent.
uses | integer
Optional. Input only. Immutable. The number of times the token can be used. If this value is zero then no limit is applied. Resuming a Live API session does not count as a use. If unspecified, the default is 1.
Message to be sent in the first (and only in the first) BidiGenerateContentClientMessage. Contains configuration that will apply for the duration of the streaming RPC.
Clients should wait for a BidiGenerateContentSetupComplete message before sending any additional messages.
Fields
model | string
Required. The model's resource name. This serves as an ID for the Model to use.
Optional. A list of Tools the model may use to generate the next response.
A Tool is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the model.
Optional. If set, enables transcription of the model's audio output. The transcription aligns with the language code specified for the output audio, if configured.
Configuration options for model generation and outputs. Not all parameters are configurable for every model.
Fields
stopSequences[] | string
Optional. The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop at the first appearance of a stop_sequence. The stop sequence will not be included as part of the response.
responseMimeType | string
Optional. MIME type of the generated candidate text. Supported MIME types are: text/plain: (default) Text output. application/json: JSON response in the response candidates. text/x.enum: ENUM as a string response in the response candidates. Refer to the docs for a list of all supported text MIME types.
Optional. Output schema of the generated candidate text. Schemas must be a subset of the OpenAPI schema and can be objects, primitives or arrays.
If set, a compatible responseMimeType must also be set. Compatible MIME types: application/json: Schema for JSON response. Refer to the JSON text generation guide for more details.
_responseJsonSchema (deprecated) | value (Value format)
This item is deprecated!
Optional. Output schema of the generated response. This is an alternative to responseSchema that accepts JSON Schema.
If set, responseSchema must be omitted, but responseMimeType is required.
While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported:
$id
$defs
$ref
$anchor
type
format
title
description
enum (for strings and numbers)
items
prefixItems
minItems
maxItems
minimum
maximum
anyOf
oneOf (interpreted the same as anyOf)
properties
additionalProperties
required
The non-standard propertyOrdering property may also be set.
Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If $ref is set on a sub-schema, no other properties, except for than those starting as a $, may be set.
Optional. The requested modalities of the response. Represents the set of modalities that the model can return, and should be expected in the response. This is an exact match to the modalities of the response.
A model may have multiple combinations of supported modalities. If the requested modalities do not match any of the supported combinations, an error will be returned.
An empty list is equivalent to requesting only text.
candidateCount | integer
Optional. Number of generated responses to return. If unset, this will default to 1. Please note that this doesn't work for previous generation models (Gemini 1.0 family)
maxOutputTokens | integer
Optional. The maximum number of tokens to include in a response candidate.
Note: The default value varies by model, see the Model.output_token_limit attribute of the Model returned from the getModel function.
temperature | number
Optional. Controls the randomness of the output.
Note: The default value varies by model, see the Model.temperature attribute of the Model returned from the getModel function.
Values can range from [0.0, 2.0].
topP | number
Optional. The maximum cumulative probability of tokens to consider when sampling.
The model uses combined Top-k and Top-p (nucleus) sampling.
Tokens are sorted based on their assigned probabilities so that only the most likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while Nucleus sampling limits the number of tokens based on the cumulative probability.
Note: The default value varies by Model and is specified by theModel.top_p attribute returned from the getModel function. An empty topK attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.
topK | integer
Optional. The maximum number of tokens to consider when sampling.
Gemini models use Top-p (nucleus) sampling or a combination of Top-k and nucleus sampling. Top-k sampling considers the set of topK most probable tokens. Models running with nucleus sampling don't allow topK setting.
Note: The default value varies by Model and is specified by theModel.top_p attribute returned from the getModel function. An empty topK attribute indicates that the model doesn't apply top-k sampling and doesn't allow setting topK on requests.
seed | integer
Optional. Seed used in decoding. If not set, the request uses a randomly generated seed.
presencePenalty | number
Optional. Presence penalty applied to the next token's logprobs if the token has already been seen in the response.
This penalty is binary on/off and not dependant on the number of times the token is used (after the first). Use frequencyPenalty for a penalty that increases with each use.
A positive penalty will discourage the use of tokens that have already been used in the response, increasing the vocabulary.
A negative penalty will encourage the use of tokens that have already been used in the response, decreasing the vocabulary.
frequencyPenalty | number
Optional. Frequency penalty applied to the next token's logprobs, multiplied by the number of times each token has been seen in the respponse so far.
A positive penalty will discourage the use of tokens that have already been used, proportional to the number of times the token has been used: The more a token is used, the more difficult it is for the model to use that token again increasing the vocabulary of responses.
Caution: A negative penalty will encourage the model to reuse tokens proportional to the number of times the token has been used. Small negative values will reduce the vocabulary of a response. Larger negative values will cause the model to start repeating a common token until it hits the maxOutputTokens limit.
responseLogprobs | boolean
Optional. If true, export the logprobs results in response.
logprobs | integer
Optional. Only valid if responseLogprobs=True. This sets the number of top logprobs, including the chosen candidate, to return at each decoding step in the Candidate.logprobs_result. The number must be in the range of [0, 20].
enableEnhancedCivicAnswers | boolean
Optional. Enables enhanced civic answers. It may not be available for all models.
Optional. Controls the maximum depth of the model's internal reasoning process before it produces a response. The default value is model-dependent. Refer to the Thinking levels guide for more details. Recommended for Gemini 3 or later models. Use with earlier models results in an error.
Allow user to specify how much to think using enum instead of integer budget.
Enums
THINKING_LEVEL_UNSPECIFIED
Default value.
MINIMAL
Little to no thinking.
LOW
Low thinking level.
MEDIUM
Medium thinking level.
HIGH
High thinking level.
ImageConfig
Config for image generation features.
Fields
aspectRatio | string
Optional. The aspect ratio of the image to generate. Supported aspect ratios: 1:1, 1:4, 4:1, 1:8, 8:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, or 21:9.
If not specified, the model will choose a default aspect ratio based on any reference images provided.
imageSize | string
Optional. Specifies the size of generated images. Supported values are 512, 1K, 2K, 4K. If not specified, the model will use default value 1K.
JSON representation
{
"aspectRatio": string,
"imageSize": string
}
MediaResolution
Media resolution for the input media.
Enums
MEDIA_RESOLUTION_UNSPECIFIED
Media resolution has not been set.
MEDIA_RESOLUTION_LOW
Media resolution set to low (64 tokens).
MEDIA_RESOLUTION_MEDIUM
Media resolution set to medium (256 tokens).
MEDIA_RESOLUTION_HIGH
Media resolution set to high (zoomed reframing with 256 tokens).
ResponseFormatConfig
Configuration for the response output format. This is a flat object where each optional sub-field configures a specific output modality.
Required. The target language for translation. Supported values are BCP-47 language codes (e.g. "en", "es", "fr").
echoTargetLanguage | boolean
Optional. If true, the model will generate audio when the target language is spoken, essentially it will parrot the input. If false, we will not produce audio for the target language.
Optional. If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals.
Optional. Determines how likely speech is to be detected.
prefixPaddingMs | integer
Optional. The required duration of detected speech before start-of-speech is committed. The lower this value, the more sensitive the start-of-speech detection is and shorter speech can be recognized. However, this also increases the probability of false positives.
Optional. Determines how likely detected speech is ended.
silenceDurationMs | integer
Optional. The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency.
Automatic detection will detect the start of speech more often.
START_SENSITIVITY_LOW
Automatic detection will detect the start of speech less often.
EndSensitivity
Determines how end of speech is detected.
Enums
END_SENSITIVITY_UNSPECIFIED
The default is END_SENSITIVITY_HIGH.
END_SENSITIVITY_HIGH
Automatic detection ends speech more often.
END_SENSITIVITY_LOW
Automatic detection ends speech less often.
ActivityHandling
The different ways of handling user activity.
Enums
ACTIVITY_HANDLING_UNSPECIFIED
If unspecified, the default behavior is START_OF_ACTIVITY_INTERRUPTS.
START_OF_ACTIVITY_INTERRUPTS
If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.
NO_INTERRUPTION
The model's response will not be interrupted.
TurnCoverage
Options about which input is included in the user's turn.
Enums
TURN_COVERAGE_UNSPECIFIED
If unspecified, a default behavior is selected based on the model. E.g., for Gemini 2.5, the default is TURN_INCLUDES_ONLY_ACTIVITY, while for Gemini 3.1 and onwards, it's TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO.
TURN_INCLUDES_ONLY_ACTIVITY
Includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream).
TURN_INCLUDES_ALL_INPUT
Includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).
TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO
Includes audio activity and all video since the last turn. With automatic activity detection, audio activity means speech and excludes silence.
SessionResumptionConfig
Session resumption configuration.
This message is included in the session configuration as BidiGenerateContentSetup.session_resumption. If configured, the server will send SessionResumptionUpdate messages.
Fields
handle | string
The handle of a previous session. If not present then a new session is created.
Session handles come from SessionResumptionUpdate.token values in previous connections.
JSON representation
{
"handle": string
}
ContextWindowCompressionConfig
Enables context window compression — a mechanism for managing the model's context window so that it does not exceed a given length.
Fields
compression_mechanism
The context window compression mechanism used. compression_mechanism can be only one of the following:
The number of tokens (before running a turn) required to trigger a context window compression.
This can be used to balance quality against latency as shorter context windows may result in faster model responses. However, any compression operation will cause a temporary latency increase, so they should not be triggered frequently.
If not set, the default is 80% of the model's context window limit. This leaves 20% for the next user request/model response.
JSON representation
{
// compression_mechanism
"slidingWindow": {
object (SlidingWindow)
}
// Union type
"triggerTokens": string
}
SlidingWindow
The SlidingWindow method operates by discarding content at the beginning of the context window. The resulting context will always begin at the start of a USER role turn. System instructions and any BidiGenerateContentSetup.prefix_turns will always remain at the beginning of the result.
The target number of tokens to keep. The default value is triggerTokens/2.
Discarding parts of the context window causes a temporary latency increase so this value should be calibrated to avoid frequent compression operations.
JSON representation
{
"targetTokens": string
}
AudioTranscriptionConfig
The audio transcription configuration.
Fields
adaptationPhrases[] (deprecated) | string
This item is deprecated!
Optional. A list of phrases used for speech adaptation, which biases the ASR model to improve recognition of these specific terms.
customVocabulary[] | string
Optional. A list of custom vocabulary phrases to bias the speech recognition model toward recognizing specific terms (product names, proper nouns, jargon).
language_config
The language config for the audio transcription. For ASR models, it is required, an error will be returned if not set. language_config can be only one of the following:
Indicates the language of the audio should be automatically detected.
LanguageHints
Provides hints to the model about possible languages present in the audio.
Fields
languageCodes[] | string
Required. BCP-47 language codes.
JSON representation
{
"languageCodes": [
string
]
}
HistoryConfig
History configuration.
This message is included in the session configuration as BidiGenerateContentSetup.history_config. Configures the exchange of history messages.
Fields
initialHistoryInClientContent | boolean
Optional. If true, after sending setupComplete, the server will wait and at first process clientContent messages until turnComplete is true. This initial history will not trigger a model call and may end with role MODEL. After turnComplete is true, the client can start the realtime conversation via realtimeInput.
Optional. Input only. Immutable. An optional time after which, when using the resulting token, messages in BidiGenerateContent sessions will be rejected. (Gemini may preemptively close the session after this time.)
If not set then this defaults to 30 minutes in the future. If set, this value must be less than 20 hours in the future.
Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30".
Optional. Input only. Immutable. The time after which new Live API sessions using the token resulting from this request will be rejected.
If not set this defaults to 60 seconds in the future. If set, this value must be less than 20 hours in the future.
Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30".
Optional. Input only. Immutable. If fieldMask is empty, and bidiGenerateContentSetup is not present, then the effective BidiGenerateContentSetup message is taken from the Live API connection.
If fieldMask is empty, and bidiGenerateContentSetupis present, then the effective BidiGenerateContentSetup message is taken entirely from bidiGenerateContentSetup in this request. The setup message from the Live API connection is ignored.
If fieldMask is not empty, then the corresponding fields from bidiGenerateContentSetup will overwrite the fields from the setup message in the Live API connection.
This is a comma-separated list of fully qualified names of fields. Example: "user.displayName,photo".
config
The method-specific configuration for the resulting token. config can be only one of the following:
Optional. Input only. Immutable. Configuration specific to BidiGenerateContent.
uses | integer
Optional. Input only. Immutable. The number of times the token can be used. If this value is zero then no limit is applied. Resuming a Live API session does not count as a use. If unspecified, the default is 1.
Response body
If successful, the response body contains a newly created instance of AuthToken.