### Create and Get Cached Content (Python) Source: https://ai.google.dev/api/caching Demonstrates creating a cache with a document and system instruction, then retrieving it using the client library. Ensure the 'google-generativeai' library is installed. ```python from google import genai client = genai.Client() document = client.files.upload(file=media / "a11.txt") model_name = "gemini-3.5-flash" cache = client.caches.create( model=model_name, config={ "contents": [document], "system_instruction": "You are an expert analyzing transcripts.", }, ) print(client.caches.get(name=cache.name)) cache.py ``` -------------------------------- ### Create Initial Chat with System Instruction Source: https://ai.google.dev/api/caching Starts a new chat session with a specified model and a system instruction to guide the AI's behavior. The system instruction is provided as a user-role content. ```go modelName := "gemini-3.5-flash" systemInstruction := "You are an expert analyzing transcripts." // Create initial chat with a system instruction. chat, err := client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{ SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser), }, nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Example Response for ListWebhooks Source: https://ai.google.dev/api/webhooks An example of the response body when listing webhooks, including webhook details and pagination information. ```json { "webhooks": [ { "name": "string", "uri": "string", "subscribed_events": [ "batch.succeeded" ], "create_time": "string", "update_time": "string", "signing_secrets": [ { "truncated_secret": "string", "expire_time": "string" } ], "state": "enabled", "new_signing_secret": "string", "id": "string" } ], "next_page_token": "string" } ``` -------------------------------- ### Agent Response Example Source: https://ai.google.dev/api/agents?hl=pl This is an example of a successful response when creating or retrieving an agent. It includes details like ID, display name, system instructions, and tools. ```json { "id": "ag_abc123", "display_name": "My Research Agent", "system_instruction": "You are a helpful research assistant.", "tools": [ { "type": "google_search" } ], "object": "agent", "created": "2025-11-26T12:25:15Z", "updated": "2025-11-26T12:25:15Z" } ``` ```json { "id": "data-analyst-abc123", "system_instruction": "You are a data analyst. Always include visualizations and export results as PDF.", "object": "agent", "created": "2025-11-26T12:25:15Z", "updated": "2025-11-26T12:25:15Z" } ``` ```json { "id": "my-data-analyst", "system_instruction": "You are a data analyst. Use the template at /workspace/template.py for all reports.", "object": "agent", "created": "2025-11-26T12:25:15Z", "updated": "2025-11-26T12:25:15Z" } ``` -------------------------------- ### BidiGenerateMusicSetupComplete Source: https://ai.google.dev/api/live_music Indicates that the music generation setup is complete. ```APIDOC ## BidiGenerateMusicSetupComplete ### Description Sent in response to a `BidiGenerateMusicSetup` message from the client. This type has no fields. ``` -------------------------------- ### Interaction Created Event Source: https://ai.google.dev/api/interactions-api-v1?hl=zh-cn Example payload for an interaction.created event, indicating the start of an interaction. ```APIDOC ## Interaction Created Event ### Description This event signifies the creation of a new interaction. ### Event Type `interaction.created` ### Request Example ```json { "event_type": "interaction.created", "interaction": { "id": "v1_ChdXS0l4YWZXTk9xbk0xZThQczhEcmlROBIXV0tJeGFmV05PcW5NMWU4UHM4RHJpUTg", "model": "gemini-3.5-flash", "status": "in_progress", "created": "2025-12-04T15:01:45Z", "updated": "2025-12-04T15:01:45Z" }, "event_id": "evt_123" } ``` ### Response Example (No specific response example provided for this event type in the source.) ``` ```APIDOC ## Interaction Created Event (Alternative Model) ### Description An alternative example of an interaction.created event, showing a different model identifier. ### Event Type `interaction.created` ### Request Example ```json { "event_type": "interaction.created", "interaction": { "id": "v1_ChdXS0l4YWZXTk9xbk0xZThQczhEcmlROBIXV0tJeGFmV05PcW5NMWU4UHM4RHJpUTg", "model": "gemini-3-flash-preview", "object": "interaction", "status": "in_progress" }, "event_id": "evt_123" } ``` ### Response Example (No specific response example provided for this event type in the source.) ``` -------------------------------- ### Upload Video and Generate Content with Go Source: https://ai.google.dev/api/files This Go example demonstrates uploading a video file and using it for content generation. It includes polling for file processing status and requires the genai Go package. Ensure context and error handling are properly managed. ```go ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } myfile, err := client.Files.UploadFromPath( ctx, filepath.Join(getMedia(), "Big_Buck_Bunny.mp4"), &genai.UploadFileConfig{ MIMEType : "video/mp4", }, ) if err != nil { log.Fatal(err) } fmt.Printf("myfile=%+v\n", myfile) // Poll until the video file is completely processed (state becomes ACTIVE). for myfile.State == genai.FileStateUnspecified || myfile.State != genai.FileStateActive { fmt.Println("Processing video...") fmt.Println("File state:", myfile.State) time.Sleep(5 * time.Second) myfile, err = client.Files.Get(ctx, myfile.Name, nil) if err != nil { log.Fatal(err) } } parts := []*genai.Part{ genai.NewPartFromURI(myfile.URI, myfile.MIMEType), genai.NewPartFromText("Describe this video clip"), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil) if err != nil { log.Fatal(err) } text := response.Text() fmt.Printf("result.text=%s\n", text) files.go ``` -------------------------------- ### Generate Content with System Instruction (Go) Source: https://ai.google.dev/api/generate-content This Go snippet demonstrates how to generate content with a system instruction. It shows how to set up the client and pass a system instruction as a genai.Content object. ```go ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } // Construct the user message contents. contents := []*genai.Content{ genai.NewContentFromText("Good morning! How are you?", genai.RoleUser), } // Set the system instruction as a *genai.Content. config := &genai.GenerateContentConfig{ SystemInstruction: genai.NewContentFromText("You are a cat. Your name is Neko.", genai.RoleUser), } response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, config) if err != nil { log.Fatal(err) } printResponse(response) system_instruction.go ``` -------------------------------- ### Get Gemini Model Information (Python) Source: https://ai.google.dev/api/models Retrieves metadata for a specific Gemini model. Ensure the 'google-generativeai' library is installed. ```python from google import genai client = genai.Client() model_info = client.models.get(model="gemini-3.5-flash") print(model_info) ``` -------------------------------- ### Create and Use Cache with Go Source: https://ai.google.dev/api/caching?hl=hi This Go snippet demonstrates uploading a file, creating a cache, and then using the cache for content generation. ```go ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } modelName := "gemini-3.5-flash" document, err := client.Files.UploadFromPath( ctx, filepath.Join(getMedia(), "a11.txt"), &genai.UploadFileConfig{ MIMEType : "text/plain", }, ) if err != nil { log.Fatal(err) } parts := []*genai.Part{ genai.NewPartFromURI(document.URI, document.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{ Contents: contents, SystemInstruction: genai.NewContentFromText( "You are an expert analyzing transcripts.", genai.RoleUser, ), }) if err != nil { log.Fatal(err) } cacheName := cache.Name // Later retrieve the cache. cache, err = client.Caches.Get(ctx, cacheName, &genai.GetCachedContentConfig{}) if err != nil { log.Fatal(err) } response, err := client.Models.GenerateContent( ctx, modelName, genai.Text("Find a lighthearted moment from this transcript"), &genai.GenerateContentConfig{ CachedContent: cache.Name, }, ) if err != nil { log.Fatal(err) } fmt.Println("Response from cache (create from name):") printResponse(response) ``` -------------------------------- ### JavaScript Function Calling Example Source: https://ai.google.dev/api/generate-content This example shows how to define functions, declare them for the model, generate content with function calling enabled, and then invoke the appropriate function based on the model's response. It covers the entire workflow from setup to handling the final result. ```javascript // Make sure to include the following import: // import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }); /** * The add function returns the sum of two numbers. * @param {number} a * @param {number} b * @returns {number} */ function add(a, b) { return a + b; } /** * The subtract function returns the difference (a - b). * @param {number} a * @param {number} b * @returns {number} */ function subtract(a, b) { return a - b; } /** * The multiply function returns the product of two numbers. * @param {number} a * @param {number} b * @returns {number} */ function multiply(a, b) { return a * b; } /** * The divide function returns the quotient of a divided by b. * @param {number} a * @param {number} b * @returns {number} */ function divide(a, b) { return a / b; } const addDeclaration = { name: "addNumbers", parameters: { type: "object", description: "Return the result of adding two numbers.", properties: { firstParam: { type: "number", description: "The first parameter which can be an integer or a floating point number.", }, secondParam: { type: "number", description: "The second parameter which can be an integer or a floating point number.", }, }, required: ["firstParam", "secondParam"], }, }; const subtractDeclaration = { name: "subtractNumbers", parameters: { type: "object", description: "Return the result of subtracting the second number from the first.", properties: { firstParam: { type: "number", description: "The first parameter.", }, secondParam: { type: "number", description: "The second parameter.", }, }, required: ["firstParam", "secondParam"], }, }; const multiplyDeclaration = { name: "multiplyNumbers", parameters: { type: "object", description: "Return the product of two numbers.", properties: { firstParam: { type: "number", description: "The first parameter.", }, secondParam: { type: "number", description: "The second parameter.", }, }, required: ["firstParam", "secondParam"], }, }; const divideDeclaration = { name: "divideNumbers", parameters: { type: "object", description: "Return the quotient of dividing the first number by the second.", properties: { firstParam: { type: "number", description: "The first parameter.", }, secondParam: { type: "number", description: "The second parameter.", }, }, required: ["firstParam", "secondParam"], }, }; // Step 1: Call generateContent with function calling enabled. const generateContentResponse = await ai.models.generateContent({ model: "gemini-3.5-flash", contents: "I have 57 cats, each owns 44 mittens, how many mittens is that in total?", config: { toolConfig: { functionCallingConfig: { mode: FunctionCallingConfigMode.ANY, }, }, tools: [ { functionDeclarations: [ addDeclaration, subtractDeclaration, multiplyDeclaration, divideDeclaration, ], }, ], }, }); // Step 2: Extract the function call.( // Assuming the response contains a 'functionCalls' array. const functionCall = generateContentResponse.functionCalls && generateContentResponse.functionCalls[0]; console.log(functionCall); // Parse the arguments. const args = functionCall.args; // Expected args format: { firstParam: number, secondParam: number } // Step 3: Invoke the actual function based on the function name. const functionMapping = { addNumbers: add, subtractNumbers: subtract, multiplyNumbers: multiply, divideNumbers: divide, }; const func = functionMapping[functionCall.name]; if (!func) { console.error("Unimplemented error:", functionCall.name); return generateContentResponse; } const resultValue = func(args.firstParam, args.secondParam); console.log("Function result:", resultValue); // Step 4: Use the chat API to send the result as the final answer. const chat = ai.chats.create({ model: "gemini-3.5-flash" }); const chatResponse = await chat.sendMessage({ message: "The final result is " + resultValue, }); console.log(chatResponse.text); return chatResponse; } function_calling.js ``` -------------------------------- ### Establish and Use Live Session Source: https://ai.google.dev/api/live Example of establishing a live WebSocket connection, sending an initial message, and then receiving subsequent messages from the server. ```python async with client.aio.live.connect(model='...', config=config) as session: await session.send(input='Hello world!', end_of_turn=True) async for message in session.receive(): print(message) ``` -------------------------------- ### Start a chat with history in Java Source: https://ai.google.dev/api/generate-content?hl=id Initiates a chat session with the Gemini API, providing initial conversation history. This Java example uses the client library to manage the chat. ```Java Client client = new Client(); Content userContent = Content.fromParts(Part.fromText("Hello")); Content modelContent = Content.builder() .role("model") .parts( Collections.singletonList( Part.fromText("Great to meet you. What would you like to know?") ) ).build(); Chat chat = client.chats.create( "gemini-3.5-flash", GenerateContentConfig.builder() .systemInstruction(userContent) .systemInstruction(modelContent) .build() ); GenerateContentResponse response1 = chat.sendMessage("I have 2 dogs in my house."); System.out.println(response1.text()); GenerateContentResponse response2 = chat.sendMessage("How many paws are in my house?"); System.out.println(response2.text()); ChatSession.java ``` -------------------------------- ### Count tokens and generate content in Go Source: https://ai.google.dev/api/tokens This Go example shows how to count tokens and generate content using the `genai` client. It includes error handling and demonstrates converting text prompts into the required `Content` format. ```go ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } prompt := "The quick brown fox jumps over the lazy dog." // Convert prompt to a slice of *genai.Content using the helper. contents := []*genai.Content{ genai.NewContentFromText(prompt, genai.RoleUser), } countResp, err := client.Models.CountTokens(ctx, "gemini-3.5-flash", contents, nil) if err != nil { return err } fmt.Println("total_tokens:", countResp.TotalTokens) response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil) if err != nil { log.Fatal(err) } usageMetadata, err := json.MarshalIndent(response.UsageMetadata, "", " ") if err != nil { log.Fatal(err) } fmt.Println(string(usageMetadata)) count_tokens.go ``` -------------------------------- ### Get File Metadata (Go) Source: https://ai.google.dev/api/files Retrieves file metadata in Go. This example includes error handling for client creation and file retrieval. Ensure the GEMINI_API_KEY environment variable is set. ```Go ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } misfile, err := client.Files.UploadFromPath( ctx, filepath.Join(getMedia(), "poem.txt"), &genai.UploadFileConfig{ MIMEType: "text/plain", }, ) if err != nil { log.Fatal(err) } fileName := myfile.Name fmt.Println(fileName) file, err := client.Files.Get(ctx, fileName, nil) if err != nil { log.Fatal(err) } fmt.Println(file) files.go ``` -------------------------------- ### Generate Content with System Instruction (Python) Source: https://ai.google.dev/api/generate-content This Python snippet demonstrates generating content with a system instruction. It shows how to set up the client and configure a system instruction for the model's behavior. ```python from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model="gemini-3.5-flash", contents="Good morning! How are you?", config=types.GenerateContentConfig( system_instruction="You are a cat. Your name is Neko." ), ) print(response.text) system_instruction.py ``` -------------------------------- ### Generate Content with Basic Configuration Source: https://ai.google.dev/api/generate-content This snippet shows how to generate content using a specified model and basic configuration parameters like candidate count, stop sequences, max output tokens, and temperature. ```Go ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } // Create local variables for parameters. candidateCount := int32(1) maxOutputTokens := int32(20) temperature := float32(1.0) response, err := client.Models.GenerateContent( ctx, "gemini-3.5-flash", genai.Text("Tell me a story about a magic backpack."), &genai.GenerateContentConfig{ CandidateCount: candidateCount, StopSequences: []string{"x"}, MaxOutputTokens: maxOutputTokens, Temperature: &temperature, }, ) if err != nil { log.Fatal(err) } printResponse(response) configure_model_parameters.go ``` -------------------------------- ### StartSensitivity Enum Source: https://ai.google.dev/api/live Determines how the start of speech is detected. Options include unspecified, high sensitivity (detects start more often), and low sensitivity (detects start less often). ```APIDOC ## Enum: StartSensitivity ### Description Determines how start of speech is detected. ### Values - `START_SENSITIVITY_UNSPECIFIED`: The default is START_SENSITIVITY_HIGH. - `START_SENSITIVITY_HIGH`: Automatic detection will detect the start of speech more often. - `START_SENSITIVITY_LOW`: Automatic detection will detect the start of speech less often. ``` -------------------------------- ### BidiGenerateContentSetupComplete Source: https://ai.google.dev/api/live Sent in response to a `BidiGenerateContentSetup` message from the client, indicating setup is complete. ```APIDOC ## BidiGenerateContentSetupComplete ### Description Sent in response to a `BidiGenerateContentSetup` message from the client. ### Fields This type has no fields. ``` -------------------------------- ### Agent Response Example Source: https://ai.google.dev/api/agents?hl=vi An example of a successful response when retrieving agent details. ```APIDOC ## Get Agent More ### Description Retrieves detailed information about a specific agent. ### Method GET ### Endpoint `/agents/{agent_id}` ### Response #### Success Response (200) - **id** (string, optional) - The unique identifier for the agent. - **display_name** (string, optional) - The display name of the agent. - **system_instruction** (string, optional) - System instruction for the agent. - **tools** (array, optional) - The tools available to the agent. - Each element can be of type `CodeExecution`, `GoogleSearch`, `UrlContext`, or `Mcpserver`. - **object** (string) - The type of object returned, always "agent". - **created** (string) - Timestamp of agent creation. - **updated** (string) - Timestamp of last agent update. #### Response Example ```json { "id": "ag_abc123", "display_name": "My Research Agent", "system_instruction": "You are a helpful research assistant.", "tools": [ { "type": "google_search" } ], "object": "agent", "created": "2025-11-26T12:25:15Z", "updated": "2025-11-26T12:25:15Z" } ``` ``` -------------------------------- ### Create and Delete Cache (Go) Source: https://ai.google.dev/api/caching Demonstrates creating a cache with a file and then deleting it in Go. Requires setting up the GenAI client with an API key. ```go ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } modelName := "gemini-3.5-flash" document, err := client.Files.UploadFromPath( ctx, filepath.Join(getMedia(), "a11.txt"), &genai.UploadFileConfig{ MIMEType : "text/plain", }, ) if err != nil { log.Fatal(err) } parts := []*genai.Part{ genai.NewPartFromURI(document.URI, document.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{ Contents: contents, SystemInstruction: genai.NewContentFromText( "You are an expert analyzing transcripts.", genai.RoleUser, ), }) if err != nil { log.Fatal(err) } _, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{}) if err != nil { log.Fatal(err) } fmt.Println("Cache deleted:", cache.Name) cache.go ``` -------------------------------- ### Example Response for RotateSigningSecret Source: https://ai.google.dev/api/webhooks An example of the response body when a new signing secret is successfully generated. ```json { "secret": "string" } ``` -------------------------------- ### Generate Content with System Instruction (Java) Source: https://ai.google.dev/api/generate-content Java example for generating content with a system instruction. This requires the Google Generative AI client library. ```java Client client = new Client(); Part textPart = Part.builder().text("You are a cat. Your name is Neko.").build(); Content content = Content.builder().role("system").parts(ImmutableList.of(textPart)).build(); GenerateContentConfig config = GenerateContentConfig.builder() .systemInstruction(content) .build(); GenerateContentResponse response = client.models.generateContent( "gemini-3.5-flash", "Good morning! How are you?", config); System.out.println(response.text()); ``` -------------------------------- ### Text Content Example Source: https://ai.google.dev/api/interactions-api-v1?hl=fa Example of a text content block. This is used for simple text responses. ```json { "type": "text", "text": "Hello, how are you?" } ``` -------------------------------- ### Interaction Response Examples Source: https://ai.google.dev/api/interactions-api-v1?hl=he Examples of responses from the Interactions API, showcasing different interaction states and content types. ```APIDOC ## Interaction Response ### Description Returns an Interaction resource, which represents a turn in a conversation or a model's output. ### Response #### Success Response (200) - **created** (string) - Timestamp of when the interaction was created. - **id** (string) - Unique identifier for the interaction. - **model** (string) - The model used for the interaction. - **object** (string) - Type of the object, typically 'interaction'. - **steps** (array) - A list of steps in the interaction, which can be model output or function calls. - **type** (string) - Type of the step (e.g., 'model_output', 'function_call'). - **content** (array, optional) - Content of the model output, if applicable. - **type** (string) - Type of content (e.g., 'text'). - **text** (string) - The text content. - **id** (string, optional) - Identifier for a function call step. - **name** (string, optional) - Name of the function called. - **arguments** (object, optional) - Arguments passed to the function. - **status** (string) - The status of the interaction (e.g., 'completed', 'requires_action'). - **updated** (string) - Timestamp of when the interaction was last updated. - **usage** (object) - Token usage details for the interaction. - **input_tokens_by_modality** (array) - Token usage broken down by modality (text, image). - **modality** (string) - The modality (e.g., 'text', 'image'). - **tokens** (integer) - Number of tokens used. - **total_cached_tokens** (integer) - Total cached tokens. - **total_input_tokens** (integer) - Total input tokens. - **total_output_tokens** (integer) - Total output tokens. - **total_thought_tokens** (integer) - Total thought tokens. - **total_tokens** (integer) - Total tokens used. - **total_tool_use_tokens** (integer) - Total tool use tokens. #### Example Response (Text Output) ```json { "created": "2025-11-26T12:25:15Z", "id": "v1_ChdPU0F4YWFtNkFwS2kxZThQZ05lbXdROBIXT1NBeGFhbTZBcEtpMWU4UGdOZW13UTg", "model": "gemini-3.5-flash", "object": "interaction", "steps": [ { "type": "model_output", "content": [ { "type": "text", "text": "Hello! I\'m functioning perfectly and ready to assist you.\n\nHow are you doing today?" } ] } ], "status": "completed", "updated": "2025-11-26T12:25:15Z", "usage": { "input_tokens_by_modality": [ { "modality": "text", "tokens": 7 } ], "total_cached_tokens": 0, "total_input_tokens": 7, "total_output_tokens": 20, "total_thought_tokens": 22, "total_tokens": 49, "total_tool_use_tokens": 0 } } ``` #### Example Response (Image Input) ```json { "id": "v1_ChdPU0F4YWFtNkFwS2kxZThQZ05lbXdROBIXT1NBeGFhbTZBcEtpMWU4UGdOZW13UTg", "model": "gemini-3.5-flash", "status": "completed", "object": "interaction", "created": "2025-11-26T12:22:47Z", "updated": "2025-11-26T12:22:47Z", "steps": [ { "type": "model_output", "content": [ { "type": "text", "text": "A white humanoid robot with glowing blue eyes stands holding a red skateboard." } ] } ], "usage": { "input_tokens_by_modality": [ { "modality": "text", "tokens": 10 }, { "modality": "image", "tokens": 258 } ], "total_cached_tokens": 0, "total_input_tokens": 268, "total_output_tokens": 20, "total_thought_tokens": 0, "total_tokens": 288, "total_tool_use_tokens": 0 } } ``` #### Example Response (Function Calling) ```json { "id": "v1_ChdPU0F4YWFtNkFwS2kxZThQZ05lbXdROBIXT1NBeGFhbTZBcEtpMWU4UGdOZW13UTg", "model": "gemini-3.5-flash", "status": "requires_action", "object": "interaction", "created": "2025-11-26T12:22:47Z", "updated": "2025-11-26T12:22:47Z", "steps": [ { "type": "function_call", "id": "gth23981", "name": "get_weather", "arguments": { "location": "Boston, MA" } } ], "usage": { "input_tokens_by_modality": [ { "modality": "text", "tokens": 100 } ], "total_cached_tokens": 0, "total_input_tokens": 100, "total_output_tokens": 25, "total_thought_tokens": 0, "total_tokens": 125, "total_tool_use_tokens": 50 } } ``` ``` -------------------------------- ### Upload file, create cache, count tokens, generate content (Go) Source: https://ai.google.dev/api/tokens?hl=hi This Go snippet illustrates uploading a file, creating a cached content, counting tokens, and generating content using the cache. It includes error handling for API calls and demonstrates how to set up the client with an API key. ```go ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } file, err := client.Files.UploadFromPath( ctx, filepath.Join(getMedia(), "a11.txt"), &genai.UploadFileConfig{ MIMEType : "text/plain", }, ) if err != nil { log.Fatal(err) } parts := []*genai.Part{ genai.NewPartFromText("Here the Apollo 11 transcript:"), genai.NewPartFromURI(file.URI, file.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } // Create cached content using a simple slice with text and a file. cache, err := client.Caches.Create(ctx, "gemini-3.5-flash", &genai.CreateCachedContentConfig{ Contents: contents, }) if err != nil { log.Fatal(err) } prompt := "Please give a short summary of this file." countResp, err := client.Models.CountTokens(ctx, "gemini-3.5-flash", []*genai.Content{ genai.NewContentFromText(prompt, genai.RoleUser), }, nil) if err != nil { log.Fatal(err) } fmt.Printf("%d", countResp.TotalTokens) response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", []*genai.Content{ genai.NewContentFromText(prompt, genai.RoleUser), }, &genai.GenerateContentConfig{ CachedContent: cache.Name, }) if err != nil { log.Fatal(err) } usageMetadata, err := json.MarshalIndent(response.UsageMetadata, "", " ") if err != nil { log.Fatal(err) } // Returns `nil` for some reason fmt.Println(string(usageMetadata)) _, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{}) count_tokens.go ``` -------------------------------- ### BidiGenerateMusicSetup Source: https://ai.google.dev/api/live_music The initial message sent by the client to set up music generation. ```APIDOC ## BidiGenerateMusicSetup ### Description Message to be sent in the first (and only in the first) `BidiGenerateMusicClientMessage`. Clients should wait for a `BidiGenerateMusicSetupComplete` message before sending any additional messages. ### Fields - `model` (string): Required. The model's resource name. This serves as an ID for the model to use. Format: `models/{model}` ``` -------------------------------- ### Document Content Example Source: https://ai.google.dev/api/interactions-api-v1?hl=fa Example of a document content block. Includes base64 encoded document data and MIME type. ```json { "type": "document", "data": "BASE64_ENCODED_DOCUMENT", "mime_type": "application/pdf" } ``` -------------------------------- ### Create and Use Cached Content in Python Source: https://ai.google.dev/api/caching Demonstrates how to create a cache with a file and system instruction, then use it for content generation. Ensure the 'google-generativeai' library is installed. ```python from google import genai from google.genai import types client = genai.Client() document = client.files.upload(file=media / "a11.txt") model_name = "gemini-3.5-flash" cache = client.caches.create( model=model_name, config=types.CreateCachedContentConfig( contents=[document], system_instruction="You are an expert analyzing transcripts.", ), ) print(cache) response = client.models.generate_content( model=model_name, contents="Please summarize this transcript", config=types.GenerateContentConfig(cached_content=cache.name), ) print(response.text) cache.py ``` -------------------------------- ### Audio Content Example Source: https://ai.google.dev/api/interactions-api-v1?hl=fa Example of an audio content block. Includes base64 encoded audio data and MIME type. ```json { "type": "audio", "data": "BASE64_ENCODED_AUDIO", "mime_type": "audio/wav" } ```