### Install Google GenAI SDK for Go Source: https://ai.google.dev/gemini-api/docs/libraries.md.txt Use go get to install the google.golang.org/genai package for Go. ```bash go get google.golang.org/genai ``` -------------------------------- ### Install Google GenAI SDK for Go Source: https://ai.google.dev/gemini-api/docs/migrate.md.txt Install the Google GenAI SDK for Go using go get. This command fetches the latest version. ```go go get github.com/google/generative-ai-go ``` ```go go get google.golang.org/genai ``` -------------------------------- ### Install Google GenAI SDK for C# Source: https://ai.google.dev/gemini-api/docs/libraries.md.txt Use the dotnet add package command to install the Google.GenAI package for C#. ```bash dotnet add package Google.GenAI ``` -------------------------------- ### Generate Video in JavaScript Source: https://ai.google.dev/gemini-api/docs/video.md.txt Utilize the `@google/genai` library to create videos from text prompts. This example shows how to initiate generation, poll for completion, and download the resulting video. Ensure the library is installed. ```javascript import { GoogleGenAI } from "@google/genai"; const ai = new GoogleGenAI({}); const prompt = `A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video.`; let operation = await ai.models.generateVideos({ model: "veo-3.1-generate-preview", prompt: prompt, config: { aspectRatio: "9:16", }, }); // Poll the operation status until the video is ready. while (!operation.done) { console.log("Waiting for video generation to complete...") await new Promise((resolve) => setTimeout(resolve, 10000)); operation = await ai.operations.getVideosOperation({ operation: operation, }); } // Download the generated video. ai.files.download({ file: operation.response.generatedVideos[0].video, downloadPath: "pizza_making.mp4", }); console.log(`Generated video saved to pizza_making.mp4`); ``` -------------------------------- ### Install npm Dependencies Source: https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example.md.txt Install AI SDK, Google provider, zod, TypeScript, and related types for npm. ```bash npm install ai @ai-sdk/google zod npm install -D @types/node tsx typescript && npx tsc --init ``` -------------------------------- ### Install Google GenAI SDK for Python Source: https://ai.google.dev/gemini-api/docs/libraries.md.txt Use pip to install the google-genai library for Python. ```bash pip install google-genai ``` -------------------------------- ### Install Google GenAI SDK for JavaScript Source: https://ai.google.dev/gemini-api/docs/libraries.md.txt Use npm to install the @google/genai library for JavaScript/TypeScript. ```bash npm install @google/genai ``` -------------------------------- ### Install yarn Dependencies Source: https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example.md.txt Install AI SDK, Google provider, zod, TypeScript, and related types for yarn. ```bash yarn add ai @ai-sdk/google zod yarn add -D @types/node tsx typescript && yarn tsc --init ``` -------------------------------- ### Install Charting and PDF Dependencies (yarn) Source: https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example.md.txt Install Puppeteer and Chart.js for chart rendering and PDF creation using yarn. ```bash yarn add puppeteer chart.js yarn add -D @types/chart.js ``` -------------------------------- ### Install pnpm Dependencies Source: https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example.md.txt Install AI SDK, Google provider, zod, TypeScript, and related types for pnpm. ```bash pnpm add ai @ai-sdk/google zod pnpm add -D @types/node tsx typescript ``` -------------------------------- ### Install Charting and PDF Dependencies (npm) Source: https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example.md.txt Install Puppeteer and Chart.js for chart rendering and PDF creation using npm. ```bash npm install puppeteer chart.js npm install -D @types/chart.js ``` -------------------------------- ### Start Chat and Send Messages (Python - Before) Source: https://ai.google.dev/gemini-api/docs/migrate.md.txt This Python code demonstrates the older method of starting a chat and sending messages. It initializes a model and then uses `start_chat`. ```python import google.generativeai as genai model = genai.GenerativeModel('gemini-2.0-flash') chat = model.start_chat() response = chat.send_message( "Tell me a story in 100 words") response = chat.send_message( "What happened after that?") ``` -------------------------------- ### Photography Prompt Example Source: https://ai.google.dev/gemini-api/docs/imagen.md.txt Start prompts with "A photo of..." to generate photorealistic images. This guides Imagen to produce results that resemble photographs. ```text A photo of coffee beans in a kitchen on a wooden surface ``` ```text A photo of a chocolate bar on a kitchen counter ``` ```text A photo of a modern building with water in the background ``` -------------------------------- ### Initialize npm Project Source: https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example.md.txt Create a new directory and initialize an npm project. ```bash mkdir market-trend-app cd market-trend-app npm init -y ``` -------------------------------- ### Few-shot Prompt Example for Concise Responses Source: https://ai.google.dev/gemini-api/docs/prompting-strategies.md.txt This few-shot prompt includes examples that guide the model towards concise responses. It demonstrates how examples can influence the model to prefer shorter explanations. ```text Below are some examples showing a question, explanation, and answer format: Question: Why is the sky blue? Explanation1: The sky appears blue because of Rayleigh scattering, which causes shorter blue wavelengths of light to be scattered more easily than longer red wavelengths, making the sky look blue. Explanation2: Due to Rayleigh scattering effect. Answer: Explanation2 Question: What is the cause of earthquakes? Explanation1: Sudden release of energy in the Earth's crust. Explanation2: Earthquakes happen when tectonic plates suddenly slip or break apart, causing a release of energy that creates seismic waves that can shake the ground and cause damage. Answer: Explanation1 Now, Answer the following question given the example formats above: Question: How is snow formed? Explanation1: Snow is formed when water vapor in the air freezes into ice crystals in the atmosphere, which can combine and grow into snowflakes as they fall through the atmosphere and accumulate on the ground. Explanation2: Water vapor freezes into ice crystals forming snow. Answer: ``` ```text Answer: Explanation2 ``` -------------------------------- ### Initialize pnpm Project Source: https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example.md.txt Create a new directory and initialize a pnpm project. ```bash mkdir market-trend-app cd market-trend-app pnpm init ``` -------------------------------- ### Create GenAI Client with Configuration in Go (New SDK) Source: https://ai.google.dev/gemini-api/docs/migrate.md.txt Shows how to create a GenAI client in Go with specific configuration, such as setting the backend to GeminiAPI. ```go import "google.golang.org/genai" client, err := genai.NewClient(ctx, &genai.ClientConfig{ Backend: genai.BackendGeminiAPI, }) ``` -------------------------------- ### JSON Output with Example and Response Prefix Source: https://ai.google.dev/gemini-api/docs/prompting-strategies.md.txt Use this pattern to guide the model in generating JSON output, especially when you want to omit fields not present in the order. Providing an example response helps the model understand the desired format and content. ```text Valid fields are cheeseburger, hamburger, fries, and drink. Order: Give me a cheeseburger and fries Output: ``` { "cheeseburger": 1, "fries": 1 } ``` Order: I want two burgers, a drink, and fries. Output: ``` -------------------------------- ### Initialize yarn Project Source: https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example.md.txt Create a new directory and initialize a yarn project. ```bash mkdir market-trend-app cd market-trend-app yarn init -y ``` -------------------------------- ### Set Video Clipping Intervals Source: https://ai.google.dev/gemini-api/docs/video-understanding.md.txt Process a specific segment of a video by providing start and end offsets in seconds. This example uses a YouTube URL. ```python from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model='models/gemini-3-flash-preview', contents=types.Content( parts=[ types.Part( file_data=types.FileData(file_uri='https://www.youtube.com/watch?v=XEzRZ35urlk'), video_metadata=types.VideoMetadata( start_offset='1250s', end_offset='1570s' ) ), types.Part(text='Please summarize the video in 3 sentences.') ] ) ) ``` ```javascript import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); const model = 'gemini-3-flash-preview'; async function main() { const contents = [ { role: 'user', parts: [ { fileData: { fileUri: 'https://www.youtube.com/watch?v=9hE5-98ZeCg', mimeType: 'video/*', }, videoMetadata: { startOffset: '40s', endOffset: '80s', } }, { text: 'Please summarize the video in 3 sentences.', }, ], }, ]; const response = await ai.models.generateContent({ model, contents, }); console.log(response.text) } await main(); ``` -------------------------------- ### Generate Content with System Instruction (Go) Source: https://ai.google.dev/gemini-api/docs/text-generation.md.txt Use `genai.NewClient` and pass a `genai.GenerateContentConfig` with `SystemInstruction` to define the model's behavior. ```go package main import ( "context" "fmt" "os" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } config := &genai.GenerateContentConfig{ SystemInstruction: genai.NewContentFromText("You are a cat. Your name is Neko.", genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, "gemini-3-flash-preview", genai.Text("Hello there"), config, ) fmt.Println(result.Text()) } ``` -------------------------------- ### Get Model Input/Output Token Limits (Python) Source: https://ai.google.dev/gemini-api/docs/tokens.md.txt Retrieves and prints the input and output token limits for a specified model. Requires the 'google' library to be installed. ```Python from google import genai client = genai.Client() model_info = client.models.get(model="gemini-3-flash-preview") print(f"{model_info.input_token_limit=}") print(f"{model_info.output_token_limit=}") ``` -------------------------------- ### Create Batch Job with Inline Requests (JavaScript) Source: https://ai.google.dev/gemini-api/docs/batch-api.md.txt Suitable for smaller batches, this JavaScript example demonstrates submitting inline requests. Ensure the @google/genai library is installed. ```javascript import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI({}); const inlinedRequests = [ { contents: [{ parts: [{text: 'Tell me a one-sentence joke.'}], role: 'user' }] }, { contents: [{ parts: [{'text': 'Why is the sky blue?'}], role: 'user' }] } ] const response = await ai.batches.create({ model: 'gemini-3-flash-preview', src: inlinedRequests, config: { displayName: 'inlined-requests-job-1', } }); console.log(response); ``` -------------------------------- ### Get Model Input/Output Token Limits (JavaScript) Source: https://ai.google.dev/gemini-api/docs/tokens.md.txt Asynchronously retrieves and logs the input and output token limits for a given model. Ensure the '@google/generative-ai' package is installed. ```JavaScript import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); async function main() { const modelInfo = await ai.models.get({model: 'gemini-3-flash-preview'}); console.log(modelInfo.inputTokenLimit); console.log(modelInfo.outputTokenLimit); } await main(); ``` -------------------------------- ### Upload PDF and Summarize with Go Source: https://ai.google.dev/gemini-api/docs/document-processing.md.txt This Go snippet demonstrates uploading a PDF and generating a summary using the Google GenAI Go SDK. It handles downloading the file, uploading it, and then sending a prompt for summarization. Ensure the GEMINI_API_KEY environment variable is set. ```go package main import ( "context" "fmt" "io" "net/http" "os" "google.golang.org/genai" ) func main() { ctx := context.Background() client, _ := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) pdfURL := "https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf" localPdfPath := "A17_FlightPlan_downloaded.pdf" respHttp, _ := http.Get(pdfURL) defer respHttp.Body.Close() outFile, _ := os.Create(localPdfPath) defer outFile.Close() _, _ = io.Copy(outFile, respHttp.Body) uploadConfig := &genai.UploadFileConfig{MIMEType: "application/pdf"} uploadedFile, _ := client.Files.UploadFromPath(ctx, localPdfPath, uploadConfig) promptParts := []*genai.Part{ genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), genai.NewPartFromText("Summarize this document"), } contents := []*genai.Content{ genai.NewContentFromParts(promptParts, genai.RoleUser), // Specify role } result, _ := client.Models.GenerateContent( ctx, "gemini-3-flash-preview", contents, nil, ) fmt.Println(result.Text()) } ``` -------------------------------- ### Create GenAI Client with API Key in Go (Legacy) Source: https://ai.google.dev/gemini-api/docs/migrate.md.txt Illustrates creating a GenAI client in Go using an API key, including necessary imports and options. ```go import ( "github.com/google/generative-ai-go/genai" "google.golang.org/api/option" ) client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY")) ``` -------------------------------- ### Task Input Example for Camping Trip Source: https://ai.google.dev/gemini-api/docs/prompting-strategies.md.txt Use this prompt format to get a simple, concise list of essential items for a specific task. Ensure the request specifies the desired number of items. ```text Give me a simple list of just the things that I must bring on a camping trip. The list should have 5 items. ``` -------------------------------- ### Install gemini-api-dev Skill with Context7 Source: https://ai.google.dev/gemini-api/docs/coding-agents.md.txt Installs the foundational gemini-api-dev skill using Context7. This skill provides documentation and best practices for general-purpose Gemini development, including prompt routing and multimodal prompting. ```bash npx ctx7 skills install /google-gemini/gemini-skills gemini-api-dev ``` -------------------------------- ### Select Output Format to WAV (Python) Source: https://ai.google.dev/gemini-api/docs/music-generation.md.txt This Python example shows how to specify the output format as WAV for generated audio using the `response_mime_type` in `GenerateContentConfig`. ```python response = client.models.generate_content( model="lyria-3-pro-preview", contents="An atmospheric ambient track.", config=types.GenerateContentConfig( response_modalities=["AUDIO", "TEXT"], response_mime_type="audio/wav", ), ) ``` -------------------------------- ### Upload File and Get Metadata in Python Source: https://ai.google.dev/gemini-api/docs/document-processing.md.txt Uploads a local file (e.g., 'example.txt') to the Gemini API and then retrieves its metadata using the Python client library. Ensure the 'google-generativeai' library is installed. ```Python from google import genai import pathlib client = genai.Client() fpath = pathlib.Path('example.txt') fpath.write_text('hello') file = client.files.upload(file='example.txt') file_info = client.files.get(name=file.name) print(file_info.model_dump_json(indent=4)) ``` -------------------------------- ### Python Live Session with Audio Transcription Source: https://ai.google.dev/gemini-api/docs/live-api/capabilities.md.txt This Python example demonstrates setting up a live session with the Gemini API, sending an initial message, and processing responses including model turns and output audio transcriptions. Requires `google-generativeai` library. ```python import asyncio from google import genai from google.genai import types client = genai.Client() model = "gemini-3.1-flash-live-preview" config = { "response_modalities": ["AUDIO"], "output_audio_transcription": {} } async def main(): async with client.aio.live.connect(model=model, config=config) as session: message = "Hello? Gemini are you there?" await session.send_client_content( turns={"role": "user", "parts": [{"text": message}]}, turn_complete=True ) async for response in session.receive(): if response.server_content.model_turn: print("Model turn:", response.server_content.model_turn) if response.server_content.output_transcription: print("Transcript:", response.server_content.output_transcription.text) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Generate Content with JavaScript SDK Source: https://ai.google.dev/gemini-api/docs/text-generation.md.txt This JavaScript example uses the Google GenAI SDK to generate content. It demonstrates setting the model, content, and generation configuration asynchronously. Ensure you have installed the @google/generativeai package. ```javascript import { GoogleGenAI } from "@google/generativeai"; const ai = new GoogleGenAI({}); async function main() { const response = await ai.models.generateContent({ model: "gemini-3-flash-preview", contents: "Explain how AI works", config: { temperature: 0.1, }, }); console.log(response.text); } await main(); ``` -------------------------------- ### Generate Content in Go (New SDK) Source: https://ai.google.dev/gemini-api/docs/migrate.md.txt Illustrates generating content in Go using the new SDK. It creates a client and then calls client.Models.GenerateContent, logging the result. ```go ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } result, err := client.Models.GenerateContent(ctx, "gemini-2.0-flash", genai.Text("Tell me a story in 300 words."), nil) if err != nil { log.Fatal(err) } debugPrint(result) // utility for printing result ``` -------------------------------- ### Get Next Appointment Source: https://ai.google.dev/gemini-api/docs/live-api/best-practices.md.txt Checks if a client has a future appointment already scheduled using their client ID. Returns the appointment details or null. Invoke this tool at the start of the 'Next Appointment' workflow step. ```APIDOC ## GET /api/client/{client_id}/next_appointment ### Description Checks if a client has a future appointment already scheduled. ### Method GET ### Endpoint /api/client/{client_id}/next_appointment ### Parameters #### Path Parameters - **client_id** (string) - Required - The unique ID of the client. ### Response #### Success Response (200) - **appointment** (object or null) - Details of the next appointment if scheduled, otherwise null. - **datetime** (string) - The date and time of the appointment in ISO 8601 format. - **duration_minutes** (integer) - The duration of the appointment in minutes. #### Response Example { "appointment": { "datetime": "2025-10-30T14:30:00Z", "duration_minutes": 60 } } { "appointment": null } ``` -------------------------------- ### Generate Speech with Multi-Speaker Transcript (JavaScript) Source: https://ai.google.dev/gemini-api/docs/speech-generation.md.txt This JavaScript example shows how to generate speech from text using the Gemini API, configuring multiple speakers with distinct voices. Make sure to install the @google/genai package. ```javascript import { GoogleGenAI } from "@google/genai"; const ai = new GoogleGenAI({}); async function main() { const transcript = await ai.models.generateContent({ model: "gemini-3-flash-preview", contents: "Generate a short transcript around 100 words that reads like it was clipped from a podcast by excited herpetologists. The hosts names are Dr. Anya and Liam.", }) const response = await ai.models.generateContent({ model: "gemini-3.1-flash-tts-preview", contents: transcript, config: { responseModalities: ['AUDIO'], speechConfig: { multiSpeakerVoiceConfig: { speakerVoiceConfigs: [ { speaker: "Dr. Anya", voiceConfig: { prebuiltVoiceConfig: {voiceName: "Kore"}, } }, { speaker: "Liam", voiceConfig: { prebuiltVoiceConfig: {voiceName: "Puck"}, } } ] } } } }); } // ..JavaScript code for exporting .wav file for output audio await main(); ``` -------------------------------- ### Install Gemini Docs MCP Server Source: https://ai.google.dev/gemini-api/docs/coding-agents.md.txt Run this command in your agent's terminal or project root to install the Gemini Docs MCP server, which provides real-time API definitions and integration patterns. ```bash npx add-mcp "https://gemini-api-docs-mcp.dev" ``` -------------------------------- ### Execute Function Call and Get Result (JavaScript) Source: https://ai.google.dev/gemini-api/docs/function-calling.md.txt Extract the function call details from the model's response, parse the arguments, and execute the corresponding function. This example demonstrates how to handle the `set_light_values` function call. ```javascript // Extract tool call details const tool_call = response.functionCalls[0] let result; if (tool_call.name === 'set_light_values') { result = setLightValues(tool_call.args.brightness, tool_call.args.color_temp); console.log(`Function execution result: ${JSON.stringify(result)}`); } ``` -------------------------------- ### Execute Function Call and Get Result (Python) Source: https://ai.google.dev/gemini-api/docs/function-calling.md.txt Extract the function call details from the model's response, parse the arguments, and execute the corresponding function. This example demonstrates how to handle the `set_light_values` function call. ```python # Extract tool call details, it may not be in the first part. tool_call = response.candidates[0].content.parts[0].function_call if tool_call.name == "set_light_values": result = set_light_values(**tool_call.args) print(f"Function execution result: {result}") ``` -------------------------------- ### Generate Video with Go SDK Source: https://ai.google.dev/gemini-api/docs/video.md.txt Use the Go SDK to generate a 4k video from a text prompt. Ensure the client is initialized and poll the operation until the video is ready for download. ```Go package main import ( "context" "log" "os" "time" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } prompt := `A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon's colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon.` videoConfig := &genai.GenerateVideosConfig{ Resolution: "4k", } operation, _ := client.Models.GenerateVideos( ctx, "veo-3.1-generate-preview", prompt, nil, videoConfig, ) // Poll the operation status until the video is ready. for !operation.Done { log.Println("Waiting for video generation to complete...") time.Sleep(10 * time.Second) operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil) } // Download the generated video. video := operation.Response.GeneratedVideos[0] client.Files.Download(ctx, video.Video, nil) fname := "4k_grand_canyon.mp4" _ = os.WriteFile(fname, video.Video.VideoBytes, 0644) log.Printf("Generated video saved to %s\n", fname) } ``` -------------------------------- ### List, Get, and Delete Documents via REST API Source: https://ai.google.dev/gemini-api/docs/file-search.md.txt Provides examples for interacting with the File Search documents API using RESTful HTTP requests. These commands can be executed from a command line or integrated into scripts. ```bash curl "https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents?key=${GEMINI_API_KEY}" ``` ```bash curl "https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents/my_doc?key=${GEMINI_API_KEY}" ``` ```bash curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents/my_doc?key=${GEMINI_API_KEY}" ``` -------------------------------- ### Generate Video from Image in Java Source: https://ai.google.dev/gemini-api/docs/video.md.txt This Java example shows how to generate a video from an image using the Google GenAI client library. It includes steps for initializing the client, loading an image, generating the video, polling for completion, and downloading the result. Note that the image loading part is a placeholder. ```java import com.google.genai.Client; import com.google.genai.types.GenerateVideosOperation; import com.google.genai.types.Image; import com.google.genai.types.Video; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class GenerateVideoFromImage { public static void main(String[] args) throws Exception { Client client = new Client(); String prompt = "Panning wide shot of a calico kitten sleeping in the sunshine"; // Step 1: Generate an image with Nano Banana 2: // Assume 'image' contains the generated image, // or is loaded from a file: Image image = Image.fromFile("path/to/your/image.png"); // Step 2: Generate video with Veo 3.1 using the image. GenerateVideosOperation operation = client.models.generateVideos("veo-3.1-generate-preview", prompt, image, null); // Poll the operation status until the video is ready. while (!operation.done().isPresent() || !operation.done().get()) { System.out.println("Waiting for video generation to complete..."); Thread.sleep(10000); operation = client.operations.getVideosOperation(operation, null); } // Download the video. Video video = operation.response().get().generatedVideos().get().get(0).video().get(); Path path = Paths.get("veo3_with_image_input.mp4"); client.files.download(video, path.toString(), null); if (video.videoBytes().isPresent()) { Files.write(path, video.videoBytes().get()); System.out.println("Generated video saved to veo3_with_image_input.mp4"); } } } ``` -------------------------------- ### Generate 4K Video with JavaScript SDK Source: https://ai.google.dev/gemini-api/docs/video.md.txt This JavaScript example shows how to generate a 4K video using the Gemini API. It asynchronously polls the operation status and downloads the video. Make sure to install the `@google/genai` package. ```javascript import { GoogleGenAI } from "@google/genai"; const ai = new GoogleGenAI({}); const prompt = `A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon's colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon.`; let operation = await ai.models.generateVideos({ model: "veo-3.1-generate-preview", prompt: prompt, config: { resolution: "4k", }, }); // Poll the operation status until the video is ready. while (!operation.done) { console.log("Waiting for video generation to complete...") await new Promise((resolve) => setTimeout(resolve, 10000)); operation = await ai.operations.getVideosOperation({ operation: operation, }); } // Download the generated video. ai.files.download({ file: operation.response.generatedVideos[0].video, downloadPath: "4k_grand_canyon.mp4", }); console.log(`Generated video saved to 4k_grand_canyon.mp4`); ``` -------------------------------- ### Install gemini-api-dev Skill with skills.sh Source: https://ai.google.dev/gemini-api/docs/coding-agents.md.txt Installs the foundational gemini-api-dev skill globally using skills.sh. This skill provides documentation and best practices for general-purpose Gemini development, including prompt routing and multimodal prompting. ```bash npx skills add google-gemini/gemini-skills --skill gemini-api-dev --global ``` -------------------------------- ### Establish API Connection with Python Source: https://ai.google.dev/gemini-api/docs/live-api/capabilities.md.txt Use this Python code to establish a connection to the Gemini API using an API key. Ensure you have the `google-generativeai` library installed. This example sets up a live session with audio response capabilities. ```python import asyncio from google import genai client = genai.Client() model = "gemini-3.1-flash-live-preview" config = {"response_modalities": ["AUDIO"]} async def main(): async with client.aio.live.connect(model=model, config=config) as session: print("Session started") # Send content... if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize Lyria RealTime Session and Generate Music (JavaScript) Source: https://ai.google.dev/gemini-api/docs/realtime-music-generation.md.txt Initializes the Lyria RealTime session, sets prompts and configuration, starts music generation, and handles audio chunks. Requires API key and speaker setup. ```javascript import { GoogleGenAI } from "@google/genai"; import Speaker from "speaker"; import { Buffer } from "buffer"; const client = new GoogleGenAI({ apiKey: GEMINI_API_KEY, apiVersion: "v1alpha" , }); async function main() { const speaker = new Speaker({ channels: 2, // stereo bitDepth: 16, // 16-bit PCM sampleRate: 44100, // 44.1 kHz }); const session = await client.live.music.connect({ model: "models/lyria-realtime-exp", callbacks: { onmessage: (message) => { if (message.serverContent?.audioChunks) { for (const chunk of message.serverContent.audioChunks) { const audioBuffer = Buffer.from(chunk.data, "base64"); speaker.write(audioBuffer); } } }, onerror: (error) => console.error("music session error:", error), onclose: () => console.log("Lyria RealTime stream closed."), }, }); await session.setWeightedPrompts({ weightedPrompts: [ { text: "Minimal techno with deep bass, sparse percussion, and atmospheric synths", weight: 1.0 }, ], }); await session.setMusicGenerationConfig({ musicGenerationConfig: { bpm: 90, temperature: 1.0, audioFormat: "pcm16", // important so we know format sampleRateHz: 44100, }, }); await session.play(); } main().catch(console.error); ``` -------------------------------- ### Generate Image with Google Search (JavaScript) Source: https://ai.google.dev/gemini-api/docs/gemini-3.md.txt Generate an image using the Gemini API in JavaScript, leveraging Google Search for prompt grounding. This example saves the generated image to a file. Ensure Node.js environment with @google/genai installed. ```javascript import { GoogleGenAI } from "@google/genai"; import * as fs from "node:fs"; const ai = new GoogleGenAI({}); async function run() { const response = await ai.models.generateContent({ model: "gemini-3-pro-image-preview", contents: "Generate a visualization of the current weather in Tokyo.", config: { tools: [{ googleSearch: {} }], imageConfig: { aspectRatio: "16:9", imageSize: "4K" } } }); for (const part of response.candidates[0].content.parts) { if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, "base64"); fs.writeFileSync("weather_tokyo.png", buffer); } } } run(); ``` -------------------------------- ### Install Gemini and Google API Libraries Source: https://ai.google.dev/gemini-api/docs/oauth.md.txt Install the necessary Python libraries for interacting with the Gemini API and Google Cloud services. These commands ensure you have the required packages for credential management and API calls. ```bash pip install --upgrade -q google-api-python-client google-auth-httplib2 google-auth-oauthlib pip install google-genai ``` -------------------------------- ### Annotate Image with Disposal Instructions Source: https://ai.google.dev/gemini-api/docs/robotics-overview.md.txt This example demonstrates how to use code execution to annotate an image, such as drawing arrows for disposal instructions, and return the modified image. The prompt guides the model to provide disposal instructions with colored arrows. ```python from google import genai from google.genai import types client = genai.Client() # Load your image with open('sorting.jpeg', 'rb') as f: image_bytes = f.read() prompt = """ Look at this image and return it as an annotated version using arrows of different colors to represent which items should go in which bins for disposal. You must return the final image to the API caller. """ response = client.models.generate_content( model="gemini-robotics-er-1.6-preview", contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/jpeg', ), prompt ], config = types.GenerateContentConfig( temperature=1.0, tools=[types.Tool(code_execution=types.ToolCodeExecution)], ) ) print(response.text) ``` -------------------------------- ### Install gemini-live-api-dev Skill with skills.sh Source: https://ai.google.dev/gemini-api/docs/coding-agents.md.txt Installs the gemini-live-api-dev skill globally using skills.sh. This skill is for building real-time conversational AI applications with Gemini Live API, covering WebSocket connections and streaming. ```bash npx skills add google-gemini/gemini-skills --skill gemini-live-api-dev --global ``` -------------------------------- ### JavaScript: Generate Content with Image and Code Execution Source: https://ai.google.dev/gemini-api/docs/gemini-3.md.txt This JavaScript example shows how to send an image and a text prompt to the Gemini API, enabling code execution. It fetches an image, converts it to base64, and sends it with the prompt. Ensure you have the `@google/genai` library installed. ```javascript import { GoogleGenAI } from "@google/genai"; const ai = new GoogleGenAI({}); async function main() { const imageUrl = "https://goo.gle/instrument-img"; const response = await fetch(imageUrl); const imageArrayBuffer = await response.arrayBuffer(); const base64ImageData = Buffer.from(imageArrayBuffer).toString("base64"); const result = await ai.models.generateContent({ model: "gemini-3-flash-preview", contents: [ { inlineData: { mimeType: "image/jpeg", data: base64ImageData, }, }, { text: "Zoom into the expression pedals and tell me how many pedals are there?", }, ], config: { tools: [{ codeExecution: {} }], }, }); for (const part of result.candidates[0].content.parts) { if (part.text) { console.log("Text:", part.text); } if (part.executableCode) { console.log("Code:", part.executableCode.code); } if (part.codeExecutionResult) { console.log("Output:", part.codeExecutionResult.output); } } } main(); ```