Repository Public
1Starting with the Gemini 2.0 release in late 2024, we introduced a new set of2libraries called the [Google GenAI SDK](https://ai.google.dev/gemini-api/docs/libraries). It offers3an improved developer experience through4an [updated client architecture](https://ai.google.dev/gemini-api/docs/migrate#client), and5[simplifies the transition](https://ai.google.dev/gemini-api/docs/migrate-to-cloud) between developer6and enterprise workflows.78The Google GenAI SDK is now in [General Availability (GA)](https://ai.google.dev/gemini-api/docs/libraries#new-libraries) across all supported9platforms. If you're using one of our [legacy libraries](https://ai.google.dev/gemini-api/docs/libraries#previous-sdks), we strongly recommend you to10migrate.1112This guide provides before-and-after examples of migrated code to help you get13started.1415> [!NOTE]16> **Note:** The Go examples omit imports and other boilerplate code to improve readability.1718## Installation1920**Before**2122### Python2324 pip install -U -q "google-generativeai"2526### JavaScript2728 npm install @google/generative-ai2930### Go3132 go get github.com/google/generative-ai-go3334### Java3536 <dependency>37 <groupId>com.google.ai.client.generativeai</groupId>38 <artifactId>generativeai</artifactId>39 <version>0.9.0</version>40 </dependency>4142**After**4344### Python4546 pip install -U -q "google-genai"4748### JavaScript4950 npm install @google/genai5152### Go5354 go get google.golang.org/genai5556### Java5758 <dependency>59 <groupId>com.google.genai</groupId>60 <artifactId>google-genai</artifactId>61 <version>1.67.0</version>62 </dependency>6364## API access6566The old SDK implicitly handled the API client behind the scenes using a variety67of ad hoc methods. This made it hard to manage the client and credentials.68Now, you interact through a central `Client` object. This `Client` object acts69as a single entry point for various API services (e.g., `models`, `chats`,70`files`, `tunings`), promoting consistency and simplifying credential and71configuration management across different API calls.7273**Before (Less Centralized API Access)**7475### Python7677The old SDK didn't explicitly use a top-level client object for most API78calls. You would directly instantiate and interact with `GenerativeModel`79objects.8081 import google.generativeai as genai8283 # Directly create and use model objects84 model = genai.GenerativeModel('gemini-3.8-flash')85 response = model.generate_content(...)86 chat = model.start_chat(...)8788### JavaScript8990While `GoogleGenerativeAI` was a central point for models and chat, other91functionalities like file and cache management often required importing and92instantiating entirely separate client classes.9394 import { GoogleGenerativeAI } from "@google/generative-ai";95 import { GoogleAIFileManager, GoogleAICacheManager } from "@google/generative-ai/server"; // For files/caching9697 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");98 const fileManager = new GoogleAIFileManager("GEMINI_API_KEY");99 const cacheManager = new GoogleAICacheManager("GEMINI_API_KEY");100101 // Get a model instance, then call methods on it102 const model = genAI.getGenerativeModel({ model: "gemini-3.8-flash" });103 const result = await model.generateContent(...);104 const chat = model.startChat(...);105106 // Call methods on separate client objects for other services107 const uploadedFile = await fileManager.uploadFile(...);108 const cache = await cacheManager.create(...);109110### Java111112 import com.google.genai.Chat;113 import com.google.genai.Client;114 import com.google.genai.types.GenerateContentResponse;115116 // Previously, model operations were called on separate model instances117 Client client = new Client();118 GenerateContentResponse response =119 client.models.generateContent("gemini-3.8-flash", "Tell me a story.", null);120 Chat chat = client.chats.create("gemini-3.8-flash");121122### Go123124The `genai.NewClient` function created a client, but generative model125operations were typically called on a separate `GenerativeModel` instance126obtained from this client. Other services might have been accessed via127distinct packages or patterns.128129 import (130 "github.com/google/generative-ai-go/genai"131 "github.com/google/generative-ai-go/genai/fileman" // For files132 "google.golang.org/api/option"133 )134135 client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))136 fileClient, err := fileman.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))137138 // Get a model instance, then call methods on it139 model := client.GenerativeModel("gemini-3.8-flash")140 resp, err := model.GenerateContent(...)141 cs := model.StartChat()142143 // Call methods on separate client objects for other services144 uploadedFile, err := fileClient.UploadFile(...)145146**After (Centralized Client Object)**147148### Python149150 from google import genai151152 # Create a single client object153 client = genai.Client()154155 # Access API methods through services on the client object156 response = client.models.generate_content(...)157 chat = client.chats.create(...)158 my_file = client.files.upload(...)159 tuning_job = client.tunings.tune(...)160161### JavaScript162163 import { GoogleGenAI } from "@google/genai";164165 // Create a single client object166 const ai = new GoogleGenAI({apiKey: "GEMINI_API_KEY"});167168 // Access API methods through services on the client object169 const response = await ai.models.generateContent(...);170 const chat = ai.chats.create(...);171 const uploadedFile = await ai.files.upload(...);172 const cache = await ai.caches.create(...);173174### Java175176 import com.google.genai.Chat;177 import com.google.genai.Client;178 import com.google.genai.types.CachedContent;179 import com.google.genai.types.CreateCachedContentConfig;180 import com.google.genai.types.File;181 import com.google.genai.types.GenerateContentResponse;182183 // Create a single client object184 Client client = new Client();185186 // Access API methods through services on the client object187 GenerateContentResponse response =188 client.models.generateContent("gemini-3.8-flash", "Tell me a story.", null);189 Chat chat = client.chats.create("gemini-3.8-flash");190 File uploadedFile = client.files.upload("sample.txt", null);191 CachedContent cache =192 client.caches.create("gemini-3.8-flash", CreateCachedContentConfig.builder().build());193194### Go195196 import "google.golang.org/genai"197198 // Create a single client object199 client, err := genai.NewClient(ctx, nil)200201 // Access API methods through services on the client object202 result, err := client.Models.GenerateContent(...)203 chat, err := client.Chats.Create(...)204 uploadedFile, err := client.Files.Upload(...)205 tuningJob, err := client.Tunings.Tune(...)206207## Authentication208209Both legacy and new libraries authenticate using API keys. You can210[create](https://aistudio.google.com/apikey) your API key in Google AI211Studio.212213**Before**214215### Python216217The old SDK handled the API client object implicitly.218219 import google.generativeai as genai220221 genai.configure(api_key=...)222223### JavaScript224225 import { GoogleGenerativeAI } from "@google/generative-ai";226227 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");228229### Java230231 import com.google.genai.Client;232233 // Passing the API key explicitly to the client builder234 Client client = Client.builder().apiKey("GEMINI_API_KEY").build();235236### Go237238Import the Google libraries:239240 import (241 "github.com/google/generative-ai-go/genai"242 "google.golang.org/api/option"243 )244245Create the client:246247 client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))248249**After**250251### Python252253With Google GenAI SDK, you create an API client first, which is used to call254the API.255The new SDK will pick up your API key from the `GEMINI_API_KEY` environment256variables, if you don't pass one to the client.257258 export GEMINI_API_KEY="YOUR_API_KEY"259260 from google import genai261262 client = genai.Client() # Set the API key using the GEMINI_API_KEY env var.263 # Alternatively, you could set the API key explicitly:264 # client = genai.Client(api_key="YOUR_API_KEY")265266### JavaScript267268 import { GoogleGenAI } from "@google/genai";269270 const ai = new GoogleGenAI({apiKey: "GEMINI_API_KEY"});271272### Java273274 import com.google.genai.Client;275276 // The client automatically picks up the GEMINI_API_KEY environment variable,277 // or you can pass it explicitly via Client.builder().apiKey("GEMINI_API_KEY").build()278 Client client = new Client();279280### Go281282Import the GenAI library:283284 import "google.golang.org/genai"285286Create the client:287288 client, err := genai.NewClient(ctx, &genai.ClientConfig{289 Backend: genai.BackendGeminiAPI,290 })291292## Generate content293294### Text295296**Before**297298### Python299300Previously, there were no client objects, you accessed APIs directly through301`GenerativeModel` objects.302303 import google.generativeai as genai304305 model = genai.GenerativeModel('gemini-3.8-flash')306 response = model.generate_content(307 'Tell me a story in 300 words'308 )309 print(response.text)310311### JavaScript312313 import { GoogleGenerativeAI } from "@google/generative-ai";314315 const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);316 const model = genAI.getGenerativeModel({ model: "gemini-3.8-flash" });317 const prompt = "Tell me a story in 300 words";318319 const result = await model.generateContent(prompt);320 console.log(result.response.text());321322### Java323324 import com.google.genai.Client;325 import com.google.genai.types.GenerateContentResponse;326327 Client client = new Client();328 String prompt = "Tell me a story in 300 words";329330 GenerateContentResponse response =331 client.models.generateContent("gemini-3.8-flash", prompt, null);332 System.out.println(response.text());333334### Go335336 ctx := context.Background()337 client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))338 if err != nil {339 log.Fatal(err)340 }341 defer client.Close()342343 model := client.GenerativeModel("gemini-3.8-flash")344 resp, err := model.GenerateContent(ctx, genai.Text("Tell me a story in 300 words."))345 if err != nil {346 log.Fatal(err)347 }348349 printResponse(resp) // utility for printing response parts350351**After**352353### Python354355The new Google GenAI SDK provides access to all the API methods through the356`Client` object. Except for a few stateful special cases (`chat` and357live-api `session`s), these are all stateless functions. For utility and358uniformity, objects returned are `pydantic` classes.359360 from google import genai361 client = genai.Client()362363 response = client.models.generate_content(364 model='gemini-3.8-flash',365 contents='Tell me a story in 300 words.'366 )367 print(response.text)368369 print(response.model_dump_json(370 exclude_none=True, indent=4))371372### JavaScript373374 import { GoogleGenAI } from "@google/genai";375376 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });377378 const response = await ai.models.generateContent({379 model: "gemini-3.8-flash",380 contents: "Tell me a story in 300 words.",381 });382 console.log(response.text);383384### Java385386 import com.google.genai.Client;387 import com.google.genai.types.GenerateContentResponse;388389 Client client = new Client();390391 GenerateContentResponse response =392 client.models.generateContent(393 "gemini-3.8-flash", "Tell me a story in 300 words.", null);394 System.out.println(response.text());395396### Go397398 ctx := context.Background()399 client, err := genai.NewClient(ctx, nil)400 if err != nil {401 log.Fatal(err)402 }403404 result, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", genai.Text("Tell me a story in 300 words."), nil)405 if err != nil {406 log.Fatal(err)407 }408 debugPrint(result) // utility for printing result409410### Image411412**Before**413414### Python415416 import google.generativeai as genai417418 model = genai.GenerativeModel('gemini-3.8-flash')419 response = model.generate_content([420 'Tell me a story based on this image',421 Image.open(image_path)422 ])423 print(response.text)424425### JavaScript426427 import { GoogleGenerativeAI } from "@google/generative-ai";428429 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");430 const model = genAI.getGenerativeModel({ model: "gemini-3.8-flash" });431432 function fileToGenerativePart(path, mimeType) {433 return {434 inlineData: {435 data: Buffer.from(fs.readFileSync(path)).toString("base64"),436 mimeType,437 },438 };439 }440441 const prompt = "Tell me a story based on this image";442443 const imagePart = fileToGenerativePart(444 `path/to/organ.jpg`,445 "image/jpeg",446 );447448 const result = await model.generateContent([prompt, imagePart]);449 console.log(result.response.text());450451### Java452453 import com.google.genai.Client;454 import com.google.genai.types.Content;455 import com.google.genai.types.GenerateContentResponse;456 import com.google.genai.types.Part;457 import java.nio.file.Files;458 import java.nio.file.Paths;459460 Client client = new Client();461462 byte[] imageBytes = Files.readAllBytes(Paths.get("path/to/organ.jpg"));463 Part imagePart = Part.fromBytes(imageBytes, "image/jpeg");464465 GenerateContentResponse response =466 client.models.generateContent(467 "gemini-3.8-flash",468 Content.fromParts(Part.fromText("Tell me a story based on this image"), imagePart),469 null);470 System.out.println(response.text());471472### Go473474 ctx := context.Background()475 client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))476 if err != nil {477 log.Fatal(err)478 }479 defer client.Close()480481 model := client.GenerativeModel("gemini-3.8-flash")482483 imgData, err := os.ReadFile("path/to/organ.jpg")484 if err != nil {485 log.Fatal(err)486 }487488 resp, err := model.GenerateContent(ctx,489 genai.Text("Tell me about this instrument"),490 genai.ImageData("jpeg", imgData))491 if err != nil {492 log.Fatal(err)493 }494495 printResponse(resp) // utility for printing response496497**After**498499### Python500501Many of the same convenience features exist in the new SDK. For502example, `PIL.Image` objects are automatically converted.503504 from google import genai505 from PIL import Image506507 client = genai.Client()508509 response = client.models.generate_content(510 model='gemini-3.8-flash',511 contents=[512 'Tell me a story based on this image',513 Image.open(image_path)514 ]515 )516 print(response.text)517518### JavaScript519520 import {GoogleGenAI} from '@google/genai';521522 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });523524 const organ = await ai.files.upload({525 file: "path/to/organ.jpg",526 });527528 const response = await ai.models.generateContent({529 model: "gemini-3.8-flash",530 contents: [531 createUserContent([532 "Tell me a story based on this image",533 createPartFromUri(organ.uri, organ.mimeType)534 ]),535 ],536 });537 console.log(response.text);538539### Java540541 import com.google.genai.Client;542 import com.google.genai.types.Content;543 import com.google.genai.types.File;544 import com.google.genai.types.GenerateContentResponse;545 import com.google.genai.types.Part;546547 Client client = new Client();548549 File organ = client.files.upload("path/to/organ.jpg", null);550551 GenerateContentResponse response =552 client.models.generateContent(553 "gemini-3.8-flash",554 Content.fromParts(555 Part.fromText("Tell me a story based on this image"),556 Part.fromUri(organ.uri().orElse(""), organ.mimeType().orElse("image/jpeg"))),557 null);558 System.out.println(response.text());559560### Go561562 ctx := context.Background()563 client, err := genai.NewClient(ctx, nil)564 if err != nil {565 log.Fatal(err)566 }567568 imgData, err := os.ReadFile("path/to/organ.jpg")569 if err != nil {570 log.Fatal(err)571 }572573 parts := []*genai.Part{574 {Text: "Tell me a story based on this image"},575 {InlineData: &genai.Blob{Data: imgData, MIMEType: "image/jpeg"}},576 }577 contents := []*genai.Content{578 {Parts: parts},579 }580581 result, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, nil)582 if err != nil {583 log.Fatal(err)584 }585 debugPrint(result) // utility for printing result586587### Streaming588589**Before**590591### Python592593 import google.generativeai as genai594595 response = model.generate_content(596 "Write a cute story about cats.",597 stream=True)598 for chunk in response:599 print(chunk.text)600601### JavaScript602603 import { GoogleGenerativeAI } from "@google/generative-ai";604605 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");606 const model = genAI.getGenerativeModel({ model: "gemini-3.8-flash" });607608 const prompt = "Write a story about a magic backpack.";609610 const result = await model.generateContentStream(prompt);611612 // Print text as it comes in.613 for await (const chunk of result.stream) {614 const chunkText = chunk.text();615 process.stdout.write(chunkText);616 }617618### Java619620 import com.google.genai.Client;621 import com.google.genai.ResponseStream;622 import com.google.genai.types.GenerateContentResponse;623624 Client client = new Client();625 String prompt = "Write a story about a magic backpack.";626627 try (ResponseStream<GenerateContentResponse> stream =628 client.models.generateContentStream("gemini-3.8-flash", prompt, null)) {629 for (GenerateContentResponse chunk : stream) {630 System.out.print(chunk.text());631 }632 }633634### Go635636 ctx := context.Background()637 client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))638 if err != nil {639 log.Fatal(err)640 }641 defer client.Close()642643 model := client.GenerativeModel("gemini-3.8-flash")644 iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))645 for {646 resp, err := iter.Next()647 if err == iterator.Done {648 break649 }650 if err != nil {651 log.Fatal(err)652 }653 printResponse(resp) // utility for printing the response654 }655656**After**657658### Python659660 from google import genai661662 client = genai.Client()663664 for chunk in client.models.generate_content_stream(665 model='gemini-3.8-flash',666 contents='Tell me a story in 300 words.'667 ):668 print(chunk.text)669670### JavaScript671672 import {GoogleGenAI} from '@google/genai';673674 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });675676 const response = await ai.models.generateContentStream({677 model: "gemini-3.8-flash",678 contents: "Write a story about a magic backpack.",679 });680 let text = "";681 for await (const chunk of response) {682 console.log(chunk.text);683 text += chunk.text;684 }685686### Java687688 import com.google.genai.Client;689 import com.google.genai.ResponseStream;690 import com.google.genai.types.GenerateContentResponse;691692 Client client = new Client();693694 try (ResponseStream<GenerateContentResponse> response =695 client.models.generateContentStream(696 "gemini-3.8-flash", "Tell me a story in 300 words.", null)) {697 for (GenerateContentResponse chunk : response) {698 System.out.println(chunk.text());699 }700 }701702### Go703704 ctx := context.Background()705 client, err := genai.NewClient(ctx, nil)706 if err != nil {707 log.Fatal(err)708 }709710 for result, err := range client.Models.GenerateContentStream(711 ctx,712 "gemini-3.8-flash",713 genai.Text("Write a story about a magic backpack."),714 nil,715 ) {716 if err != nil {717 log.Fatal(err)718 }719 fmt.Print(result.Candidates[0].Content.Parts[0].Text)720 }721722## Configuration723724**Before**725726### Python727728 import google.generativeai as genai729730 model = genai.GenerativeModel(731 'gemini-3.8-flash',732 system_instruction='you are a story teller for kids under 5 years old',733 generation_config=genai.GenerationConfig(734 max_output_tokens=400,735 top_k=2,736 top_p=0.5,737 temperature=0.5,738 response_mime_type='application/json',739 stop_sequences=['\n'],740 )741 )742 response = model.generate_content('tell me a story in 100 words')743744### JavaScript745746 import { GoogleGenerativeAI } from "@google/generative-ai";747748 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");749 const model = genAI.getGenerativeModel({750 model: "gemini-3.8-flash",751 generationConfig: {752 candidateCount: 1,753 stopSequences: ["x"],754 maxOutputTokens: 20,755 temperature: 1.0,756 },757 });758759 const result = await model.generateContent(760 "Tell me a story about a magic backpack.",761 );762 console.log(result.response.text())763764### Java765766 import com.google.genai.Client;767 import com.google.genai.types.Content;768 import com.google.genai.types.GenerateContentConfig;769 import com.google.genai.types.GenerateContentResponse;770 import com.google.genai.types.Part;771 import java.util.Arrays;772773 Client client = new Client();774775 GenerateContentConfig config =776 GenerateContentConfig.builder()777 .systemInstruction(778 Content.fromParts(Part.fromText("you are a story teller for kids under 5 years old")))779 .maxOutputTokens(400)780 .topK(2.0f)781 .topP(0.5f)782 .temperature(0.5f)783 .responseMimeType("application/json")784 .stopSequences(Arrays.asList("\n"))785 .build();786787 GenerateContentResponse response =788 client.models.generateContent("gemini-3.8-flash", "tell me a story in 100 words", config);789 System.out.println(response.text());790791### Go792793 ctx := context.Background()794 client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))795 if err != nil {796 log.Fatal(err)797 }798 defer client.Close()799800 model := client.GenerativeModel("gemini-3.8-flash")801 model.SetTemperature(0.5)802 model.SetTopP(0.5)803 model.SetTopK(2.0)804 model.SetMaxOutputTokens(100)805 model.ResponseMIMEType = "application/json"806 resp, err := model.GenerateContent(ctx, genai.Text("Tell me about New York"))807 if err != nil {808 log.Fatal(err)809 }810 printResponse(resp) // utility for printing response811812**After**813814### Python815816For all methods in the new SDK, the required arguments are provided as817keyword arguments. All optional inputs are provided in the `config`818argument. Config arguments can be specified as either Python dictionaries or819`Config` classes in the `google.genai.types` namespace. For utility and820uniformity, all definitions within the `types` module are `pydantic`821classes.822823 from google import genai824 from google.genai import types825826 client = genai.Client()827828 response = client.models.generate_content(829 model='gemini-3.8-flash',830 contents='Tell me a story in 100 words.',831 config=types.GenerateContentConfig(832 system_instruction='you are a story teller for kids under 5 years old',833 max_output_tokens= 400,834 top_k= 2,835 top_p= 0.5,836 temperature= 0.5,837 response_mime_type= 'application/json',838 stop_sequences= ['\n'],839 seed=42,840 ),841 )842843### JavaScript844845 import {GoogleGenAI} from '@google/genai';846847 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });848849 const response = await ai.models.generateContent({850 model: "gemini-3.8-flash",851 contents: "Tell me a story about a magic backpack.",852 config: {853 candidateCount: 1,854 stopSequences: ["x"],855 maxOutputTokens: 20,856 temperature: 1.0,857 },858 });859860 console.log(response.text);861862### Java863864 import com.google.genai.Client;865 import com.google.genai.types.GenerateContentConfig;866 import com.google.genai.types.GenerateContentResponse;867 import java.util.Arrays;868869 Client client = new Client();870871 GenerateContentConfig config =872 GenerateContentConfig.builder()873 .candidateCount(1)874 .stopSequences(Arrays.asList("x"))875 .maxOutputTokens(20)876 .temperature(1.0f)877 .build();878879 GenerateContentResponse response =880 client.models.generateContent(881 "gemini-3.8-flash", "Tell me a story about a magic backpack.", config);882 System.out.println(response.text());883884### Go885886 ctx := context.Background()887 client, err := genai.NewClient(ctx, nil)888 if err != nil {889 log.Fatal(err)890 }891892 result, err := client.Models.GenerateContent(ctx,893 "gemini-3.8-flash",894 genai.Text("Tell me about New York"),895 &genai.GenerateContentConfig{896 Temperature: genai.Ptr[float32](0.5),897 TopP: genai.Ptr[float32](0.5),898 TopK: genai.Ptr[float32](2.0),899 ResponseMIMEType: "application/json",900 StopSequences: []string{"Yankees"},901 CandidateCount: 2,902 Seed: genai.Ptr[int32](42),903 MaxOutputTokens: 128,904 PresencePenalty: genai.Ptr[float32](0.5),905 FrequencyPenalty: genai.Ptr[float32](0.5),906 },907 )908 if err != nil {909 log.Fatal(err)910 }911 debugPrint(result) // utility for printing response912913## Safety settings914915Generate a response with safety settings:916917**Before**918919### Python920921 import google.generativeai as genai922923 model = genai.GenerativeModel('gemini-3.8-flash')924 response = model.generate_content(925 'say something bad',926 safety_settings={927 'HATE': 'BLOCK_ONLY_HIGH',928 'HARASSMENT': 'BLOCK_ONLY_HIGH',929 }930 )931932### JavaScript933934 import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from "@google/generative-ai";935936 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");937 const model = genAI.getGenerativeModel({938 model: "gemini-3.8-flash",939 safetySettings: [940 {941 category: HarmCategory.HARM_CATEGORY_HARASSMENT,942 threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,943 },944 ],945 });946947 const unsafePrompt =948 "I support Martians Soccer Club and I think " +949 "Jupiterians Football Club sucks! Write an ironic phrase telling " +950 "them how I feel about them.";951952 const result = await model.generateContent(unsafePrompt);953954 try {955 result.response.text();956 } catch (e) {957 console.error(e);958 console.log(result.response.candidates[0].safetyRatings);959 }960961### Java962963 import com.google.genai.Client;964 import com.google.genai.types.GenerateContentConfig;965 import com.google.genai.types.GenerateContentResponse;966 import com.google.genai.types.HarmBlockThreshold;967 import com.google.genai.types.HarmCategory;968 import com.google.genai.types.SafetySetting;969 import java.util.Arrays;970971 Client client = new Client();972973 GenerateContentConfig config =974 GenerateContentConfig.builder()975 .safetySettings(976 Arrays.asList(977 SafetySetting.builder()978 .category(HarmCategory.Known.HARM_CATEGORY_HARASSMENT)979 .threshold(HarmBlockThreshold.Known.BLOCK_LOW_AND_ABOVE)980 .build()))981 .build();982983 GenerateContentResponse response =984 client.models.generateContent("gemini-3.8-flash", "say something bad", config);985 System.out.println(response.text());986987**After**988989### Python990991 from google import genai992 from google.genai import types993994 client = genai.Client()995996 response = client.models.generate_content(997 model='gemini-3.8-flash',998 contents='say something bad',999 config=types.GenerateContentConfig(1000 safety_settings= [1001 types.SafetySetting(1002 category='HARM_CATEGORY_HATE_SPEECH',1003 threshold='BLOCK_ONLY_HIGH'1004 ),1005 ]1006 ),1007 )10081009### JavaScript10101011 import {GoogleGenAI} from '@google/genai';10121013 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });1014 const unsafePrompt =1015 "I support Martians Soccer Club and I think " +1016 "Jupiterians Football Club sucks! Write an ironic phrase telling " +1017 "them how I feel about them.";10181019 const response = await ai.models.generateContent({1020 model: "gemini-3.8-flash",1021 contents: unsafePrompt,1022 config: {1023 safetySettings: [1024 {1025 category: "HARM_CATEGORY_HARASSMENT",1026 threshold: "BLOCK_ONLY_HIGH",1027 },1028 ],1029 },1030 });10311032 console.log("Finish reason:", response.candidates[0].finishReason);1033 console.log("Safety ratings:", response.candidates[0].safetyRatings);10341035### Java10361037 import com.google.genai.Client;1038 import com.google.genai.types.GenerateContentConfig;1039 import com.google.genai.types.GenerateContentResponse;1040 import com.google.genai.types.HarmBlockThreshold;1041 import com.google.genai.types.HarmCategory;1042 import com.google.genai.types.SafetySetting;1043 import java.util.Arrays;10441045 Client client = new Client();10461047 GenerateContentConfig config =1048 GenerateContentConfig.builder()1049 .safetySettings(1050 Arrays.asList(1051 SafetySetting.builder()1052 .category(HarmCategory.Known.HARM_CATEGORY_HATE_SPEECH)1053 .threshold(HarmBlockThreshold.Known.BLOCK_ONLY_HIGH)1054 .build()))1055 .build();10561057 GenerateContentResponse response =1058 client.models.generateContent("gemini-3.8-flash", "say something bad", config);1059 System.out.println("Finish reason: " + response.finishReason());10601061## Async10621063**Before**10641065### Python10661067 import google.generativeai as genai10681069 model = genai.GenerativeModel('gemini-3.8-flash')1070 response = model.generate_content_async(1071 'tell me a story in 100 words'1072 )10731074**After**10751076### Python10771078To use the new SDK with `asyncio`, there is a separate `async`1079implementation of every method under `client.aio`.10801081 from google import genai10821083 client = genai.Client()10841085 response = await client.aio.models.generate_content(1086 model='gemini-3.8-flash',1087 contents='Tell me a story in 300 words.'1088 )10891090## Chat10911092Start a chat and send a message to the model:10931094**Before**10951096### Python10971098 import google.generativeai as genai10991100 model = genai.GenerativeModel('gemini-3.8-flash')1101 chat = model.start_chat()11021103 response = chat.send_message(1104 "Tell me a story in 100 words")1105 response = chat.send_message(1106 "What happened after that?")11071108### JavaScript11091110 import { GoogleGenerativeAI } from "@google/generative-ai";11111112 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");1113 const model = genAI.getGenerativeModel({ model: "gemini-3.8-flash" });1114 const chat = model.startChat({1115 history: [1116 {1117 role: "user",1118 parts: [{ text: "Hello" }],1119 },1120 {1121 role: "model",1122 parts: [{ text: "Great to meet you. What would you like to know?" }],1123 },1124 ],1125 });1126 let result = await chat.sendMessage("I have 2 dogs in my house.");1127 console.log(result.response.text());1128 result = await chat.sendMessage("How many paws are in my house?");1129 console.log(result.response.text());11301131### Java11321133 import com.google.genai.Chat;1134 import com.google.genai.Client;1135 import com.google.genai.types.GenerateContentResponse;11361137 Client client = new Client();1138 Chat chat = client.chats.create("gemini-3.8-flash");11391140 GenerateContentResponse response1 = chat.sendMessage("Tell me a story in 100 words");1141 System.out.println(response1.text());11421143 GenerateContentResponse response2 = chat.sendMessage("What happened after that?");1144 System.out.println(response2.text());11451146### Go11471148 ctx := context.Background()1149 client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))1150 if err != nil {1151 log.Fatal(err)1152 }1153 defer client.Close()11541155 model := client.GenerativeModel("gemini-3.8-flash")1156 cs := model.StartChat()11571158 cs.History = []*genai.Content{1159 {1160 Parts: []genai.Part{1161 genai.Text("Hello, I have 2 dogs in my house."),1162 },1163 Role: "user",1164 },1165 {1166 Parts: []genai.Part{1167 genai.Text("Great to meet you. What would you like to know?"),1168 },1169 Role: "model",1170 },1171 }11721173 res, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))1174 if err != nil {1175 log.Fatal(err)1176 }1177 printResponse(res) // utility for printing the response11781179**After**11801181### Python11821183 from google import genai11841185 client = genai.Client()11861187 chat = client.chats.create(model='gemini-3.8-flash')11881189 response = chat.send_message(1190 message='Tell me a story in 100 words')1191 response = chat.send_message(1192 message='What happened after that?')11931194### JavaScript11951196 import {GoogleGenAI} from '@google/genai';11971198 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });1199 const chat = ai.chats.create({1200 model: "gemini-3.8-flash",1201 history: [1202 {1203 role: "user",1204 parts: [{ text: "Hello" }],1205 },1206 {1207 role: "model",1208 parts: [{ text: "Great to meet you. What would you like to know?" }],1209 },1210 ],1211 });12121213 const response1 = await chat.sendMessage({1214 message: "I have 2 dogs in my house.",1215 });1216 console.log("Chat response 1:", response1.text);12171218 const response2 = await chat.sendMessage({1219 message: "How many paws are in my house?",1220 });1221 console.log("Chat response 2:", response2.text);12221223### Java12241225 import com.google.genai.Chat;1226 import com.google.genai.Client;1227 import com.google.genai.types.GenerateContentResponse;12281229 Client client = new Client();1230 Chat chat = client.chats.create("gemini-3.8-flash");12311232 GenerateContentResponse response1 = chat.sendMessage("I have 2 dogs in my house.");1233 System.out.println("Chat response 1: " + response1.text());12341235 GenerateContentResponse response2 = chat.sendMessage("How many paws are in my house?");1236 System.out.println("Chat response 2: " + response2.text());12371238### Go12391240 ctx := context.Background()1241 client, err := genai.NewClient(ctx, nil)1242 if err != nil {1243 log.Fatal(err)1244 }12451246 chat, err := client.Chats.Create(ctx, "gemini-3.8-flash", nil, nil)1247 if err != nil {1248 log.Fatal(err)1249 }12501251 result, err := chat.SendMessage(ctx, genai.Part{Text: "Hello, I have 2 dogs in my house."})1252 if err != nil {1253 log.Fatal(err)1254 }1255 debugPrint(result) // utility for printing result12561257 result, err = chat.SendMessage(ctx, genai.Part{Text: "How many paws are in my house?"})1258 if err != nil {1259 log.Fatal(err)1260 }1261 debugPrint(result) // utility for printing result12621263## Function calling12641265**Before**12661267### Python12681269 import google.generativeai as genai1270 from enum import Enum12711272 def get_current_weather(location: str) -> str:1273 """Get the current whether in a given location.12741275 Args:1276 location: required, The city and state, e.g. San Franciso, CA1277 unit: celsius or fahrenheit1278 """1279 print(f'Called with: {location=}')1280 return "23C"12811282 model = genai.GenerativeModel(1283 model_name="gemini-3.8-flash",1284 tools=[get_current_weather]1285 )12861287 response = model.generate_content("What is the weather in San Francisco?")1288 function_call = response.candidates[0].parts[0].function_call12891290**After**12911292### Python12931294In the new SDK, automatic function calling is the default. Here, you disable1295it.12961297 from google import genai1298 from google.genai import types12991300 client = genai.Client()13011302 def get_current_weather(location: str) -> str:1303 """Get the current whether in a given location.13041305 Args:1306 location: required, The city and state, e.g. San Franciso, CA1307 unit: celsius or fahrenheit1308 """1309 print(f'Called with: {location=}')1310 return "23C"13111312 response = client.models.generate_content(1313 model='gemini-3.8-flash',1314 contents="What is the weather like in Boston?",1315 config=types.GenerateContentConfig(1316 tools=[get_current_weather],1317 automatic_function_calling={'disable': True},1318 ),1319 )13201321 function_call = response.candidates[0].content.parts[0].function_call13221323### Automatic function calling13241325**Before**13261327### Python13281329The old SDK only supports automatic function calling in chat. In the new SDK1330this is the default behavior in `generate_content`.13311332 import google.generativeai as genai13331334 def get_current_weather(city: str) -> str:1335 return "23C"13361337 model = genai.GenerativeModel(1338 model_name="gemini-3.8-flash",1339 tools=[get_current_weather]1340 )13411342 chat = model.start_chat(1343 enable_automatic_function_calling=True)1344 result = chat.send_message("What is the weather in San Francisco?")13451346**After**13471348### Python13491350 from google import genai1351 from google.genai import types1352 client = genai.Client()13531354 def get_current_weather(city: str) -> str:1355 return "23C"13561357 response = client.models.generate_content(1358 model='gemini-3.8-flash',1359 contents="What is the weather like in Boston?",1360 config=types.GenerateContentConfig(1361 tools=[get_current_weather]1362 ),1363 )13641365## Code execution13661367Code execution is a tool that allows the model to generate Python code, run it,1368and return the result.13691370**Before**13711372### Python13731374 import google.generativeai as genai13751376 model = genai.GenerativeModel(1377 model_name="gemini-3.8-flash",1378 tools="code_execution"1379 )13801381 result = model.generate_content(1382 "What is the sum of the first 50 prime numbers? Generate and run code for "1383 "the calculation, and make sure you get all 50.")13841385### JavaScript13861387 import { GoogleGenerativeAI } from "@google/generative-ai";13881389 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");1390 const model = genAI.getGenerativeModel({1391 model: "gemini-3.8-flash",1392 tools: [{ codeExecution: {} }],1393 });13941395 const result = await model.generateContent(1396 "What is the sum of the first 50 prime numbers? " +1397 "Generate and run code for the calculation, and make sure you get " +1398 "all 50.",1399 );14001401 console.log(result.response.text());14021403### Java14041405 import com.google.genai.Client;1406 import com.google.genai.types.GenerateContentConfig;1407 import com.google.genai.types.GenerateContentResponse;1408 import com.google.genai.types.Tool;1409 import com.google.genai.types.ToolCodeExecution;1410 import java.util.Arrays;14111412 Client client = new Client();14131414 GenerateContentConfig config =1415 GenerateContentConfig.builder()1416 .tools(1417 Arrays.asList(1418 Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build()))1419 .build();14201421 GenerateContentResponse response =1422 client.models.generateContent(1423 "gemini-3.8-flash",1424 "What is the sum of the first 50 prime numbers? Generate and run code for "1425 + "the calculation, and make sure you get all 50.",1426 config);1427 System.out.println(response.text());14281429**After**14301431### Python14321433 from google import genai1434 from google.genai import types14351436 client = genai.Client()14371438 response = client.models.generate_content(1439 model='gemini-3.8-flash',1440 contents='What is the sum of the first 50 prime numbers? Generate and run '1441 'code for the calculation, and make sure you get all 50.',1442 config=types.GenerateContentConfig(1443 tools=[types.Tool(code_execution=types.ToolCodeExecution)],1444 ),1445 )14461447### JavaScript14481449 import {GoogleGenAI} from '@google/genai';14501451 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });14521453 const response = await ai.models.generateContent({1454 model: "gemini-3.8-flash",1455 contents: `Write and execute code that calculates the sum of the first 50 prime numbers.1456 Ensure that only the executable code and its resulting output are generated.`,1457 });14581459 // Each part may contain text, executable code, or an execution result.1460 for (const part of response.candidates[0].content.parts) {1461 console.log(part);1462 console.log("\n");1463 }14641465 console.log("-".repeat(80));1466 // The `.text` accessor concatenates the parts into a markdown-formatted text.1467 console.log("\n", response.text);14681469### Java14701471 import com.google.genai.Client;1472 import com.google.genai.types.GenerateContentConfig;1473 import com.google.genai.types.GenerateContentResponse;1474 import com.google.genai.types.Part;1475 import com.google.genai.types.Tool;1476 import com.google.genai.types.ToolCodeExecution;1477 import java.util.Arrays;14781479 Client client = new Client();14801481 GenerateContentConfig config =1482 GenerateContentConfig.builder()1483 .tools(1484 Arrays.asList(1485 Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build()))1486 .build();14871488 GenerateContentResponse response =1489 client.models.generateContent(1490 "gemini-3.8-flash",1491 "Write and execute code that calculates the sum of the first 50 prime numbers. "1492 + "Ensure that only the executable code and its resulting output are generated.",1493 config);14941495 if (response.parts() != null) {1496 for (Part part : response.parts()) {1497 System.out.println(part);1498 }1499 }1500 System.out.println(response.text());15011502## Search grounding15031504`GoogleSearch` (Gemini\>=2.0) and `GoogleSearchRetrieval` (Gemini \< 2.0) are1505tools that allow the model to retrieve public web data for grounding, powered by1506Google.15071508**Before**15091510### Python15111512 import google.generativeai as genai15131514 model = genai.GenerativeModel('gemini-3.8-flash')1515 response = model.generate_content(1516 contents="what is the Google stock price?",1517 tools='google_search_retrieval'1518 )15191520**After**15211522### Python15231524 from google import genai1525 from google.genai import types15261527 client = genai.Client()15281529 response = client.models.generate_content(1530 model='gemini-3.8-flash',1531 contents='What is the Google stock price?',1532 config=types.GenerateContentConfig(1533 tools=[1534 types.Tool(1535 google_search=types.GoogleSearch()1536 )1537 ]1538 )1539 )15401541## JSON response15421543Generate answers in JSON format.15441545**Before**15461547### Python15481549By specifying a `response_schema` and setting1550`response_mime_type="application/json"` users can constrain the model to1551produce a `JSON` response following a given structure.15521553 import google.generativeai as genai1554 import typing_extensions as typing15551556 class CountryInfo(typing.TypedDict):1557 name: str1558 population: int1559 capital: str1560 continent: str1561 major_cities: list[str]1562 gdp: int1563 official_language: str1564 total_area_sq_mi: int15651566 model = genai.GenerativeModel(model_name="gemini-3.8-flash")1567 result = model.generate_content(1568 "Give me information of the United States",1569 generation_config=genai.GenerationConfig(1570 response_mime_type="application/json",1571 response_schema = CountryInfo1572 ),1573 )15741575### JavaScript15761577 import { GoogleGenerativeAI, SchemaType } from "@google/generative-ai";15781579 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");15801581 const schema = {1582 description: "List of recipes",1583 type: SchemaType.ARRAY,1584 items: {1585 type: SchemaType.OBJECT,1586 properties: {1587 recipeName: {1588 type: SchemaType.STRING,1589 description: "Name of the recipe",1590 nullable: false,1591 },1592 },1593 required: ["recipeName"],1594 },1595 };15961597 const model = genAI.getGenerativeModel({1598 model: "gemini-3.8-flash",1599 generationConfig: {1600 responseMimeType: "application/json",1601 responseSchema: schema,1602 },1603 });16041605 const result = await model.generateContent(1606 "List a few popular cookie recipes.",1607 );1608 console.log(result.response.text());16091610### Java16111612 import com.google.genai.Client;1613 import com.google.genai.types.GenerateContentConfig;1614 import com.google.genai.types.GenerateContentResponse;1615 import com.google.genai.types.Schema;1616 import com.google.genai.types.Type;1617 import java.util.Arrays;1618 import java.util.Map;16191620 Client client = new Client();16211622 Schema schema =1623 Schema.builder()1624 .description("List of recipes")1625 .type(Type.Known.ARRAY)1626 .items(1627 Schema.builder()1628 .type(Type.Known.OBJECT)1629 .properties(1630 Map.of(1631 "recipeName",1632 Schema.builder()1633 .type(Type.Known.STRING)1634 .description("Name of the recipe")1635 .build()))1636 .required(Arrays.asList("recipeName"))1637 .build())1638 .build();16391640 GenerateContentConfig config =1641 GenerateContentConfig.builder()1642 .responseMimeType("application/json")1643 .responseSchema(schema)1644 .build();16451646 GenerateContentResponse response =1647 client.models.generateContent(1648 "gemini-3.8-flash", "List a few popular cookie recipes.", config);1649 System.out.println(response.text());16501651**After**16521653### Python16541655The new SDK uses1656`pydantic` classes to provide the schema (although you can pass a1657`genai.types.Schema`, or equivalent `dict`). When possible, the SDK will1658parse the returned JSON, and return the result in `response.parsed`. If you1659provided a `pydantic` class as the schema the SDK will convert that `JSON`1660to an instance of the class.16611662 from google import genai1663 from pydantic import BaseModel16641665 client = genai.Client()16661667 class CountryInfo(BaseModel):1668 name: str1669 population: int1670 capital: str1671 continent: str1672 major_cities: list[str]1673 gdp: int1674 official_language: str1675 total_area_sq_mi: int16761677 response = client.models.generate_content(1678 model='gemini-3.8-flash',1679 contents='Give me information of the United States.',1680 config={1681 'response_mime_type': 'application/json',1682 'response_schema': CountryInfo,1683 },1684 )16851686 response.parsed16871688### JavaScript16891690 import {GoogleGenAI} from '@google/genai';16911692 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });1693 const response = await ai.models.generateContent({1694 model: "gemini-3.8-flash",1695 contents: "List a few popular cookie recipes.",1696 config: {1697 responseMimeType: "application/json",1698 responseSchema: {1699 type: "array",1700 items: {1701 type: "object",1702 properties: {1703 recipeName: { type: "string" },1704 ingredients: { type: "array", items: { type: "string" } },1705 },1706 required: ["recipeName", "ingredients"],1707 },1708 },1709 },1710 });1711 console.log(response.text);17121713### Java17141715 import com.google.genai.Client;1716 import com.google.genai.types.GenerateContentConfig;1717 import com.google.genai.types.GenerateContentResponse;1718 import com.google.genai.types.Schema;1719 import com.google.genai.types.Type;1720 import java.util.Arrays;1721 import java.util.Map;17221723 Client client = new Client();17241725 Schema schema =1726 Schema.builder()1727 .type(Type.Known.ARRAY)1728 .items(1729 Schema.builder()1730 .type(Type.Known.OBJECT)1731 .properties(1732 Map.of(1733 "recipeName", Schema.builder().type(Type.Known.STRING).build(),1734 "ingredients",1735 Schema.builder()1736 .type(Type.Known.ARRAY)1737 .items(Schema.builder().type(Type.Known.STRING).build())1738 .build()))1739 .required(Arrays.asList("recipeName", "ingredients"))1740 .build())1741 .build();17421743 GenerateContentConfig config =1744 GenerateContentConfig.builder()1745 .responseMimeType("application/json")1746 .responseSchema(schema)1747 .build();17481749 GenerateContentResponse response =1750 client.models.generateContent(1751 "gemini-3.8-flash", "List a few popular cookie recipes.", config);1752 System.out.println(response.text());17531754## Files17551756### Upload17571758Upload a file:17591760**Before**17611762### Python17631764 import requests1765 import pathlib1766 import google.generativeai as genai17671768 # Download file1769 response = requests.get(1770 'https://storage.googleapis.com/generativeai-downloads/data/a11.txt')1771 pathlib.Path('a11.txt').write_text(response.text)17721773 file = genai.upload_file(path='a11.txt')17741775 model = genai.GenerativeModel('gemini-3.8-flash')1776 response = model.generate_content([1777 'Can you summarize this file:',1778 my_file1779 ])1780 print(response.text)17811782**After**17831784### Python17851786 import requests1787 import pathlib1788 from google import genai17891790 client = genai.Client()17911792 # Download file1793 response = requests.get(1794 'https://storage.googleapis.com/generativeai-downloads/data/a11.txt')1795 pathlib.Path('a11.txt').write_text(response.text)17961797 my_file = client.files.upload(file='a11.txt')17981799 response = client.models.generate_content(1800 model='gemini-3.8-flash',1801 contents=[1802 'Can you summarize this file:',1803 my_file1804 ]1805 )1806 print(response.text)18071808### List and get18091810List uploaded files and get an uploaded file with a filename:18111812**Before**18131814### Python18151816 import google.generativeai as genai18171818 for file in genai.list_files():1819 print(file.name)18201821 file = genai.get_file(name=file.name)18221823**After**18241825### Python18261827 from google import genai1828 client = genai.Client()18291830 for file in client.files.list():1831 print(file.name)18321833 file = client.files.get(name=file.name)18341835### Delete18361837Delete a file:18381839**Before**18401841### Python18421843 import pathlib1844 import google.generativeai as genai18451846 pathlib.Path('dummy.txt').write_text(dummy)1847 dummy_file = genai.upload_file(path='dummy.txt')18481849 file = genai.delete_file(name=dummy_file.name)18501851**After**18521853### Python18541855 import pathlib1856 from google import genai18571858 client = genai.Client()18591860 pathlib.Path('dummy.txt').write_text(dummy)1861 dummy_file = client.files.upload(file='dummy.txt')18621863 response = client.files.delete(name=dummy_file.name)18641865## Context caching18661867Context caching allows the user to pass the content to the model once, cache the1868input tokens, and then refer to the cached tokens in subsequent calls to lower1869the cost.18701871**Before**18721873### Python18741875 import requests1876 import pathlib1877 import google.generativeai as genai1878 from google.generativeai import caching18791880 # Download file1881 response = requests.get(1882 'https://storage.googleapis.com/generativeai-downloads/data/a11.txt')1883 pathlib.Path('a11.txt').write_text(response.text)18841885 # Upload file1886 document = genai.upload_file(path="a11.txt")18871888 # Create cache1889 apollo_cache = caching.CachedContent.create(1890 model="gemini-3.8-flash",1891 system_instruction="You are an expert at analyzing transcripts.",1892 contents=[document],1893 )18941895 # Generate response1896 apollo_model = genai.GenerativeModel.from_cached_content(1897 cached_content=apollo_cache1898 )1899 response = apollo_model.generate_content("Find a lighthearted moment from this transcript")19001901### JavaScript19021903 import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";1904 import { GoogleGenerativeAI } from "@google/generative-ai";19051906 const cacheManager = new GoogleAICacheManager("GEMINI_API_KEY");1907 const fileManager = new GoogleAIFileManager("GEMINI_API_KEY");19081909 const uploadResult = await fileManager.uploadFile("path/to/a11.txt", {1910 mimeType: "text/plain",1911 });19121913 const cacheResult = await cacheManager.create({1914 model: "models/gemini-3.8-flash",1915 contents: [1916 {1917 role: "user",1918 parts: [1919 {1920 fileData: {1921 fileUri: uploadResult.file.uri,1922 mimeType: uploadResult.file.mimeType,1923 },1924 },1925 ],1926 },1927 ],1928 });19291930 console.log(cacheResult);19311932 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");1933 const model = genAI.getGenerativeModelFromCachedContent(cacheResult);1934 const result = await model.generateContent(1935 "Please summarize this transcript.",1936 );1937 console.log(result.response.text());19381939### Java19401941 import com.google.genai.Client;1942 import com.google.genai.types.CachedContent;1943 import com.google.genai.types.Content;1944 import com.google.genai.types.CreateCachedContentConfig;1945 import com.google.genai.types.File;1946 import com.google.genai.types.GenerateContentConfig;1947 import com.google.genai.types.GenerateContentResponse;1948 import com.google.genai.types.Part;1949 import java.util.Arrays;19501951 Client client = new Client();19521953 File uploadResult = client.files.upload("path/to/a11.txt", null);19541955 CachedContent cacheResult =1956 client.caches.create(1957 "gemini-3.8-flash",1958 CreateCachedContentConfig.builder()1959 .contents(1960 Arrays.asList(1961 Content.fromParts(1962 Part.fromUri(1963 uploadResult.uri().orElse(""),1964 uploadResult.mimeType().orElse("text/plain")))))1965 .systemInstruction(1966 Content.fromParts(Part.fromText("You are an expert at analyzing transcripts.")))1967 .build());19681969 GenerateContentResponse response =1970 client.models.generateContent(1971 "gemini-3.8-flash",1972 "Please summarize this transcript.",1973 GenerateContentConfig.builder().cachedContent(cacheResult.name().orElse("")).build());1974 System.out.println(response.text());19751976**After**19771978### Python19791980 import requests1981 import pathlib1982 from google import genai1983 from google.genai import types19841985 client = genai.Client()19861987 # Check which models support caching.1988 for m in client.models.list():1989 for action in m.supported_actions:1990 if action == "createCachedContent":1991 print(m.name)1992 break19931994 # Download file1995 response = requests.get(1996 'https://storage.googleapis.com/generativeai-downloads/data/a11.txt')1997 pathlib.Path('a11.txt').write_text(response.text)19981999 # Upload file2000 document = client.files.upload(file='a11.txt')20012002 # Create cache2003 model='gemini-3.8-flash'2004 apollo_cache = client.caches.create(2005 model=model,2006 config={2007 'contents': [document],2008 'system_instruction': 'You are an expert at analyzing transcripts.',2009 },2010 )20112012 # Generate response2013 response = client.models.generate_content(2014 model=model,2015 contents='Find a lighthearted moment from this transcript',2016 config=types.GenerateContentConfig(2017 cached_content=apollo_cache.name,2018 )2019 )20202021### JavaScript20222023 import {GoogleGenAI} from '@google/genai';20242025 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });2026 const filePath = path.join(media, "a11.txt");2027 const document = await ai.files.upload({2028 file: filePath,2029 config: { mimeType: "text/plain" },2030 });2031 console.log("Uploaded file name:", document.name);2032 const modelName = "gemini-3.8-flash";20332034 const contents = [2035 createUserContent(createPartFromUri(document.uri, document.mimeType)),2036 ];20372038 const cache = await ai.caches.create({2039 model: modelName,2040 config: {2041 contents: contents,2042 systemInstruction: "You are an expert analyzing transcripts.",2043 },2044 });2045 console.log("Cache created:", cache);20462047 const response = await ai.models.generateContent({2048 model: modelName,2049 contents: "Please summarize this transcript",2050 config: { cachedContent: cache.name },2051 });2052 console.log("Response text:", response.text);20532054### Java20552056 import com.google.genai.Client;2057 import com.google.genai.types.CachedContent;2058 import com.google.genai.types.Content;2059 import com.google.genai.types.CreateCachedContentConfig;2060 import com.google.genai.types.File;2061 import com.google.genai.types.GenerateContentConfig;2062 import com.google.genai.types.GenerateContentResponse;2063 import com.google.genai.types.Part;2064 import java.util.Arrays;20652066 Client client = new Client();20672068 File document = client.files.upload("a11.txt", null);2069 String modelName = "gemini-3.8-flash";20702071 CachedContent cache =2072 client.caches.create(2073 modelName,2074 CreateCachedContentConfig.builder()2075 .contents(2076 Arrays.asList(2077 Content.fromParts(2078 Part.fromUri(2079 document.uri().orElse(""), document.mimeType().orElse("text/plain")))))2080 .systemInstruction(2081 Content.fromParts(Part.fromText("You are an expert analyzing transcripts.")))2082 .build());20832084 GenerateContentResponse response =2085 client.models.generateContent(2086 modelName,2087 "Find a lighthearted moment from this transcript",2088 GenerateContentConfig.builder().cachedContent(cache.name().orElse("")).build());2089 System.out.println(response.text());20902091## Count tokens20922093Count the number of tokens in a request.20942095**Before**20962097### Python20982099 import google.generativeai as genai21002101 model = genai.GenerativeModel('gemini-3.8-flash')2102 response = model.count_tokens(2103 'The quick brown fox jumps over the lazy dog.')21042105### JavaScript21062107 import { GoogleGenerativeAI } from "@google/generative-ai";21082109 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");2110 const model = genAI.getGenerativeModel({2111 model: "gemini-3.8-flash",2112 });21132114 // Count tokens in a prompt without calling text generation.2115 const countResult = await model.countTokens(2116 "The quick brown fox jumps over the lazy dog.",2117 );21182119 console.log(countResult.totalTokens); // 1121202121 const generateResult = await model.generateContent(2122 "The quick brown fox jumps over the lazy dog.",2123 );21242125 // On the response for `generateContent`, use `usageMetadata`2126 // to get separate input and output token counts2127 // (`promptTokenCount` and `candidatesTokenCount`, respectively),2128 // as well as the combined token count (`totalTokenCount`).2129 console.log(generateResult.response.usageMetadata);2130 // candidatesTokenCount and totalTokenCount depend on response, may vary2131 // { promptTokenCount: 11, candidatesTokenCount: 124, totalTokenCount: 135 }21322133### Java21342135 import com.google.genai.Client;2136 import com.google.genai.types.CountTokensResponse;2137 import com.google.genai.types.GenerateContentResponse;21382139 Client client = new Client();2140 String prompt = "The quick brown fox jumps over the lazy dog.";21412142 CountTokensResponse countResult = client.models.countTokens("gemini-3.8-flash", prompt, null);2143 System.out.println(countResult.totalTokens().orElse(0));21442145 GenerateContentResponse generateResult =2146 client.models.generateContent("gemini-3.8-flash", prompt, null);2147 System.out.println(generateResult.usageMetadata());21482149**After**21502151### Python21522153 from google import genai21542155 client = genai.Client()21562157 response = client.models.count_tokens(2158 model='gemini-3.8-flash',2159 contents='The quick brown fox jumps over the lazy dog.',2160 )21612162### JavaScript21632164 import {GoogleGenAI} from '@google/genai';21652166 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });2167 const prompt = "The quick brown fox jumps over the lazy dog.";2168 const countTokensResponse = await ai.models.countTokens({2169 model: "gemini-3.8-flash",2170 contents: prompt,2171 });2172 console.log(countTokensResponse.totalTokens);21732174 const generateResponse = await ai.models.generateContent({2175 model: "gemini-3.8-flash",2176 contents: prompt,2177 });2178 console.log(generateResponse.usageMetadata);21792180### Java21812182 import com.google.genai.Client;2183 import com.google.genai.types.CountTokensResponse;2184 import com.google.genai.types.GenerateContentResponse;21852186 Client client = new Client();2187 String prompt = "The quick brown fox jumps over the lazy dog.";21882189 CountTokensResponse countTokensResponse =2190 client.models.countTokens("gemini-3.8-flash", prompt, null);2191 System.out.println(countTokensResponse.totalTokens().orElse(0));21922193 GenerateContentResponse generateResponse =2194 client.models.generateContent("gemini-3.8-flash", prompt, null);2195 System.out.println(generateResponse.usageMetadata());21962197## Generate images21982199Generate images:22002201**Before**22022203### Python22042205 #pip install https://github.com/google-gemini/generative-ai-python@imagen2206 import google.generativeai as genai22072208 imagen = genai.ImageGenerationModel(2209 "imagen-3.0-generate-001")2210 gen_images = imagen.generate_images(2211 prompt="Robot holding a red skateboard",2212 number_of_images=1,2213 safety_filter_level="block_low_and_above",2214 person_generation="allow_adult",2215 aspect_ratio="3:4",2216 )22172218**After**22192220### Python22212222 from google import genai22232224 client = genai.Client()22252226 gen_images = client.models.generate_images(2227 model='gemini-2.5-flash-image',2228 prompt='Robot holding a red skateboard',2229 config=types.GenerateImagesConfig(2230 number_of_images= 1,2231 safety_filter_level= "BLOCK_LOW_AND_ABOVE",2232 person_generation= "ALLOW_ADULT",2233 aspect_ratio= "3:4",2234 )2235 )22362237 for n, image in enumerate(gen_images.generated_images):2238 pathlib.Path(f'{n}.png').write_bytes(2239 image.image.image_bytes)22402241## Embed content22422243Generate content embeddings.22442245**Before**22462247### Python22482249 import google.generativeai as genai22502251 response = genai.embed_content(2252 model='models/gemini-embedding-001',2253 content='Hello world'2254 )22552256### JavaScript22572258 import { GoogleGenerativeAI } from "@google/generative-ai";22592260 const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");2261 const model = genAI.getGenerativeModel({2262 model: "gemini-embedding-001",2263 });22642265 const result = await model.embedContent("Hello world!");22662267 console.log(result.embedding);22682269### Java22702271 import com.google.genai.Client;2272 import com.google.genai.types.EmbedContentResponse;22732274 Client client = new Client();22752276 EmbedContentResponse response =2277 client.models.embedContent("gemini-embedding-001", "Hello world!", null);2278 System.out.println(response.embeddings());22792280**After**22812282### Python22832284 from google import genai22852286 client = genai.Client()22872288 response = client.models.embed_content(2289 model='gemini-embedding-001',2290 contents='Hello world',2291 )22922293### JavaScript22942295 import {GoogleGenAI} from '@google/genai';22962297 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });2298 const text = "Hello World!";2299 const result = await ai.models.embedContent({2300 model: "gemini-embedding-001",2301 contents: text,2302 config: { outputDimensionality: 10 },2303 });2304 console.log(result.embeddings);23052306### Java23072308 import com.google.genai.Client;2309 import com.google.genai.types.EmbedContentConfig;2310 import com.google.genai.types.EmbedContentResponse;23112312 Client client = new Client();2313 String text = "Hello World!";23142315 EmbedContentResponse result =2316 client.models.embedContent(2317 "gemini-embedding-001",2318 text,2319 EmbedContentConfig.builder().outputDimensionality(10).build());2320 System.out.println(result.embeddings());