Text generation
The Gemini API can generate text output from various inputs, including text, images, video, and audio.
Here's a basic example that takes a single text input:
Python
fromgoogleimport genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="How does AI work?"
)
print(response.text)
JavaScript
import{GoogleGenAI}from"@google/genai";
constai=newGoogleGenAI({});
asyncfunctionmain(){
constresponse=awaitai.models.generateContent({
model:"gemini-2.5-flash",
contents:"How does AI work?",
});
console.log(response.text);
}
awaitmain();
Go
packagemain
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-2.5-flash",
genai.Text("Explain how AI works in a few words"),
nil,
)
fmt.Println(result.Text())
}
Java
importcom.google.genai.Client;
importcom.google.genai.types.GenerateContentResponse;
publicclass GenerateContentWithTextInput{
publicstaticvoidmain(String[]args){
Clientclient=newClient();
GenerateContentResponseresponse=
client.models.generateContent("gemini-2.5-flash","How does AI work?",null);
System.out.println(response.text());
}
}
REST
curl"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"\
-H"x-goog-api-key: $GEMINI_API_KEY"\
-H'Content-Type: application/json'\
-XPOST\
-d'{
"contents": [
{
"parts": [
{
"text": "How does AI work?"
}
]
}
]
}'
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:[
{
parts:[
{text:'How AI does work?'},
],
},
],
};
consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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
fromgoogleimport genai
fromgoogle.genaiimport types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="How does AI work?",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(thinking_budget=0) # Disables thinking
),
)
print(response.text)
JavaScript
import{GoogleGenAI}from"@google/genai";
constai=newGoogleGenAI({});
asyncfunctionmain(){
constresponse=awaitai.models.generateContent({
model:"gemini-2.5-flash",
contents:"How does AI work?",
config:{
thinkingConfig:{
thinkingBudget:0,// Disables thinking
},
}
});
console.log(response.text);
}
awaitmain();
Go
packagemain
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-2.5-flash",
genai.Text("How does AI work?"),
&genai.GenerateContentConfig{
ThinkingConfig:&genai.ThinkingConfig{
ThinkingBudget:int32(0),// Disables thinking
},
}
)
fmt.Println(result.Text())
}
Java
importcom.google.genai.Client;
importcom.google.genai.types.GenerateContentConfig;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.ThinkingConfig;
publicclass GenerateContentWithThinkingConfig{
publicstaticvoidmain(String[]args){
Clientclient=newClient();
GenerateContentConfigconfig=
GenerateContentConfig.builder()
// Disables thinking
.thinkingConfig(ThinkingConfig.builder().thinkingBudget(0))
.build();
GenerateContentResponseresponse=
client.models.generateContent("gemini-2.5-flash","How does AI work?",config);
System.out.println(response.text());
}
}
REST
curl"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"\
-H"x-goog-api-key: $GEMINI_API_KEY"\
-H'Content-Type: application/json'\
-XPOST\
-d'{
"contents": [
{
"parts": [
{
"text": "How does AI work?"
}
]
}
],
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 0
}
}
}'
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:[
{
parts:[
{text:'How AI does work?'},
],
},
],
};
consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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
fromgoogleimport genai
fromgoogle.genaiimport types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-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-2.5-flash",
contents:"Hello there",
config:{
systemInstruction:"You are a cat. Your name is Neko.",
},
});
console.log(response.text);
}
awaitmain();
Go
packagemain
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-2.5-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;
publicclass GenerateContentWithSystemInstruction{
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-2.5-flash","Hello there",config);
System.out.println(response.text());
}
}
REST
curl"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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-2.5-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 GenerateContentConfig
object also lets you override default generation parameters, such as
temperature.
Python
fromgoogleimport genai
fromgoogle.genaiimport types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=["Explain how AI works"],
config=types.GenerateContentConfig(
temperature=0.1
)
)
print(response.text)
JavaScript
import{GoogleGenAI}from"@google/genai";
constai=newGoogleGenAI({});
asyncfunctionmain(){
constresponse=awaitai.models.generateContent({
model:"gemini-2.5-flash",
contents:"Explain how AI works",
config:{
temperature:0.1,
},
});
console.log(response.text);
}
awaitmain();
Go
packagemain
import(
"context"
"fmt"
"os"
"google.golang.org/genai"
)
funcmain(){
ctx:=context.Background()
client,err:=genai.NewClient(ctx,nil)
iferr!=nil{
log.Fatal(err)
}
temp:=float32(0.9)
topP:=float32(0.5)
topK:=float32(20.0)
config:=&genai.GenerateContentConfig{
Temperature:&temp,
TopP:&topP,
TopK:&topK,
ResponseMIMEType:"application/json",
}
result,_:=client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
genai.Text("What is the average size of a swallow?"),
config,
)
fmt.Println(result.Text())
}
Java
importcom.google.genai.Client;
importcom.google.genai.types.GenerateContentConfig;
importcom.google.genai.types.GenerateContentResponse;
publicclass GenerateContentWithConfig{
publicstaticvoidmain(String[]args){
Clientclient=newClient();
GenerateContentConfigconfig=GenerateContentConfig.builder().temperature(0.1f).build();
GenerateContentResponseresponse=
client.models.generateContent("gemini-2.5-flash","Explain how AI works",config);
System.out.println(response.text());
}
}
REST
curlhttps://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent\
-H"x-goog-api-key: $GEMINI_API_KEY"\
-H'Content-Type: application/json'\
-XPOST\
-d'{
"contents": [
{
"parts": [
{
"text": "Explain how AI works"
}
]
}
],
"generationConfig": {
"stopSequences": [
"Title"
],
"temperature": 1.0,
"topP": 0.8,
"topK": 10
}
}'
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(){
constgenerationConfig={
temperature:1,
topP:0.95,
topK:40,
responseMimeType:'text/plain',
};
constpayload={
generationConfig,
contents:[
{
parts:[
{text:'Explain how AI works in a few words'},
],
},
],
};
consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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
fromPILimport Image
fromgoogleimport genai
client = genai.Client()
image = Image.open("/path/to/organ.png")
response = client.models.generate_content(
model="gemini-2.5-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-2.5-flash",
contents:[
createUserContent([
"Tell me about this instrument",
createPartFromUri(image.uri,image.mimeType),
]),
],
});
console.log(response.text);
}
awaitmain();
Go
packagemain
import(
"context"
"fmt"
"os"
"google.golang.org/genai"
)
funcmain(){
ctx:=context.Background()
client,err:=genai.NewClient(ctx,nil)
iferr!=nil{
log.Fatal(err)
}
imagePath:="/path/to/organ.jpg"
imgData,_:=os.ReadFile(imagePath)
parts:=[]*genai.Part{
genai.NewPartFromText("Tell me about this instrument"),
&genai.Part{
InlineData:&genai.Blob{
MIMEType:"image/jpeg",
Data:imgData,
},
},
}
contents:=[]*genai.Content{
genai.NewContentFromParts(parts,genai.RoleUser),
}
result,_:=client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
contents,
nil,
)
fmt.Println(result.Text())
}
Java
importcom.google.genai.Client;
importcom.google.genai.Content;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.Part;
publicclass GenerateContentWithMultiModalInputs{
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-2.5-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-2.5-flash:generateContent"\
-H"x-goog-api-key: $GEMINI_API_KEY"\
-H'Content-Type: application/json'\
-XPOST\
-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='http://image/url';
constimage=getImageData(imageUrl);
constpayload={
contents:[
{
parts:[
{image},
{text:'Tell me about this instrument'},
],
},
],
};
consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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
fromgoogleimport genai
client = genai.Client()
response = client.models.generate_content_stream(
model="gemini-2.5-flash",
contents=["Explain how AI works"]
)
for chunk in response:
print(chunk.text, end="")
JavaScript
import{GoogleGenAI}from"@google/genai";
constai=newGoogleGenAI({});
asyncfunctionmain(){
constresponse=awaitai.models.generateContentStream({
model:"gemini-2.5-flash",
contents:"Explain how AI works",
});
forawait(constchunkofresponse){
console.log(chunk.text);
}
}
awaitmain();
Go
packagemain
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-2.5-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;
publicclass GenerateContentStream{
publicstaticvoidmain(String[]args){
Clientclient=newClient();
ResponseStream<GenerateContentResponse>responseStream=
client.models.generateContentStream(
"gemini-2.5-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();
}
}
REST
curl"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"\
-H"x-goog-api-key: $GEMINI_API_KEY"\
-H'Content-Type: application/json'\
--no-buffer\
-d'{
"contents": [
{
"parts": [
{
"text": "Explain how AI works"
}
]
}
]
}'
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:[
{
parts:[
{text:'Explain how AI works'},
],
},
],
};
consturl='https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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.
Python
fromgoogleimport genai
client = genai.Client()
chat = client.chats.create(model="gemini-2.5-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)
for message in chat.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-2.5-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
packagemain
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-2.5-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;
publicclass MultiTurnConversation{
publicstaticvoidmain(String[]args){
Clientclient=newClient();
ChatchatSession=client.chats.create("gemini-2.5-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
curlhttps://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent\
-H"x-goog-api-key: $GEMINI_API_KEY"\
-H'Content-Type: application/json'\
-XPOST\
-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-2.5-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
fromgoogleimport genai
client = genai.Client()
chat = client.chats.create(model="gemini-2.5-flash")
response = chat.send_message_stream("I have 2 dogs in my house.")
for chunk in response:
print(chunk.text, end="")
response = chat.send_message_stream("How many paws are in my house?")
for chunk in response:
print(chunk.text, end="")
for message in chat.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-2.5-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
packagemain
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-2.5-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;
publicclass MultiTurnConversationWithStreaming{
publicstaticvoidmain(String[]args){
Clientclient=newClient();
ChatchatSession=client.chats.create("gemini-2.5-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
curlhttps://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse\
-H"x-goog-api-key: $GEMINI_API_KEY"\
-H'Content-Type: application/json'\
-XPOST\
-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-2.5-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);
}
Prompting tips
Consult our prompt engineering guide for suggestions on getting the most out of Gemini.
What's next
- Try Gemini in Google AI Studio.
- Experiment with structured outputs for JSON-like responses.
- Explore Gemini's image, video, audio and document understanding capabilities.
- Learn about multimodal file prompting strategies.