Repository Public
1The Gemini API can generate text output from text, images, video, and audio2inputs.34Here's a basic example:56### Python78 from google import genai910 client = genai.Client()1112 response = client.models.generate_content(13 model="gemini-3.8-flash",14 contents="How does AI work?"15 )16 print(response.text)1718### JavaScript1920 import { GoogleGenAI } from "@google/genai";2122 const ai = new GoogleGenAI({});2324 async function main() {25 const response = await ai.models.generateContent({26 model: "gemini-3.8-flash",27 contents: "How does AI work?",28 });29 console.log(response.text);30 }3132 await main();3334### Go3536 package main3738 import (39 "context"40 "fmt"41 "os"42 "google.golang.org/genai"43 )4445 func main() {4647 ctx := context.Background()48 client, err := genai.NewClient(ctx, nil)49 if err != nil {50 log.Fatal(err)51 }5253 result, _ := client.Models.GenerateContent(54 ctx,55 "gemini-3.8-flash",56 genai.Text("Explain how AI works in a few words"),57 nil,58 )5960 fmt.Println(result.Text())61 }6263### Java6465 import com.google.genai.Client;66 import com.google.genai.types.GenerateContentResponse;6768 public class GenerateContentWithTextInput {69 public static void main(String[] args) {7071 Client client = new Client();7273 GenerateContentResponse response =74 client.models.generateContent("gemini-3.8-flash", "How does AI work?", null);7576 System.out.println(response.text());77 }78 }7980### REST8182 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \83 -H "x-goog-api-key: $GEMINI_API_KEY" \84 -H 'Content-Type: application/json' \85 -X POST \86 -d '{87 "contents": [88 {89 "parts": [90 {91 "text": "How does AI work?"92 }93 ]94 }95 ]96 }'9798### Apps Script99100 // See https://developers.google.com/apps-script/guides/properties101 // for instructions on how to set the API key.102 const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');103104 function main() {105 const payload = {106 contents: [107 {108 parts: [109 { text: 'How AI does work?' },110 ],111 },112 ],113 };114115 const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent';116 const options = {117 method: 'POST',118 contentType: 'application/json',119 headers: {120 'x-goog-api-key': apiKey,121 },122 payload: JSON.stringify(payload)123 };124125 const response = UrlFetchApp.fetch(url, options);126 const data = JSON.parse(response);127 const content = data['candidates'][0]['content']['parts'][0]['text'];128 console.log(content);129 }130131## Thinking with Gemini132133Gemini models often have ["thinking"](https://ai.google.dev/gemini-api/docs/thinking) enabled by default134which allows the model to reason before responding to a request.135136Each model supports different thinking configurations which gives you control137over cost, latency, and intelligence. For more details, see the138[thinking guide](https://ai.google.dev/gemini-api/docs/thinking#set-budget).139140### Python141142 from google import genai143 from google.genai import types144145 client = genai.Client()146147 response = client.models.generate_content(148 model="gemini-3.8-flash",149 contents="How does AI work?",150 config=types.GenerateContentConfig(151 thinking_config=types.ThinkingConfig(thinking_level="low")152 ),153 )154 print(response.text)155156### JavaScript157158 import { GoogleGenAI, ThinkingLevel } from "@google/genai";159160 const ai = new GoogleGenAI({});161162 async function main() {163 const response = await ai.models.generateContent({164 model: "gemini-3.8-flash",165 contents: "How does AI work?",166 config: {167 thinkingConfig: {168 thinkingLevel: ThinkingLevel.LOW,169 },170 }171 });172 console.log(response.text);173 }174175 await main();176177### Go178179 package main180181 import (182 "context"183 "fmt"184 "os"185 "google.golang.org/genai"186 )187188 func main() {189190 ctx := context.Background()191 client, err := genai.NewClient(ctx, nil)192 if err != nil {193 log.Fatal(err)194 }195196 thinkingLevelVal := "low"197198 result, _ := client.Models.GenerateContent(199 ctx,200 "gemini-3.8-flash",201 genai.Text("How does AI work?"),202 &genai.GenerateContentConfig{203 ThinkingConfig: &genai.ThinkingConfig{204 ThinkingLevel: &thinkingLevelVal,205 },206 }207 )208209 fmt.Println(result.Text())210 }211212### Java213214 import com.google.genai.Client;215 import com.google.genai.types.GenerateContentConfig;216 import com.google.genai.types.GenerateContentResponse;217 import com.google.genai.types.ThinkingConfig;218 import com.google.genai.types.ThinkingLevel;219220 public class GenerateContentWithThinkingConfig {221 public static void main(String[] args) {222223 Client client = new Client();224225 GenerateContentConfig config =226 GenerateContentConfig.builder()227 .thinkingConfig(ThinkingConfig.builder().thinkingLevel(new ThinkingLevel("low")))228 .build();229230 GenerateContentResponse response =231 client.models.generateContent("gemini-3.8-flash", "How does AI work?", config);232233 System.out.println(response.text());234 }235 }236237### REST238239 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \240 -H "x-goog-api-key: $GEMINI_API_KEY" \241 -H 'Content-Type: application/json' \242 -X POST \243 -d '{244 "contents": [245 {246 "parts": [247 {248 "text": "How does AI work?"249 }250 ]251 }252 ],253 "generationConfig": {254 "thinkingConfig": {255 "thinkingLevel": "low"256 }257 }258 }'259260### Apps Script261262 // See https://developers.google.com/apps-script/guides/properties263 // for instructions on how to set the API key.264 const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');265266 function main() {267 const payload = {268 contents: [269 {270 parts: [271 { text: 'How AI does work?' },272 ],273 },274 ],275 generationConfig: {276 thinkingConfig: {277 thinkingLevel: 'low'278 }279 }280 };281282 const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent';283 const options = {284 method: 'POST',285 contentType: 'application/json',286 headers: {287 'x-goog-api-key': apiKey,288 },289 payload: JSON.stringify(payload)290 };291292 const response = UrlFetchApp.fetch(url, options);293 const data = JSON.parse(response);294 const content = data['candidates'][0]['content']['parts'][0]['text'];295 console.log(content);296 }297298## System instructions and other configurations299300You can guide the behavior of Gemini models with system instructions. To do so,301pass a [`GenerateContentConfig`](https://ai.google.dev/api/generate-content#v1beta.GenerationConfig)302object.303304### Python305306 from google import genai307 from google.genai import types308309 client = genai.Client()310311 response = client.models.generate_content(312 model="gemini-3.8-flash",313 config=types.GenerateContentConfig(314 system_instruction="You are a cat. Your name is Neko."),315 contents="Hello there"316 )317318 print(response.text)319320### JavaScript321322 import { GoogleGenAI } from "@google/genai";323324 const ai = new GoogleGenAI({});325326 async function main() {327 const response = await ai.models.generateContent({328 model: "gemini-3.8-flash",329 contents: "Hello there",330 config: {331 systemInstruction: "You are a cat. Your name is Neko.",332 },333 });334 console.log(response.text);335 }336337 await main();338339### Go340341 package main342343 import (344 "context"345 "fmt"346 "os"347 "google.golang.org/genai"348 )349350 func main() {351352 ctx := context.Background()353 client, err := genai.NewClient(ctx, nil)354 if err != nil {355 log.Fatal(err)356 }357358 config := &genai.GenerateContentConfig{359 SystemInstruction: genai.NewContentFromText("You are a cat. Your name is Neko.", genai.RoleUser),360 }361362 result, _ := client.Models.GenerateContent(363 ctx,364 "gemini-3.8-flash",365 genai.Text("Hello there"),366 config,367 )368369 fmt.Println(result.Text())370 }371372### Java373374 import com.google.genai.Client;375 import com.google.genai.types.Content;376 import com.google.genai.types.GenerateContentConfig;377 import com.google.genai.types.GenerateContentResponse;378 import com.google.genai.types.Part;379380 public class GenerateContentWithSystemInstruction {381 public static void main(String[] args) {382383 Client client = new Client();384385 GenerateContentConfig config =386 GenerateContentConfig.builder()387 .systemInstruction(388 Content.fromParts(Part.fromText("You are a cat. Your name is Neko.")))389 .build();390391 GenerateContentResponse response =392 client.models.generateContent("gemini-3.8-flash", "Hello there", config);393394 System.out.println(response.text());395 }396 }397398### REST399400 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \401 -H "x-goog-api-key: $GEMINI_API_KEY" \402 -H 'Content-Type: application/json' \403 -d '{404 "system_instruction": {405 "parts": [406 {407 "text": "You are a cat. Your name is Neko."408 }409 ]410 },411 "contents": [412 {413 "parts": [414 {415 "text": "Hello there"416 }417 ]418 }419 ]420 }'421422### Apps Script423424 // See https://developers.google.com/apps-script/guides/properties425 // for instructions on how to set the API key.426 const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');427428 function main() {429 const systemInstruction = {430 parts: [{431 text: 'You are a cat. Your name is Neko.'432 }]433 };434435 const payload = {436 systemInstruction,437 contents: [438 {439 parts: [440 { text: 'Hello there' },441 ],442 },443 ],444 };445446 const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent';447 const options = {448 method: 'POST',449 contentType: 'application/json',450 headers: {451 'x-goog-api-key': apiKey,452 },453 payload: JSON.stringify(payload)454 };455456 const response = UrlFetchApp.fetch(url, options);457 const data = JSON.parse(response);458 const content = data['candidates'][0]['content']['parts'][0]['text'];459 console.log(content);460 }461462The [`GenerateContentConfig`](https://ai.google.dev/api/generate-content#v1beta.GenerationConfig)463object also lets you override default generation parameters, such as464[`max_output_tokens`](https://ai.google.dev/api/generate-content#v1beta.GenerationConfig).465466> [!NOTE]467> 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.468469### Python470471 from google import genai472 from google.genai import types473474 client = genai.Client()475476 response = client.models.generate_content(477 model="gemini-3.8-flash",478 contents=["Explain how AI works"],479 config=types.GenerateContentConfig(480 max_output_tokens=1000481 )482 )483 print(response.text)484485### JavaScript486487 import { GoogleGenAI } from "@google/genai";488489 const ai = new GoogleGenAI({});490491 async function main() {492 const response = await ai.models.generateContent({493 model: "gemini-3.8-flash",494 contents: "Explain how AI works",495 config: {496 maxOutputTokens: 1000,497 },498 });499 console.log(response.text);500 }501502 await main();503504### Go505506 package main507508 import (509 "context"510 "fmt"511 "log"512 "google.golang.org/genai"513 )514515 func main() {516517 ctx := context.Background()518 client, err := genai.NewClient(ctx, nil)519 if err != nil {520 log.Fatal(err)521 }522523 config := &genai.GenerateContentConfig{524 MaxOutputTokens: 1000,525 ResponseMIMEType: "application/json",526 }527528 result, _ := client.Models.GenerateContent(529 ctx,530 "gemini-3.8-flash",531 genai.Text("What is the average size of a swallow?"),532 config,533 )534535 fmt.Println(result.Text())536 }537538### Java539540 import com.google.genai.Client;541 import com.google.genai.types.GenerateContentConfig;542 import com.google.genai.types.GenerateContentResponse;543544 public class GenerateContentWithConfig {545 public static void main(String[] args) {546547 Client client = new Client();548549 GenerateContentConfig config = GenerateContentConfig.builder().maxOutputTokens(1000).build();550551 GenerateContentResponse response =552 client.models.generateContent("gemini-3.8-flash", "Explain how AI works", config);553554 System.out.println(response.text());555 }556 }557558### REST559560 curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent \561 -H "x-goog-api-key: $GEMINI_API_KEY" \562 -H 'Content-Type: application/json' \563 -X POST \564 -d '{565 "contents": [566 {567 "parts": [568 {569 "text": "Explain how AI works"570 }571 ]572 }573 ],574 "generationConfig": {575 "stopSequences": [576 "Title"577 ],578 "maxOutputTokens": 1000579 }580 }'581582### Apps Script583584 // See https://developers.google.com/apps-script/guides/properties585 // for instructions on how to set the API key.586 const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');587588 function main() {589 const generationConfig = {590 maxOutputTokens: 1000,591 responseFormat: { text: { mimeType: "text/plain" } },592 };593594 const payload = {595 generationConfig,596 contents: [597 {598 parts: [599 { text: 'Explain how AI works in a few words' },600 ],601 },602 ],603 };604605 const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent';606 const options = {607 method: 'POST',608 contentType: 'application/json',609 headers: {610 'x-goog-api-key': apiKey,611 },612 payload: JSON.stringify(payload)613 };614615 const response = UrlFetchApp.fetch(url, options);616 const data = JSON.parse(response);617 const content = data['candidates'][0]['content']['parts'][0]['text'];618 console.log(content);619 }620621Refer to the [`GenerateContentConfig`](https://ai.google.dev/api/generate-content#v1beta.GenerationConfig)622in our API reference for a complete list of configurable parameters and their623descriptions.624625## Multimodal inputs626627The Gemini API supports multimodal inputs, allowing you to combine text with628media files. The following example demonstrates providing an image:629630### Python631632 from PIL import Image633 from google import genai634635 client = genai.Client()636637 image = Image.open("/path/to/organ.png")638 response = client.models.generate_content(639 model="gemini-3.8-flash",640 contents=[image, "Tell me about this instrument"]641 )642 print(response.text)643644### JavaScript645646 import {647 GoogleGenAI,648 createUserContent,649 createPartFromUri,650 } from "@google/genai";651652 const ai = new GoogleGenAI({});653654 async function main() {655 const image = await ai.files.upload({656 file: "/path/to/organ.png",657 });658 const response = await ai.models.generateContent({659 model: "gemini-3.8-flash",660 contents: [661 createUserContent([662 "Tell me about this instrument",663 createPartFromUri(image.uri, image.mimeType),664 ]),665 ],666 });667 console.log(response.text);668 }669670 await main();671672### Go673674 package main675676 import (677 "context"678 "fmt"679 "os"680 "google.golang.org/genai"681 )682683 func main() {684685 ctx := context.Background()686 client, err := genai.NewClient(ctx, nil)687 if err != nil {688 log.Fatal(err)689 }690691 imagePath := "/path/to/organ.jpg"692 imgData, _ := os.ReadFile(imagePath)693694 parts := []*genai.Part{695 genai.NewPartFromText("Tell me about this instrument"),696 &genai.Part{697 InlineData: &genai.Blob{698 MIMEType: "image/jpeg",699 Data: imgData,700 },701 },702 }703704 contents := []*genai.Content{705 genai.NewContentFromParts(parts, genai.RoleUser),706 }707708 result, _ := client.Models.GenerateContent(709 ctx,710 "gemini-3.8-flash",711 contents,712 nil,713 )714715 fmt.Println(result.Text())716 }717718### Java719720 import com.google.genai.Client;721 import com.google.genai.Content;722 import com.google.genai.types.GenerateContentResponse;723 import com.google.genai.types.Part;724725 public class GenerateContentWithMultiModalInputs {726 public static void main(String[] args) {727728 Client client = new Client();729730 Content content =731 Content.fromParts(732 Part.fromText("Tell me about this instrument"),733 Part.fromUri("/path/to/organ.jpg", "image/jpeg"));734735 GenerateContentResponse response =736 client.models.generateContent("gemini-3.8-flash", content, null);737738 System.out.println(response.text());739 }740 }741742### REST743744 # Use a temporary file to hold the base64 encoded image data745 TEMP_B64=$(mktemp)746 trap 'rm -f "$TEMP_B64"' EXIT747 base64 $B64FLAGS $IMG_PATH > "$TEMP_B64"748749 # Use a temporary file to hold the JSON payload750 TEMP_JSON=$(mktemp)751 trap 'rm -f "$TEMP_JSON"' EXIT752753 cat > "$TEMP_JSON" << EOF754 {755 "contents": [756 {757 "parts": [758 {759 "text": "Tell me about this instrument"760 },761 {762 "inline_data": {763 "mime_type": "image/jpeg",764 "data": "$(cat "$TEMP_B64")"765 }766 }767 ]768 }769 ]770 }771 EOF772773 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \774 -H "x-goog-api-key: $GEMINI_API_KEY" \775 -H 'Content-Type: application/json' \776 -X POST \777 -d "@$TEMP_JSON"778779### Apps Script780781 // See https://developers.google.com/apps-script/guides/properties782 // for instructions on how to set the API key.783 const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');784785 function main() {786 const imageUrl = 'https://example.com/image.jpg';787 const image = getImageData(imageUrl);788 const payload = {789 contents: [790 {791 parts: [792 { image },793 { text: 'Tell me about this instrument' },794 ],795 },796 ],797 };798799 const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent';800 const options = {801 method: 'POST',802 contentType: 'application/json',803 headers: {804 'x-goog-api-key': apiKey,805 },806 payload: JSON.stringify(payload)807 };808809 const response = UrlFetchApp.fetch(url, options);810 const data = JSON.parse(response);811 const content = data['candidates'][0]['content']['parts'][0]['text'];812 console.log(content);813 }814815 function getImageData(url) {816 const blob = UrlFetchApp.fetch(url).getBlob();817818 return {819 mimeType: blob.getContentType(),820 data: Utilities.base64Encode(blob.getBytes())821 };822 }823824For alternative methods of providing images and more advanced image processing,825see our [image understanding guide](https://ai.google.dev/gemini-api/docs/image-understanding).826The API also supports [document](https://ai.google.dev/gemini-api/docs/document-processing), [video](https://ai.google.dev/gemini-api/docs/video-understanding), and [audio](https://ai.google.dev/gemini-api/docs/audio)827inputs and understanding.828829## Streaming responses830831By default, the model returns a response only after the entire generation832process is complete.833834For more fluid interactions, use streaming to receive [`GenerateContentResponse`](https://ai.google.dev/api/generate-content#v1beta.GenerateContentResponse) instances incrementally835as they're generated.836837### Python838839 from google import genai840841 client = genai.Client()842843 response = client.models.generate_content_stream(844 model="gemini-3.8-flash",845 contents=["Explain how AI works"]846 )847 for chunk in response:848 print(chunk.text, end="")849850### JavaScript851852 import { GoogleGenAI } from "@google/genai";853854 const ai = new GoogleGenAI({});855856 async function main() {857 const response = await ai.models.generateContentStream({858 model: "gemini-3.8-flash",859 contents: "Explain how AI works",860 });861862 for await (const chunk of response) {863 console.log(chunk.text);864 }865 }866867 await main();868869### Go870871 package main872873 import (874 "context"875 "fmt"876 "os"877 "google.golang.org/genai"878 )879880 func main() {881882 ctx := context.Background()883 client, err := genai.NewClient(ctx, nil)884 if err != nil {885 log.Fatal(err)886 }887888 stream := client.Models.GenerateContentStream(889 ctx,890 "gemini-3.8-flash",891 genai.Text("Write a story about a magic backpack."),892 nil,893 )894895 for chunk, _ := range stream {896 part := chunk.Candidates[0].Content.Parts[0]897 fmt.Print(part.Text)898 }899 }900901### Java902903 import com.google.genai.Client;904 import com.google.genai.ResponseStream;905 import com.google.genai.types.GenerateContentResponse;906907 public class GenerateContentStream {908 public static void main(String[] args) {909910 Client client = new Client();911912 ResponseStream<GenerateContentResponse> responseStream =913 client.models.generateContentStream(914 "gemini-3.8-flash", "Write a story about a magic backpack.", null);915916 for (GenerateContentResponse res : responseStream) {917 System.out.print(res.text());918 }919920 // To save resources and avoid connection leaks, it is recommended to close the response921 // stream after consumption (or using try block to get the response stream).922 responseStream.close();923 }924 }925926### REST927928 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse" \929 -H "x-goog-api-key: $GEMINI_API_KEY" \930 -H 'Content-Type: application/json' \931 --no-buffer \932 -d '{933 "contents": [934 {935 "parts": [936 {937 "text": "Explain how AI works"938 }939 ]940 }941 ]942 }'943944### Apps Script945946 // See https://developers.google.com/apps-script/guides/properties947 // for instructions on how to set the API key.948 const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');949950 function main() {951 const payload = {952 contents: [953 {954 parts: [955 { text: 'Explain how AI works' },956 ],957 },958 ],959 };960961 const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent';962 const options = {963 method: 'POST',964 contentType: 'application/json',965 headers: {966 'x-goog-api-key': apiKey,967 },968 payload: JSON.stringify(payload)969 };970971 const response = UrlFetchApp.fetch(url, options);972 const data = JSON.parse(response);973 const content = data['candidates'][0]['content']['parts'][0]['text'];974 console.log(content);975 }976977## Multi-turn conversations (chat)978979Our SDKs provide functionality to collect multiple rounds of prompts and980responses into a chat, giving you an easy way to keep track of the conversation981history.982983> [!NOTE]984> **Note:** Chat functionality is only implemented as part of the SDKs. Behind the scenes, it still uses the [`generateContent`](https://ai.google.dev/api/generate-content#method:-models.generatecontent) API. For multi-turn conversations, the full conversation history is sent to the model with each follow-up turn.985986### Python987988 from google import genai989990 client = genai.Client()991 chat = client.chats.create(model="gemini-3.8-flash")992993 response = chat.send_message("I have 2 dogs in my house.")994 print(response.text)995996 response = chat.send_message("How many paws are in my house?")997 print(response.text)998999 for message in chat.get_history():1000 print(f'role - {message.role}',end=": ")1001 print(message.parts[0].text)10021003### JavaScript10041005 import { GoogleGenAI } from "@google/genai";10061007 const ai = new GoogleGenAI({});10081009 async function main() {1010 const chat = ai.chats.create({1011 model: "gemini-3.8-flash",1012 history: [1013 {1014 role: "user",1015 parts: [{ text: "Hello" }],1016 },1017 {1018 role: "model",1019 parts: [{ text: "Great to meet you. What would you like to know?" }],1020 },1021 ],1022 });10231024 const response1 = await chat.sendMessage({1025 message: "I have 2 dogs in my house.",1026 });1027 console.log("Chat response 1:", response1.text);10281029 const response2 = await chat.sendMessage({1030 message: "How many paws are in my house?",1031 });1032 console.log("Chat response 2:", response2.text);1033 }10341035 await main();10361037### Go10381039 package main10401041 import (1042 "context"1043 "fmt"1044 "os"1045 "google.golang.org/genai"1046 )10471048 func main() {10491050 ctx := context.Background()1051 client, err := genai.NewClient(ctx, nil)1052 if err != nil {1053 log.Fatal(err)1054 }10551056 history := []*genai.Content{1057 genai.NewContentFromText("Hi nice to meet you! I have 2 dogs in my house.", genai.RoleUser),1058 genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),1059 }10601061 chat, _ := client.Chats.Create(ctx, "gemini-3.8-flash", nil, history)1062 res, _ := chat.SendMessage(ctx, genai.Part{Text: "How many paws are in my house?"})10631064 if len(res.Candidates) > 0 {1065 fmt.Println(res.Candidates[0].Content.Parts[0].Text)1066 }1067 }10681069### Java10701071 import com.google.genai.Chat;1072 import com.google.genai.Client;1073 import com.google.genai.types.Content;1074 import com.google.genai.types.GenerateContentResponse;10751076 public class MultiTurnConversation {1077 public static void main(String[] args) {10781079 Client client = new Client();1080 Chat chatSession = client.chats.create("gemini-3.8-flash");10811082 GenerateContentResponse response =1083 chatSession.sendMessage("I have 2 dogs in my house.");1084 System.out.println("First response: " + response.text());10851086 response = chatSession.sendMessage("How many paws are in my house?");1087 System.out.println("Second response: " + response.text());10881089 // Get the history of the chat session.1090 // Passing 'true' to getHistory() returns the curated history, which excludes1091 // empty or invalid parts.1092 // Passing 'false' here would return the comprehensive history, including1093 // empty or invalid parts.1094 ImmutableList<Content> history = chatSession.getHistory(true);1095 System.out.println("History: " + history);1096 }1097 }10981099### REST11001101 curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent \1102 -H "x-goog-api-key: $GEMINI_API_KEY" \1103 -H 'Content-Type: application/json' \1104 -X POST \1105 -d '{1106 "contents": [1107 {1108 "role": "user",1109 "parts": [1110 {1111 "text": "Hello"1112 }1113 ]1114 },1115 {1116 "role": "model",1117 "parts": [1118 {1119 "text": "Great to meet you. What would you like to know?"1120 }1121 ]1122 },1123 {1124 "role": "user",1125 "parts": [1126 {1127 "text": "I have two dogs in my house. How many paws are in my house?"1128 }1129 ]1130 }1131 ]1132 }'11331134### Apps Script11351136 // See https://developers.google.com/apps-script/guides/properties1137 // for instructions on how to set the API key.1138 const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');11391140 function main() {1141 const payload = {1142 contents: [1143 {1144 role: 'user',1145 parts: [1146 { text: 'Hello' },1147 ],1148 },1149 {1150 role: 'model',1151 parts: [1152 { text: 'Great to meet you. What would you like to know?' },1153 ],1154 },1155 {1156 role: 'user',1157 parts: [1158 { text: 'I have two dogs in my house. How many paws are in my house?' },1159 ],1160 },1161 ],1162 };11631164 const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent';1165 const options = {1166 method: 'POST',1167 contentType: 'application/json',1168 headers: {1169 'x-goog-api-key': apiKey,1170 },1171 payload: JSON.stringify(payload)1172 };11731174 const response = UrlFetchApp.fetch(url, options);1175 const data = JSON.parse(response);1176 const content = data['candidates'][0]['content']['parts'][0]['text'];1177 console.log(content);1178 }11791180Streaming can also be used for multi-turn conversations.11811182### Python11831184 from google import genai11851186 client = genai.Client()1187 chat = client.chats.create(model="gemini-3.8-flash")11881189 response = chat.send_message_stream("I have 2 dogs in my house.")1190 for chunk in response:1191 print(chunk.text, end="")11921193 response = chat.send_message_stream("How many paws are in my house?")1194 for chunk in response:1195 print(chunk.text, end="")11961197 for message in chat.get_history():1198 print(f'role - {message.role}', end=": ")1199 print(message.parts[0].text)12001201### JavaScript12021203 import { GoogleGenAI } from "@google/genai";12041205 const ai = new GoogleGenAI({});12061207 async function main() {1208 const chat = ai.chats.create({1209 model: "gemini-3.8-flash",1210 history: [1211 {1212 role: "user",1213 parts: [{ text: "Hello" }],1214 },1215 {1216 role: "model",1217 parts: [{ text: "Great to meet you. What would you like to know?" }],1218 },1219 ],1220 });12211222 const stream1 = await chat.sendMessageStream({1223 message: "I have 2 dogs in my house.",1224 });1225 for await (const chunk of stream1) {1226 console.log(chunk.text);1227 console.log("_".repeat(80));1228 }12291230 const stream2 = await chat.sendMessageStream({1231 message: "How many paws are in my house?",1232 });1233 for await (const chunk of stream2) {1234 console.log(chunk.text);1235 console.log("_".repeat(80));1236 }1237 }12381239 await main();12401241### Go12421243 package main12441245 import (1246 "context"1247 "fmt"1248 "os"1249 "google.golang.org/genai"1250 )12511252 func main() {12531254 ctx := context.Background()1255 client, err := genai.NewClient(ctx, nil)1256 if err != nil {1257 log.Fatal(err)1258 }12591260 history := []*genai.Content{1261 genai.NewContentFromText("Hi nice to meet you! I have 2 dogs in my house.", genai.RoleUser),1262 genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),1263 }12641265 chat, _ := client.Chats.Create(ctx, "gemini-3.8-flash", nil, history)1266 stream := chat.SendMessageStream(ctx, genai.Part{Text: "How many paws are in my house?"})12671268 for chunk, _ := range stream {1269 part := chunk.Candidates[0].Content.Parts[0]1270 fmt.Print(part.Text)1271 }1272 }12731274### Java12751276 import com.google.genai.Chat;1277 import com.google.genai.Client;1278 import com.google.genai.ResponseStream;1279 import com.google.genai.types.GenerateContentResponse;12801281 public class MultiTurnConversationWithStreaming {1282 public static void main(String[] args) {12831284 Client client = new Client();1285 Chat chatSession = client.chats.create("gemini-3.8-flash");12861287 ResponseStream<GenerateContentResponse> responseStream =1288 chatSession.sendMessageStream("I have 2 dogs in my house.", null);12891290 for (GenerateContentResponse response : responseStream) {1291 System.out.print(response.text());1292 }12931294 responseStream = chatSession.sendMessageStream("How many paws are in my house?", null);12951296 for (GenerateContentResponse response : responseStream) {1297 System.out.print(response.text());1298 }12991300 // Get the history of the chat session. History is added after the stream1301 // is consumed and includes the aggregated response from the stream.1302 System.out.println("History: " + chatSession.getHistory(false));1303 }1304 }13051306### REST13071308 curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse \1309 -H "x-goog-api-key: $GEMINI_API_KEY" \1310 -H 'Content-Type: application/json' \1311 -X POST \1312 -d '{1313 "contents": [1314 {1315 "role": "user",1316 "parts": [1317 {1318 "text": "Hello"1319 }1320 ]1321 },1322 {1323 "role": "model",1324 "parts": [1325 {1326 "text": "Great to meet you. What would you like to know?"1327 }1328 ]1329 },1330 {1331 "role": "user",1332 "parts": [1333 {1334 "text": "I have two dogs in my house. How many paws are in my house?"1335 }1336 ]1337 }1338 ]1339 }'13401341### Apps Script13421343 // See https://developers.google.com/apps-script/guides/properties1344 // for instructions on how to set the API key.1345 const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');13461347 function main() {1348 const payload = {1349 contents: [1350 {1351 role: 'user',1352 parts: [1353 { text: 'Hello' },1354 ],1355 },1356 {1357 role: 'model',1358 parts: [1359 { text: 'Great to meet you. What would you like to know?' },1360 ],1361 },1362 {1363 role: 'user',1364 parts: [1365 { text: 'I have two dogs in my house. How many paws are in my house?' },1366 ],1367 },1368 ],1369 };13701371 const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent';1372 const options = {1373 method: 'POST',1374 contentType: 'application/json',1375 headers: {1376 'x-goog-api-key': apiKey,1377 },1378 payload: JSON.stringify(payload)1379 };13801381 const response = UrlFetchApp.fetch(url, options);1382 const data = JSON.parse(response);1383 const content = data['candidates'][0]['content']['parts'][0]['text'];1384 console.log(content);1385 }13861387## Prompting tips13881389Consult our [prompt engineering guide](https://ai.google.dev/gemini/docs/prompting-strategies) for1390suggestions on getting the most out of Gemini.13911392## What's next13931394- Try [Gemini in Google AI Studio](https://aistudio.google.com).1395- Experiment with [structured outputs](https://ai.google.dev/gemini-api/docs/structured-output) for JSON-like responses.1396- Explore Gemini's [image](https://ai.google.dev/gemini-api/docs/image-understanding), [video](https://ai.google.dev/gemini-api/docs/video-understanding), [audio](https://ai.google.dev/gemini-api/docs/audio) and [document](https://ai.google.dev/gemini-api/docs/document-processing) understanding capabilities.1397- Learn about multimodal [file prompting strategies](https://ai.google.dev/gemini-api/docs/files#prompt-guide).13981399## Content generation14001401This is the central endpoint for sending prompts to the model. There are two1402endpoints for generating content, the key difference is how you receive the1403response:14041405- **[`generateContent`](https://ai.google.dev/api/generate-content#method:-models.generatecontent)1406 (REST)**: Receives a request and provides a single response after the model has finished its entire generation.1407- **[`streamGenerateContent`](https://ai.google.dev/api/generate-content#method:-models.streamgeneratecontent)1408 (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.14091410### Request body structure14111412The [request body](https://ai.google.dev/api/generate-content#request-body) is a JSON object that is1413**identical** for both standard and streaming modes and is built from a few core1414objects:14151416- [`Content`](https://ai.google.dev/api/caching#Content) object: Represents a single turn in a conversation.1417- [`Part`](https://ai.google.dev/api/caching#Part) object: A piece of data within a `Content` turn (like text or an image).1418- `inline_data` ([`Blob`](https://ai.google.dev/api/caching#Blob)): A container for raw media bytes and their MIME type.14191420At the highest level, the request body contains a `contents` object, which is a1421list of `Content` objects, each representing turns in conversation. In most1422cases, for basic text generation, you will have a single `Content` object, but1423if you'd like to maintain conversation history, you can use multiple `Content`1424objects.14251426The following shows a typical `generateContent` request body:14271428 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \1429 -H "x-goog-api-key: $GEMINI_API_KEY" \1430 -H 'Content-Type: application/json' \1431 -X POST \1432 -d '{1433 "contents": [1434 {1435 "role": "user",1436 "parts": [1437 // A list of Part objects goes here1438 ]1439 },1440 {1441 "role": "model",1442 "parts": [1443 // A list of Part objects goes here1444 ]1445 }1446 ]1447 }'14481449### Response body structure14501451The [response body](https://ai.google.dev/api/generate-content#response-body) is similar for both1452the streaming and standard modes except for the following:14531454- Standard mode: The response body contains an instance of [`GenerateContentResponse`](https://ai.google.dev/api/generate-content#v1beta.GenerateContentResponse).1455- Streaming mode: The response body contains a stream of [`GenerateContentResponse`](https://ai.google.dev/api/generate-content#v1beta.GenerateContentResponse) instances.14561457At a high level, the response body contains a `candidates` object, which is a1458list of `Candidate` objects. The `Candidate` object contains a `Content`1459object that has the generated response returned from the model.14601461## REST API Examples14621463### Multimodal prompt (text and image)14641465To provide both text and an image in a prompt, the `parts` array should contain1466two `Part` objects: one for the text, and one for the image `inline_data`.14671468 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \1469 -H "x-goog-api-key: $GEMINI_API_KEY" \1470 -H 'Content-Type: application/json' \1471 -X POST \1472 -d '{1473 "contents": [{1474 "parts":[1475 {1476 "inline_data": {1477 "mime_type":"image/jpeg",1478 "data": "/9j/4AAQSkZJRgABAQ... (base64-encoded image)"1479 }1480 },1481 {"text": "What is in this picture?"},1482 ]1483 }]1484 }'14851486### Multi-turn conversations (chat)14871488To build a conversation with multiple turns, you define the `contents` array1489with multiple `Content` objects. The API will use this entire history as context1490for the next response. The `role` for each `Content` object should alternate1491between `user` and `model`.14921493> [!NOTE]1494> **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.14951496 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \1497 -H "x-goog-api-key: $GEMINI_API_KEY" \1498 -H 'Content-Type: application/json' \1499 -X POST \1500 -d '{1501 "contents": [1502 {1503 "role": "user",1504 "parts": [1505 { "text": "Hello." }1506 ]1507 },1508 {1509 "role": "model",1510 "parts": [1511 { "text": "Hello! How can I help you today?" }1512 ]1513 },1514 {1515 "role": "user",1516 "parts": [1517 { "text": "Please write a four-line poem about the ocean." }1518 ]1519 }1520 ]1521 }'15221523### Key takeaways15241525- `Content` is the envelope: It's the top-level container for a message turn, whether it's from the user or the model.1526- `Part` enables multimodality: Use multiple `Part` objects within a single `Content` object to combine different types of data (text, image, video URI, etc.).1527- Choose your data method:1528 - For small, directly embedded media (like most images), use a `Part` with `inline_data`.1529 - 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.1530- 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.15311532## Response examples15331534The following examples show how these components come together for different1535types of requests.15361537### Text-only response15381539A default text response consists of a `candidates` array with one or more1540`content` objects that contain the model's response.15411542The following is an example of a **standard** response:15431544 {1545 "candidates": [1546 {1547 "content": {1548 "parts": [1549 {1550 "text": "At its core, Artificial Intelligence works by learning from vast amounts of data ..."1551 }1552 ],1553 "role": "model"1554 },1555 "finishReason": "STOP",1556 "index": 11557 }1558 ],1559 }15601561The following is series of **streaming** responses. Each response contains a1562`responseId` that ties the full response together:15631564 {1565 "candidates": [1566 {1567 "content": {1568 "parts": [1569 {1570 "text": "The image displays"1571 }1572 ],1573 "role": "model"1574 },1575 "index": 01576 }1577 ],1578 "usageMetadata": {1579 "promptTokenCount": ...1580 },1581 "modelVersion": "gemini-3.8-flash",1582 "responseId": "mAitaLmkHPPlz7IPvtfUqQ4"1583 }15841585 ...15861587 {1588 "candidates": [1589 {1590 "content": {1591 "parts": [1592 {1593 "text": " the following materials:\n\n* **Wood:** The accordion and the violin are primarily"1594 }1595 ],1596 "role": "model"1597 },1598 "index": 01599 }1600 ],1601 "usageMetadata": {1602 "promptTokenCount": ...1603 }1604 "modelVersion": "gemini-3.8-flash",1605 "responseId": "mAitaLmkHPPlz7IPvtfUqQ4"1606 }16071608## Live API (BidiGenerateContent) WebSockets API16091610Live API offers a stateful WebSocket based API for bi-directional streaming to1611enable real-time streaming use cases. You can review1612[Live API guide](https://ai.google.dev/gemini-api/docs/live) and the [Live API reference](https://ai.google.dev/api/live)1613for more details.16141615## Specialized models16161617In addition to the Gemini family of models, Gemini API offers endpoints for1618specialized models such as [Nano Banana](https://ai.google.dev/gemini-api/docs/image-generation),1619[Lyria](https://ai.google.dev/gemini-api/docs/music-generation) and1620[embedding](https://ai.google.dev/gemini-api/docs/embeddings) models. You can check out1621these guides under the Models section.16221623## Platform APIs16241625The rest of the endpoints enable additional capabilities to use with the main1626endpoints described so far. Check out topics1627[Batch mode](https://ai.google.dev/gemini-api/docs/batch-mode) and1628[File API](https://ai.google.dev/gemini-api/docs/files) in the Guides section to learn more.16291630## What's next16311632If you're just getting started, check out the following guides, which will help1633you understand the Gemini API programming model:16341635- [Gemini API Get started guide](https://ai.google.dev/gemini-api/docs/generate-content/get-started)1636- [Gemini model guide](https://ai.google.dev/gemini-api/docs/models/gemini)16371638You might also want to check out the capabilities guides, which introduce different1639Gemini API features and provide code examples:16401641- [Text generation](https://ai.google.dev/gemini-api/docs/text-generation)1642- [Context caching](https://ai.google.dev/gemini-api/docs/caching)1643- [Embeddings](https://ai.google.dev/gemini-api/docs/embeddings)