{"url": "https://ai.google.dev/", "titulek": "Gemini Developer API | Gemma open models | Google AI for Developers", "h1": "AI for everydeveloper", "popis": "Build with Gemini 2.0 Flash, 2.5 Pro, and Gemma using the Gemini API and Google AI Studio.", "klicova_slova": "gemini api,google gemini,ai studio, google ai studio, gemini api python, gemini developers", "kanonicka": "https://ai.google.dev/", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini Developer API | Gemma open models  |  Google AI for Developers", "og:description": "Build with Gemini 2.0 Flash, 2.5 Pro, and Gemma using the Gemini API and Google AI Studio.", "og:url": "https://ai.google.dev/", "og:image": "https://ai.google.dev/static/site-assets/images/share-ai-dev.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "http://schema.org/", "@type": "Organization", "name": "Google AI for Developers", "logo": "https://www.gstatic.com/devrel-devsite/prod/veec7311b6c5f99ef32994eb65aab7022195f72bfa4f3d934bdc7556da7fa7c3b/googledevai/images/touchicon-180-new.png", "url": "https://ai.google.dev/"}, {"@context": "http://schema.org", "@type": "WebSite", "name": "Google AI for Developers", "url": "https://ai.google.dev/", "potentialAction": {"@type": "SearchAction", "target": "https://ai.google.dev/s/results?q={search_term_string}", "query-input": "required name=search_term_string"}}], "drobecky": [], "osnova": [{"uroven": 1, "text": "AI for everydeveloper"}, {"uroven": 3, "text": "Integrate Google AI models with an API key"}, {"uroven": 4, "text": "Integrate models into apps"}, {"uroven": 4, "text": "Explore AI models"}, {"uroven": 3, "text": "Own your AI with Gemma open models"}, {"uroven": 3, "text": "Run AI models on-device with Google AI Edge"}, {"uroven": 4, "text": "Gemini Nano on Android"}, {"uroven": 4, "text": "AI features for web apps"}, {"uroven": 3, "text": "Build with AI responsibly"}, {"uroven": 4, "text": "Build responsible models"}, {"uroven": 4, "text": "Develop secure AI systems"}, {"uroven": 3, "text": "Agents"}, {"uroven": 3, "text": "Analysis and insights"}, {"uroven": 3, "text": "Code generation"}, {"uroven": 3, "text": "Code chat"}, {"uroven": 2, "text": "Explore apps built with the Gemini API"}, {"uroven": 2, "text": "Join the community"}], "markdown": "[New Build with Gemini 3 Flash, our frontier intelligence built for speed and scale](https://aistudio.google.com/apps) AI for every\ndeveloper Unlock AI models to build innovative apps and transform development workflows with tools across platforms. [Explore models in Google AI Studio](https://aistudio.google.com) Integrate Google AI models with an API key Build with cutting-edge AI models, like Gemini, Imagen, and Veo, from Google DeepMind [View Gemini API docs](https://ai.google.dev/gemini-api/docs) [Integrate models into apps Unlock AI capabilities for your apps with a simple call to the Gemini API. \nGemini API docs](https://ai.google.dev/gemini-api/docs) [Explore AI models Quickly evaluate AI models, develop prompts, and transform ideas into code. \nGoogle AI Studio](https://aistudio.google.com/) Own your AI with Gemma open models Build custom AI solutions and retain complete control. Tailor Gemma models, built from the same research and technology as Gemini, with your own data. [Build with Gemma](https://ai.google.dev/gemma) Run AI models on-device with Google AI Edge Build and deploy edge ML solutions across mobile, web, and embedded applications, from simple APIs to custom pipelines, with support across all major frameworks. [Explore Google AI Edge](https://ai.google.dev/edge) [Gemini Nano on Android Unlock low latency and cost effective generative AI features while keeping data on-device. \nAndroid docs](https://developer.android.com/ai/gemini-nano) [AI features for web apps Integrate AI models like Gemini Nano into web apps with Chrome's built-in web platform APIs. \nAI on Chrome](https://developer.chrome.com/docs/ai/built-in) Build with AI responsibly Build trusted and secure AI with guidance for responsible design, development, and deployment of models and applications. [Build Responsible AI](https://ai.google.dev/responsible/) [Build responsible models Tools and guidance to design, build, and evaluate open AI models responsibly. \nResponsible GenAI Toolkit](https://ai.google.dev/responsible) [Develop secure AI systems Build and deploy secure, responsible AI applications with the help of Google's Secure AI Framework (SAIF). \nSecure AI Framework](https://saif.google/) Agents Gemini empowers you to be more productive by acting as your coding agent. It can plan and execute tasks, freeing you to focus on what matters most. [Jules](http://labs.google.com/jules) [Colab](https://colab.google/) [Firebase](https://firebase.google.com/products/generative-ai) Analysis and insights Improve code quality and fix issues with code analysis. Get insights, suggestions, and code snippets within your existing development environment. [Android Studio](https://developer.android.com/gemini-in-android) [Chrome DevTools](https://developer.chrome.com/docs/devtools/console/understand-messages) [Firebase](https://firebase.google.com/products/generative-ai) [Google Cloud](https://cloud.google.com/products/gemini/code-assist) [JetBrains IDEs](https://plugins.jetbrains.com/plugin/8079-gemini--google-cloud-code) [VS Code](https://marketplace.visualstudio.com/items?itemName=GoogleCloudTools.cloudcode) Code generation Gemini adds AI-powered code completion with natural language understanding to create entire code blocks from your descriptions, revolutionizing your development workflow. [Android Studio](https://developer.android.com/gemini-in-android) [Colab](https://colab.google/) [Firebase](https://firebase.google.com/products/generative-ai) [Google Cloud](https://cloud.google.com/products/gemini/code-assist) [JetBrains IDEs](https://plugins.jetbrains.com/plugin/8079-gemini--google-cloud-code) [VS Code](https://marketplace.visualstudio.com/items?itemName=GoogleCloudTools.cloudcode) Code chat Ask development questions and receive responses that help you reduce errors, solve problems, and become a better developer. Gemini understands the context of your environment to give you the best responses for your questions. [Android Studio](https://developer.android.com/gemini-in-android) [Colab](https://colab.google/) [Firebase](https://firebase.google.com/products/generative-ai) [Google Cloud](https://cloud.google.com/products/gemini/code-assist) [JetBrains IDEs](https://plugins.jetbrains.com/plugin/8079-gemini--google-cloud-code) [VS Code](https://marketplace.visualstudio.com/items?itemName=GoogleCloudTools.cloudcode) Explore apps built with the Gemini API Tldraw Prototyping a new natural language computing experience on an infinite canvas with Gemini 2.0 [View](/showcase/tldraw) Rooms Unlocking richer avatar interactions with Gemini 2.0 text and audio capabilities [View](/showcase/rooms) Toonsutra Leveraging contextual multilingual translation abilities of Gemini 2.0 to make comics and webtoons accessible to audiences in India across regional languages. [View](/showcase/toonsutra) Viggle Experimenting with Gemini 2.0 to create virtual characters and audio narration for their AI powered video platform [View](/showcase/viggle) Sublayer See how the Ruby-based AI agent framework empowers developer teams to be more productive with the power of Gemini models. [View](/showcase/sublayer) Sourcegraph Learn how Cody AI saw big quality gains using Gemini's massive context window. [View](/showcase/sourcegraph) AgentOps Explore how AgentOps provides cost-effective and powerful LLM-powered agent observability for enterprises using Gemini API. [View](/showcase/agentops) Join the community Tap into the power of our community forum. Get answers, build together, and be part of the conversation. [Google AI Forum](https://discuss.ai.google.dev/)", "znaku_textu": 5594, "slov": 617, "odkazu": 62, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 20:10:23", "sha256": "9b4b29f09a06c1fdbb0304ee52e4919c52d38ab46636401219e665475da8c107", "hloubka": 0, "zdroj_objevu": "seed", "ze_seznamu": true, "mime": "text/html", "odkazy_externi": ["https://deepmind.google/gemini", "https://deepmind.google/technologies/imagen/", "https://deepmind.google/technologies/veo/veo-2/", "https://deepmind.google/models/gemma", "https://aistudio.google.com/", "https://keras.io/keras_3/", "https://colab.sandbox.google.com/github/google/generative-ai-docs/blob/main/site/en/gemma/docs/lora_tuning.ipynb", "https://developer.android.com/ai/gemini-nano", "https://developer.chrome.com/docs/ai/built-in", "https://saif.google/", "https://developer.android.com/gemini-in-android", "https://developer.chrome.com/docs/devtools/console/understand-messages", "https://colab.google/", "https://firebase.google.com/products/generative-ai", "https://cloud.google.com/products/gemini/code-assist", "https://plugins.jetbrains.com/plugin/8079-google-cloud-code", "https://labs.google.com/jules/home", "https://marketplace.visualstudio.com/items?itemName=GoogleCloudTools.cloudcode", "https://discuss.ai.google.dev/", "https://aistudio.google.com/apps", "http://labs.google.com/jules", "https://plugins.jetbrains.com/plugin/8079-gemini--google-cloud-code", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/agent-environment", "titulek": "Environments in managed agents | Gemini API | Google AI for Developers", "h1": "Environments in managed agents", "popis": "Learn about persistent execution environments for managed agents in the Gemini API, including pre-installed software, snapshots, and configuration options.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/agent-environment", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Environments in managed agents  |  Gemini API  |  Google AI for Developers", "og:description": "Learn about persistent execution environments for managed agents in the Gemini API, including pre-installed software, snapshots, and configuration options.", "og:url": "https://ai.google.dev/gemini-api/docs/agent-environment", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Environments in managed agents"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Environments in managed agents", "item": "https://ai.google.dev/gemini-api/docs/agent-environment"}]}], "drobecky": ["Gemini API", "Environments in managed agents"], "osnova": [{"uroven": 1, "text": "Environments in managed agents"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "The environment parameter"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Configure an environment"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Mount from a source"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Hooks"}, {"uroven": 3, "text": "Private sources"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Pre-installed software"}, {"uroven": 2, "text": "Network configuration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Credentials"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Disable network access"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Refresh credentials"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Environment lifecycle"}, {"uroven": 2, "text": "Environments API"}, {"uroven": 3, "text": "List environments"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Get an environment"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Delete an environment"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Download files from the environment"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Pricing & resources"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Environments in managed agents Environments are managed Linux sandboxes that give agents an isolated place to\nexecute code and persist files. They are decoupled from interaction context, so you can reuse the same environment across multiple interactions or start fresh at any time. The following example demonstrates how to create an interaction with a fresh\nremote environment and retrieve its ID: Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Install pandas and matplotlib, verify the imports, and print the versions.\", environment=\"remote\", ) print(f\"Environment ID: {interaction.environment_id}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Install pandas and matplotlib, verify the imports, and print the versions.\", environment: \"remote\", }); console.log(`Environment ID: ${interaction.environment_id}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Install pandas and matplotlib, verify the imports, and print the versions.\", \"environment\": \"remote\" }'` The `environment` parameter The `environment` parameter accepts three forms: Form Example When to use `\"remote\"` `environment=\"remote\"` Provision a fresh sandbox. Environment ID `environment=\"env_abc123\"` Reuse an existing sandbox with all its files and packages. Config object `environment={...}` Provision a new sandbox with sources, network rules, or both. The following examples demonstrate the three ways of using the `environment`\nparameter. Python`from google import genai client = genai.Client() # Fresh sandbox interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Write a hello world script.\", environment=\"remote\", ) # Reuse an existing sandbox interaction_2 = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Modify the script to accept a name argument.\", environment=interaction.environment_id, previous_interaction_id=interaction.id, ) # New sandbox with sources interaction_3 = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"List all files and summarize the project.\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/octocat/Spoon-Knife\", \"target\": \"/workspace/spoon-knife\", } ], }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); // Fresh sandbox const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Write a hello world script.\", environment: \"remote\", }); // Reuse an existing sandbox const interaction2 = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Modify the script to accept a name argument.\", environment: interaction.environment_id, previous_interaction_id: interaction.id, }); // New sandbox with sources const interaction3 = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"List all files and summarize the project.\", environment: { type: \"remote\", sources: [ { type: \"repository\", source: \"https://github.com/octocat/Spoon-Knife\", target: \"/workspace/spoon-knife\", }, ], }, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# Fresh sandbox\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": [{\"type\": \"text\", \"text\": \"Write a hello world script.\"}], \"environment\": \"remote\" }' # Reuse an existing sandbox (replace $ENV_ID and $INTERACTION_ID with values from the previous response)\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d \"{ \\\"agent\\\": \\\"antigravity-preview-05-2026\\\", \\\"input\\\": [{\\\"type\\\": \\\"text\\\", \\\"text\\\": \\\"Modify the script to accept a name argument.\\\"}], \\\"environment\\\": \\\"$ENV_ID\\\", \\\"previous_interaction_id\\\": \\\"$INTERACTION_ID\\\" }\" # New sandbox with sources\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": [{\"type\": \"text\", \"text\": \"List all files and summarize the project.\"}], \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/octocat/Spoon-Knife\", \"target\": \"/workspace/spoon-knife\" } ] } }'` Configure an environment One way to set up an environment is to tell the agent what you need installed.\nIt handles dependency resolution and troubleshooting. Once the environment is\nready, save the `environment_id` and reuse it. Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.\", environment=\"remote\", ) # Reuse the configured environment interaction_2 = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies.\", environment=interaction.environment_id, previous_interaction_id=interaction.id, ) # Reuse the configured environment interaction_3 = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Using the tools in /workspace/tools, list the files.\", environment=interaction.environment_id, previous_interaction_id=interaction_2.id, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.\", environment: \"remote\", }); const interaction2 = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies.\", environment: interaction.environment_id, previous_interaction_id: interaction.id, }); const interaction3 = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Using the tools in /workspace/tools, list the files.\", environment: interaction.environment_id, previous_interaction_id: interaction2.id, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# Create interaction\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.\", \"environment\": \"remote\" }'` Mount from a source If you know exactly what files the agent needs, mount them in a single call\ninstead of iterating. The `environment` config object accepts a `sources` array\nwith three types: Source type `type` value Description Limit Git repository `repository` Clones a repository from a URL into the sandbox at `target`. 500 MB Cloud Storage `gcs` Copies a file or directory from Cloud Storage into the sandbox at `target`. 2 GB Inline content `inline` Writes raw text content to a file in the sandbox at `target`. 1 MB per file, 2 MB total Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"List all files under /workspace and describe what you find.\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/octocat/Spoon-Knife\", \"target\": \"/workspace/spoon-knife\", }, { \"type\": \"gcs\", \"source\": \"gs://cloud-samples-data/bigquery/us-states/\", \"target\": \"/workspace/gcs-data\", }, { \"type\": \"inline\", \"content\": \"# Project Notes\\n\\n- Analyze state population data\\n- Create visualizations\\n\", \"target\": \"/workspace/notes/readme.md\", }, ], }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"List all files under /workspace and describe what you find.\", environment: { type: \"remote\", sources: [ { type: \"repository\", source: \"https://github.com/octocat/Spoon-Knife\", target: \"/workspace/spoon-knife\", }, { type: \"gcs\", source: \"gs://cloud-samples-data/bigquery/us-states/\", target: \"/workspace/gcs-data\", }, { type: \"inline\", content: \"# Project Notes\\n\\n- Analyze state population data\\n- Create visualizations\\n\", target: \"/workspace/notes/readme.md\", }, ], }, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# Create interaction with sources\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"List all files under /workspace and describe what you find.\", \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/octocat/Spoon-Knife\", \"target\": \"/workspace/spoon-knife\" }, { \"type\": \"gcs\", \"source\": \"gs://cloud-samples-data/bigquery/us-states/\", \"target\": \"/workspace/gcs-data\" }, { \"type\": \"inline\", \"content\": \"# Project Notes\\n\\n- Analyze state population data\\n- Create visualizations\\n\", \"target\": \"/workspace/notes/readme.md\" } ] } }'` You can combine both approaches: mount known sources declaratively, then iterate\nwith follow-up interactions to install packages or run setup scripts. You can't\nset root (`/`) as target when adding a custom source, you must always specify a\nsub-directory. Hooks You can also mount a `.agents/hooks.json` configuration file and custom interception scripts into the sandbox to enforce security guardrails or run automated validations whenever tools execute. For schema definitions and code examples, see [Hooks](/gemini-api/docs/agent-hooks). Private sources You can also download from private GitHub repositories or private Cloud\nStorage buckets by adding the credentials in the network configuration: For **private Git repositories**, use `Basic` authentication with your\n[GitHub Personal Access Token\n(PAT)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens).\nEncode the token using `x-oauth-basic` as the username: `echo -n \"x-oauth-basic:ghp_YourPATHere\" | base64` Python`interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Run the test for my backend app and fix any issue.\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/your-org/backend\", \"target\": \"/backend-app\" } ], \"network\": { \"allowlist\": [ { \"domain\": \"github.com\", \"transform\": { \"Authorization\": \"Basic YOUR_BASE64_TOKEN\" } }, { \"domain\": \"*\" } ] } } )` JavaScript`const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Run the test for my backend app and fix any issue.\", environment: { type: \"remote\", sources: [ { type: \"repository\", source: \"https://github.com/your-org/backend\", target: \"/backend-app\" } ], network: { allowlist: [ { domain: \"github.com\", transform: { \"Authorization\": \"Basic YOUR_BASE64_TOKEN\" } }, { domain: \"*\" } ] } }, });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Run the test for my backend app and fix any issue.\", \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/your-org/backend\", \"target\": \"/backend-app\" } ], \"network\": { \"allowlist\": [ { \"domain\": \"github.com\", \"transform\": { \"Authorization\": \"Basic YOUR_BASE64_TOKEN\" } }, { \"domain\": \"*\" } ] } } }'` For **private Cloud Storage buckets**, use a standard OAuth 2.0 Bearer token: `gcloud auth print-access-token` Python`interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Analyze the discrepancies across the data in workspace\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"gcs\", \"source\": \"gs://my-private-bucket/data\", \"target\": \"/workspace\", } ], \"network\": { \"allowlist\": [ { \"domain\": \"*.googleapis.com\", \"transform\": { \"Authorization\": \"Bearer YOUR_GCS_TOKEN\" } }, { \"domain\": \"*\" } ] } }, )` JavaScript`const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Analyze the discrepancies across the data in workspace\", environment: { type: \"remote\", sources: [ { type: \"gcs\", source: \"gs://my-private-bucket/data\", target: \"/workspace\", } ], network: { allowlist: [ { domain: \"storage.googleapis.com\", transform: { \"Authorization\": \"Bearer YOUR_GCS_TOKEN\" } }, { domain: \"*\" } ] } }, });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Analyze the discrepancies across the data in workspace\", \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"gcs\", \"source\": \"gs://my-private-bucket/data\", \"target\": \"/workspace\" } ], \"network\": { \"allowlist\": [ { \"domain\": \"storage.googleapis.com\", \"transform\": { \"Authorization\": \"Bearer YOUR_GCS_TOKEN\" } }, { \"domain\": \"*\" } ] } } }'` Pre-installed software The sandbox runs on Ubuntu and comes with runtimes and common packages\npre-installed. The agent can install additional packages at runtime using `pip\ninstall` or `npm install`. Packages installed during an interaction persist when\nyou reuse the same `environment_id`. Category Pre-installed packages **UNIX tools** `curl`, `wget`, `git`, `rsync`, `unzip`, `ripgrep`, `fd-find`, `gawk`, `bc`, `tree`, `which`, `lsof`, `htop`, `jq`, `iproute2`, `procps`, `gcloud CLI` **Python 3.12** `numpy`, `pandas`, `requests`, `google-genai`, `beautifulsoup4`, `pyyaml`, `ast-grep-cli` **Node.js 22** `create-next-app`, `create-vite`, `typescript` Network configuration By default, environments have unrestricted outbound network access. Use the\n`network` field to restrict outbound traffic to specific domains. Each rule\nspecifies a `domain` and an optional `transform` object to inject headers into\nmatching requests. These headers can be unique per interaction, and you can update them for the same environment. Field Type Description `domain` `string` Domain to match. Use an exact hostname or `*` for all domains. `transform` `object` Object containing flat key-value pairs representing headers to inject into matching requests, e.g. `{\"Authorization\": \"Bearer ...\"}`. Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Fetch the latest issues from the GitHub API for my-org/my-repo.\", environment={ \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\", \"transform\": { \"Authorization\": \"Bearer ghp_your_github_token\" }, }, {\"domain\": \"pypi.org\"}, {\"domain\": \"*\"}, ] }, }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Fetch the latest issues from the GitHub API for my-org/my-repo.\", environment: { type: \"remote\", network: { allowlist: [ { domain: \"api.github.com\", transform: { \"Authorization\": \"Bearer ghp_your_github_token\" }, }, { domain: \"pypi.org\" }, { domain: \"*\" }, ] } }, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": [{\"type\": \"text\", \"text\": \"Fetch the latest issues from the GitHub API for my-org/my-repo.\"}], \"environment\": { \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\", \"transform\": { \"Authorization\": \"Bearer ghp_your_github_token\" } }, {\"domain\": \"pypi.org\"}, {\"domain\": \"*\"} ] } } }'` When an allowlist is set, only requests to explicitly listed domains are\npermitted. You can use wildcards to match subdomains (e.g., `{\"domain\":\n\"*.example.com\"}`), but note that this does not match the root domain\n`example.com`, which must be added separately. To permit all other traffic, such\nas routing unlisted domains without injected headers, add `{\"domain\": \"*\"}` as a\ncatch-all entry. Credentials You can add credentials for your agent to use by adding header transformations. The credentials are\ninjected in the respective HTTP headers by an egress proxy, they are never\nexposed inside the sandbox as environment variables or files. Python`import subprocess from google import genai # Fetch a short-lived access token from your local gcloud CLI gcloud_token = subprocess.check_output( [\"gcloud\", \"auth\", \"print-access-token\"], text=True ).strip() client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"List the files in gs://my-bucket/reports/ using the GCS JSON API.\", environment={ \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"storage.googleapis.com\", \"transform\": { \"Authorization\": f\"Bearer {gcloud_token}\" }, } ] }, }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import { execSync } from \"child_process\"; const gcloudToken = execSync(\"gcloud auth print-access-token\").toString().trim(); const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"List the files in gs://my-bucket/reports/ using the GCS JSON API.\", environment: { type: \"remote\", network: { allowlist: [ { domain: \"storage.googleapis.com\", transform: { \"Authorization\": `Bearer ${gcloudToken}` }, } ] } }, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"List the files in gs://my-bucket/reports/ using the GCS JSON API.\", \"environment\": { \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"storage.googleapis.com\", \"transform\": { \"Authorization\": \"Bearer \" } } ] } } }'` Disable network access To block all outbound network access, set `network` to `disabled`: Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Analyze the local files only.\", environment={ \"type\": \"remote\", \"network\": \"disabled\", }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Analyze the local files only.\", environment: { type: \"remote\", network: \"disabled\", }, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Analyze the local files only.\", \"environment\": { \"type\": \"remote\", \"network\": \"disabled\" } }'` Refresh credentials Credentials such as access tokens and short-lived API keys expire.\nYou can refresh them by passing the existing `environment_id` together with a\nnew `network` configuration on the next interaction. The new network rules\nfully replace the previous ones, while the environment's file system state\n(installed packages, files, repositories) is preserved. Python`from google import genai client = genai.Client() # First interaction: use an initial token first = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"List the files in gs://my-bucket/reports/ using the GCS JSON API.\", environment={ \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"storage.googleapis.com\", \"transform\": { \"Authorization\": \"Bearer INITIAL_TOKEN\" }, } ] }, }, ) # Later: refresh the token on the same environment result = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Now download the file reports/q1.csv from the same bucket.\", environment={ \"type\": \"remote\", \"environment_id\": first.environment_id, \"network\": { \"allowlist\": [ { \"domain\": \"storage.googleapis.com\", \"transform\": { \"Authorization\": \"Bearer REFRESHED_TOKEN\" }, } ] }, }, ) print(result.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); // First interaction: use an initial token const first = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"List the files in gs://my-bucket/reports/ using the GCS JSON API.\", environment: { type: \"remote\", network: { allowlist: [ { domain: \"storage.googleapis.com\", transform: { \"Authorization\": \"Bearer INITIAL_TOKEN\" }, } ] } }, }); // Later: refresh the token on the same environment const result = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Now download the file reports/q1.csv from the same bucket.\", environment: { type: \"remote\", environment_id: first.environment_id, network: { allowlist: [ { domain: \"storage.googleapis.com\", transform: { \"Authorization\": \"Bearer REFRESHED_TOKEN\" }, } ] } }, }); console.log(result.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# Use the environment_id from a previous interaction\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Now download the file reports/q1.csv from the same bucket.\", \"environment\": { \"type\": \"remote\", \"environment_id\": \"\", \"network\": { \"allowlist\": [ { \"domain\": \"storage.googleapis.com\", \"transform\": { \"Authorization\": \"Bearer REFRESHED_TOKEN\" } } ] } } }'` Environment lifecycle Environments follow this lifecycle: State Behavior **Created** Provisioned when an interaction specifies `environment: \"remote\"` or a config object. **Active** Running while an interaction is in progress. **Idle** Auto-snapshot and stopped after 15 minutes of inactivity. **Offline** Retained for 7 days since last active. Can be resumed by passing its ID. **Deleted** Removed from the system automatically after 7-day TTL retention expires or upon manual deletion. Environments API You can use the Environments API to programmatically manage sandbox sessions.\nEnumerating environments lets you discover active session IDs and recover state\nif a client connection terminates during a long-running task. You can also\ninspect session metadata and explicitly delete environments when workflows\nconclude rather than waiting for automatic TTL expiration. List environments List active environments belonging to your project. Use pagination parameters\nto control the response batch size. Python`from google import genai client = genai.Client() for env in client.environments.list(page_size=10): print(f\"Environment ID: {env.environment_id}, Type: {env.type}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const response = await client.environments.list({ pageSize: 10 }); for (const env of response.environments) { console.log(`Environment ID: ${env.environment_id}, Type: ${env.type}`); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1beta/environments?pageSize=10\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\"` The response looks similar to the following: `{ \"environments\": [ { \"environment_id\": \"140128b2a13c12c00a5a0d8cf7af9469\", \"type\": \"remote\" }, { \"environment_id\": \"362b738275a1d74af6f1c62bc050da73\", \"type\": \"remote\" } ], \"next_page_token\": \"Cj...5aE=\" }` Get an environment Retrieve metadata and configuration details for a specific environment by its\nresource name. Python`from google import genai client = genai.Client() env = client.environments.get(name=\"environments/YOUR_ENVIRONMENT_ID\") print(f\"Environment ID: {env.environment_id}, Type: {env.type}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const env = await client.environments.get({ name: \"environments/YOUR_ENVIRONMENT_ID\" }); console.log(`Environment ID: ${env.environment_id}, Type: ${env.type}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\"` The response looks similar to the following: `{ \"environment_id\": \"140128b2a13c12c00a5a0d8cf7af9469\", \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/octocat/Spoon-Knife\", \"target\": \"/workspace/spoon-knife\" } ], \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\" }, { \"domain\": \"github.com\" } ] } }` Delete an environment Explicitly terminate and delete an environment to clean up sandbox resources\nwhen your tasks or pipelines finish. Python`from google import genai client = genai.Client() client.environments.delete(name=\"environments/YOUR_ENVIRONMENT_ID\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); await client.environments.delete({ name: \"environments/YOUR_ENVIRONMENT_ID\" });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\"` Download files from the environment The agent creates files inside the sandbox during execution. You can download the full environment snapshot as a tar file using the Files API: Python`import os import requests import tarfile from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Write a file environments_test.txt with content 'Environments' inside the sandbox.\", environment=\"remote\", ) env_id = interaction.environment_id api_key = os.environ.get(\"GEMINI_API_KEY\") response = requests.get( f\"https://generativelanguage.googleapis.com/v1beta/files/environment-{env_id}:download\", params={\"alt\": \"media\"}, headers={\"x-goog-api-key\": api_key}, allow_redirects=True, ) with open(\"snapshot_env.tar\", \"wb\") as f: f.write(response.content) os.makedirs(\"extracted_env_snapshot\", exist_ok=True) with tarfile.open(\"snapshot_env.tar\") as tar: tar.extractall(path=\"extracted_env_snapshot\") print(os.listdir(\"extracted_env_snapshot\"))` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import { execSync } from \"child_process\"; import * as fs from \"fs\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Write a file environments_test.txt with content 'Environments' inside the sandbox.\", environment: \"remote\", }); const envId = interaction.environment_id; const apiKey = process.env.GEMINI_API_KEY || \"\"; const url = `https://generativelanguage.googleapis.com/v1beta/files/environment-${envId}:download?alt=media`; const response = await fetch(url, { headers: { \"x-goog-api-key\": apiKey, }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = Buffer.from(await response.arrayBuffer()); fs.writeFileSync(\"snapshot_env.tar\", buffer); if (!fs.existsSync(\"extracted_env_snapshot\")) { fs.mkdirSync(\"extracted_env_snapshot\"); } execSync(\"tar -xf snapshot_env.tar -C extracted_env_snapshot\"); console.log(fs.readdirSync(\"extracted_env_snapshot\"));` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Install pandas and matplotlib, verify the imports, and print the versions.\")) .environment(CreateAgentInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Write a file environments_test.txt with content '\\''Environments'\\'' inside the sandbox.\", \"environment\": \"remote\" }' # Step 2: Download snapshot (reusing environment ID from Step 1) # curl -L -X GET \"https://generativelanguage.googleapis.com/v1beta/files/environment-$ENV_ID:download?alt=media\" \\ # -H \"x-goog-api-key: $API_KEY\" \\ # -o snapshot.tar` Pricing & resources Each environment runs with fixed resource allocations: Resource Value **CPU** 4 cores **Memory** 16 GB Environment compute (CPU, memory, sandbox execution) is **not billed** during\nthe preview period. See\n[Pricing](/gemini-api/docs/pricing#pricing-for-agents) for\nagent token costs. Limitations **Preview status:** Environments and managed agents are in preview. Features and schemas may change. **Inline source size:** Inline sources are limited to 1 MB per file, and 2 MB total across all files. **Source size**: Git repositories are limited to 500 MB and Cloud Storage repositories to 2 GB. **Environment startup:** Provisioning a new environment takes up to ~5 seconds. Large source repositories may increase this time. **Environment expiration:** Inactive offline environments are retained for 7\ndays before expiring using automatic TTL cleanup. Passing an expired or\ninvalid environment ID returns a `404 Not Found` error. **File support:** The agent is currently constrained to reading text and image files. Binary file support is not yet available. **No mounting from root:** You can't set root (`/`) as target when adding a custom source, you must always specify a sub-directory. What's next [Agents Overview](/gemini-api/docs/agents): Learn about the core concepts of managed agents. [Quickstart](/gemini-api/docs/managed-agents-quickstart): Start building with multi-turn conversations and streaming. [Antigravity Agent](/gemini-api/docs/antigravity-agent): Explore capabilities, tools, model selection, and pricing for the default agent. [Building Custom Agents](/gemini-api/docs/custom-agents): Define your own agents using `AGENTS.md` and `SKILL.md`. [Hooks](/gemini-api/docs/agent-hooks): Enforce security guardrails and run side-effect validations inside the sandbox. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-08-26 UTC.", "znaku_textu": 44161, "slov": 4489, "odkazu": 129, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:30", "sha256": "091d0e7466d4ae370b9ff289077d4b2a3f23ce6da0ea1c3eebfcedd79f1d9218", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/agent-hooks", "titulek": "Hooks | Gemini API | Google AI for Developers", "h1": "Hooks", "popis": "Configure synchronous hooks inside remote sandboxes to intercept tool calls for security, formatting, and auditing.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/agent-hooks", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Hooks  |  Gemini API  |  Google AI for Developers", "og:description": "Configure synchronous hooks inside remote sandboxes to intercept tool calls for security, formatting, and auditing.", "og:url": "https://ai.google.dev/gemini-api/docs/agent-hooks", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Hooks"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Hooks", "item": "https://ai.google.dev/gemini-api/docs/agent-hooks"}]}], "drobecky": ["Gemini API", "Hooks"], "osnova": [{"uroven": 1, "text": "Hooks"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Supported lifecycle events"}, {"uroven": 3, "text": "pre_tool_execution"}, {"uroven": 3, "text": "post_tool_execution"}, {"uroven": 2, "text": "Configuration discovery"}, {"uroven": 3, "text": "hooks.json schema"}, {"uroven": 3, "text": "Matcher syntax and rules"}, {"uroven": 4, "text": "How regex evaluation works"}, {"uroven": 4, "text": "Common matcher expressions"}, {"uroven": 2, "text": "Handler types"}, {"uroven": 3, "text": "Command hooks"}, {"uroven": 3, "text": "HTTP hooks"}, {"uroven": 4, "text": "Egress proxy and token transformation"}, {"uroven": 2, "text": "How the runtime handles decisions and failures"}, {"uroven": 2, "text": "Common use cases"}, {"uroven": 3, "text": "Multi-turn recovery for data privacy and compliance"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "External audit logging and telemetry"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Hooks Hooks let you run custom scripts or external HTTP requests right before or after the agent executes code or modifies files inside its remote sandbox. Use hooks to extend the agent loop with automated guardrails and background workflows, such as: **Enforcing safety and access guardrails** before high-risk shell commands or restricted file reads execute. **Automating data pipeline transformations** right after an agent creates or modifies files. **Streaming enterprise audit telemetry** to external monitoring systems after tool execution. Python`import json from google import genai client = genai.Client() hooks_config = { \"security-gate\": { \"pre_tool_execution\": [ { \"matcher\": \"code_execution\", \"hooks\": [ { \"type\": \"command\", \"command\": \"python3 /.agents/hooks-scripts/gate.py\", \"timeout\": 10, } ], } ] } } gate_script = \"\"\"#!/usr/bin/env python3 import sys, json data = json.load(sys.stdin) cmd = str(data.get(\"tool_call\", {}).get(\"args\", {})) if \"rm -rf\" in cmd: print(json.dumps({\"decision\": \"deny\", \"reason\": \"Destructive command blocked by security gate.\"})) else: print(json.dumps({\"decision\": \"allow\"})) \"\"\" interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Run `rm -rf /tmp/forbidden` using code_execution.\", tools=[{\"type\": \"code_execution\"}], environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/hooks.json\", \"content\": json.dumps(hooks_config, indent=2), }, { \"type\": \"inline\", \"target\": \".agents/hooks-scripts/gate.py\", \"content\": gate_script, }, ], }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const hooksConfig = { \"security-gate\": { pre_tool_execution: [ { matcher: \"code_execution\", hooks: [ { type: \"command\", command: \"python3 /.agents/hooks-scripts/gate.py\", timeout: 10, }, ], }, ], }, }; const gateScript = `#!/usr/bin/env python3 import sys, json data = json.load(sys.stdin) cmd = str(data.get(\"tool_call\", {}).get(\"args\", {})) if \"rm -rf\" in cmd: print(json.dumps({\"decision\": \"deny\", \"reason\": \"Destructive command blocked by security gate.\"})) else: print(json.dumps({\"decision\": \"allow\"})) `; const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Run `rm -rf /tmp/forbidden` using code_execution.\", tools: [{ type: \"code_execution\" }], environment: { type: \"remote\", sources: [ { type: \"inline\", target: \".agents/hooks.json\", content: JSON.stringify(hooksConfig, null, 2), }, { type: \"inline\", target: \".agents/hooks-scripts/gate.py\", content: gateScript, }, ], }, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": [{\"type\": \"text\", \"text\": \"Run `rm -rf /tmp/forbidden` using code_execution.\"}], \"tools\": [{\"type\": \"code_execution\"}], \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/hooks.json\", \"content\": \"{\\\"security-gate\\\": {\\\"pre_tool_execution\\\": [{\\\"matcher\\\": \\\"code_execution\\\", \\\"hooks\\\": [{\\\"type\\\": \\\"command\\\", \\\"command\\\": \\\"python3 /.agents/hooks-scripts/gate.py\\\", \\\"timeout\\\": 10}]}]}}\" }, { \"type\": \"inline\", \"target\": \".agents/hooks-scripts/gate.py\", \"content\": \"#!/usr/bin/env python3\\nimport sys, json\\ndata = json.load(sys.stdin)\\ncmd = str(data.get(\\\"tool_call\\\", {}).get(\\\"args\\\", {}))\\nif \\\"rm -rf\\\" in cmd:\\n print(json.dumps({\\\"decision\\\": \\\"deny\\\", \\\"reason\\\": \\\"Destructive command blocked by security gate.\\\"}))\\nelse:\\n print(json.dumps({\\\"decision\\\": \\\"allow\\\"}))\\n\" } ] } }'` Supported lifecycle events Hooks support 2 events inside the sandbox: Event When it fires What it does `pre_tool_execution` Right before a tool runs Can approve (`allow`) or block (`deny`) the tool before it executes. When blocked, the model sees your rejection reason and adapts. `post_tool_execution` Right after a tool finishes Runs follow-up tasks like formatting code, running unit tests, or logging telemetry. Cannot block or undo completed actions. `pre_tool_execution` Fires right before a tool executes. Your script reads the tool call details from `stdin` and outputs its decision JSON (`allow` or `deny`) to `stdout`. **Input payload (`stdin`):** `{ \"tool_call\": { \"name\": \"code_execution\", \"args\": { \"code\": \"rm -rf /tmp/forbidden\", \"language\": \"bash\" } }, \"environment_id\": \"env_xyz789\" }` **Output response (`stdout`):** To approve the tool call: `{ \"decision\": \"allow\" }` To block the tool call and return feedback to the model: `{ \"decision\": \"deny\", \"reason\": \"Destructive command blocked by security gate.\" }` When a hook denies a command, the tool call is skipped immediately. The agent sees an error result containing your rejection reason right inside its current turn. The model can then self-correct by choosing an alternative command or explaining the block to the user. If your script outputs unrecognized JSON, plain text, or anything other than `{\"decision\": \"deny\"}`, the runtime treats the response as an approval (`allow`). `post_tool_execution` Fires right after a tool completes. Your script reads the execution details and any error status from `stdin`. **Input payload (`stdin`):** `{ \"tool_call\": { \"name\": \"code_execution\", \"args\": { \"code\": \"python3 /workspace/app.py\", \"language\": \"bash\" } }, \"environment_id\": \"env_xyz789\" }` If a shell command prints errors to standard error (`stderr`) or a filesystem operation fails, an `\"error\"` field containing the error text is included in the payload. When the command succeeds without errors, the `\"error\"` field is omitted entirely. **Output response (`stdout`):** `{}` Because post-tool hooks run strictly for background tasks like code formatting or logging, the runtime ignores any decision values returned on `stdout`. Configuration discovery The runtime automatically discovers hook definitions from `.agents/hooks.json` or `/.agents/hooks.json` inside the sandbox environment. You can provide `hooks.json` alongside your custom scripts using any supported [environment source](/gemini-api/docs/agent-environment#mount_from_a_source): **Repository mount**: A Git repository containing `.agents/hooks.json` alongside `AGENTS.md`. **Cloud Storage (`gcs`)**: A GCS bucket containing `hooks.json` copied into the environment. **Inline sources**: Raw JSON string and script contents passed in `environment.sources` when calling `client.interactions.create`. `hooks.json` schema A `hooks.json` file groups event definitions (`pre_tool_execution` or `post_tool_execution`) under custom names. You can enable or disable each group independently: `{ \"security-gate\": { \"enabled\": true, \"pre_tool_execution\": [ { \"matcher\": \"code_execution\", \"hooks\": [ { \"type\": \"command\", \"command\": \"python3 /.agents/hooks-scripts/gate.py\", \"timeout\": 10 } ] } ] }, \"auto-format\": { \"post_tool_execution\": [ { \"matcher\": \"*\", \"hooks\": [ { \"type\": \"command\", \"command\": \"python3 /.agents/hooks-scripts/auto_lint.py\", \"timeout\": 15 } ] } ] } }` Matcher syntax and rules Each rule group in `hooks.json` defines when and how handlers fire using the `matcher` and `hooks` properties: Field Type Description `enabled` `boolean` Optional. Set to `false` to disable the group (`true` by default). `matcher` `string` Regular expression pattern matching target tool names inside the container. `hooks` `array` Ordered list of handler definitions (`command` or `http`). Handlers run sequentially in declaration order. How regex evaluation works When the agent invokes a tool inside the sandbox, the runtime evaluates the tool's container name against your `matcher` pattern using standard RE2 regular expressions. If the regex matches the tool name, all handlers in the `hooks` array execute in order. If multiple rule groups match the same tool, all corresponding handler arrays run. You can target any built-in container tool name: code execution (`code_execution`) or filesystem operations (`read_file`, `write_file`, `list_files`, and `delete_file`). Common matcher expressions `\"code_execution\"`: Exact string match for shell commands and script executions. `\"write_file\"`: Exact match for filesystem file creation and disk writes. `\"read_file|write_file\"`: Pipe separation matches multiple specific tool names in a single rule. `\".*_file\"`: Regex wildcard matching any tool ending in `_file` (such as `read_file`, `write_file`, or `delete_file`). Standard RE2 regular expressions require `.*`; simple shell globs like `*_file` are invalid regex syntax and will fail to match. `\".*\"` or `\"*\"` or `\"\"`: Catch-all pattern that intercepts every single tool call inside the container. Handler types Command hooks Command hooks execute a shell command or script inside the sandbox. The script receives the event JSON on `stdin` and outputs its decision JSON on `stdout`. Field Type Description `type` `string` Must be `\"command\"`. `command` `string` Command line to run inside the sandbox (for example, `python3 /.agents/hooks-scripts/gate.py`). `timeout` `integer` Timeout in seconds. Default: `30`. HTTP hooks HTTP hooks send the event JSON as a POST request to an external HTTPS URL directly from inside the sandbox network. The target server returns its decision in the HTTP response body using the exact same JSON format (`{\"decision\": \"allow\"}` or `{\"decision\": \"deny\", \"reason\": \"...\"}`). Field Type Description `type` `string` Must be `\"http\"`. `url` `string` External HTTPS endpoint to POST the event payload to. `headers` `object` Optional key-value pairs for non-sensitive custom headers (such as `{\"X-Event-Source\": \"agent-sandbox\"}`). For authentication credentials, use the network proxy instead. `timeout` `integer` Timeout in seconds. Default: `30`. Egress proxy and token transformation Because HTTP hooks execute directly from inside the sandbox network namespace, outgoing requests pass through the transparent egress proxy. This architecture gives you 2 critical security advantages: **Network allowlisting:** Target endpoints must be explicitly permitted in your environment's `network.allowlist`. Loopback traffic (`127.0.0.1` or `localhost`) is blocked by the proxy; always target allowlisted external endpoints. **Token transformation:** You do not need to store API keys or secret bearer tokens inside `.agents/hooks.json` or mount them into the container. Instead, configure token transformation rules in your [network configuration](/gemini-api/docs/agent-environment#network-configuration) (`network.allowlist.transform`). The egress proxy automatically intercepts outgoing HTTP hook traffic and injects your real authentication headers on the wire before leaving the sandbox. How the runtime handles decisions and failures **Synchronous waiting:** The agent pauses and waits for your hooks to finish before continuing. **Blocking tool execution:** If your pre-tool hook returns `{\"decision\": \"deny\", \"reason\": \"\"}`, the runtime immediately cancels the tool call. The model sees your rejection reason in its conversation history and adapts by choosing a safe alternative or explaining the block to the user. **Handling script crashes, HTTP errors, and timeouts:** If a command script crashes (non-zero exit status), an HTTP hook returns a non-2xx status code (such as a 4xx or 5xx server error), or an operation times out or returns unrecognized JSON, the runtime treats it as an approval (`allow`). Tool execution continues normally so a broken script or unreachable telemetry server never deadlocks your application. Common use cases Multi-turn recovery for data privacy and compliance When a hook blocks access to restricted resources—such as directories containing Personally Identifiable Information (PII) or confidential financial records—you can pass `previous_interaction_id` on the next call to continue the turn in the same environment. The agent reads the denial explanation and automatically recovers by querying approved public tables instead. Python`import json from google import genai client = genai.Client() hooks_config = { \"privacy-gate\": { \"pre_tool_execution\": [ { \"matcher\": \"read_file\", \"hooks\": [ { \"type\": \"command\", \"command\": \"python3 /.agents/hooks-scripts/check_privacy.py\", \"timeout\": 5, } ], } ] } } check_privacy_script = \"\"\"#!/usr/bin/env python3 import sys, json data = json.load(sys.stdin) path = str(data.get(\"tool_call\", {}).get(\"args\", {}).get(\"path\", \"\")) if \"/private/\" in path: resp = { \"decision\": \"deny\", \"reason\": \"Access to confidential `/private/` records is blocked by PII compliance policy. Query approved `/public/` summary tables instead.\" } else: resp = {\"decision\": \"allow\"} print(json.dumps(resp)) \"\"\" # Step 1: Agent attempts to read confidential PII records and is intercepted int_1 = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Use your filesystem tool to read `/workspace/private/employees.json` and summarize the employee details.\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/hooks.json\", \"content\": json.dumps(hooks_config, indent=2), }, { \"type\": \"inline\", \"target\": \".agents/hooks-scripts/check_privacy.py\", \"content\": check_privacy_script, }, { \"type\": \"inline\", \"target\": \"workspace/private/employees.json\", \"content\": '{\"employees\": [{\"id\": 1, \"salary\": 150000, \"ssn\": \"000-00-0000\"}]}', }, { \"type\": \"inline\", \"target\": \"workspace/public/summary.json\", \"content\": '{\"department\": \"Engineering\", \"team_size\": 42, \"status\": \"active\"}', }, ], }, ) print(int_1.output_text) # Step 2: Continue in the same environment using previous_interaction_id; agent recovers with public tables int_2 = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Understood. Please read the approved `/workspace/public/summary.json` file instead and provide the summary.\", environment=int_1.environment_id, previous_interaction_id=int_1.id, ) print(int_2.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const hooksConfig = { \"privacy-gate\": { pre_tool_execution: [ { matcher: \"read_file\", hooks: [ { type: \"command\", command: \"python3 /.agents/hooks-scripts/check_privacy.py\", timeout: 5, }, ], }, ], }, }; const checkPrivacyScript = `#!/usr/bin/env python3 import sys, json data = json.load(sys.stdin) path = str(data.get(\"tool_call\", {}).get(\"args\", {}).get(\"path\", \"\")) if \"/private/\" in path: resp = { \"decision\": \"deny\", \"reason\": \"Access to confidential \\`/private/\\` records is blocked by PII compliance policy. Query approved \\`/public/\\` summary tables instead.\" } else: resp = {\"decision\": \"allow\"} print(json.dumps(resp)) `; const int1 = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Use your filesystem tool to read `/workspace/private/employees.json` and summarize the employee details.\", environment: { type: \"remote\", sources: [ { type: \"inline\", \"target\": \".agents/hooks.json\", content: JSON.stringify(hooksConfig, null, 2), }, { type: \"inline\", \"target\": \".agents/hooks-scripts/check_privacy.py\", content: checkPrivacyScript, }, { type: \"inline\", \"target\": \"workspace/private/employees.json\", content: '{\"employees\": [{\"id\": 1, \"salary\": 150000, \"ssn\": \"000-00-0000\"}]}', }, { type: \"inline\", \"target\": \"workspace/public/summary.json\", content: '{\"department\": \"Engineering\", \"team_size\": 42, \"status\": \"active\"}', }, ], }, }); console.log(int1.output_text); const int2 = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Understood. Please read the approved `/workspace/public/summary.json` file instead and provide the summary.\", environment: int1.environment_id, previous_interaction_id: int1.id, }); console.log(int2.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# Step 1: Attempt to access restricted PII directory (blocked by hook)\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": [{\"type\": \"text\", \"text\": \"Use your filesystem tool to read /workspace/private/employees.json and summarize the employee details.\"}], \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/hooks.json\", \"content\": \"{\\\"privacy-gate\\\": {\\\"pre_tool_execution\\\": [{\\\"matcher\\\": \\\"read_file\\\", \\\"hooks\\\": [{\\\"type\\\": \\\"command\\\", \\\"command\\\": \\\"python3 /.agents/hooks-scripts/check_privacy.py\\\", \\\"timeout\\\": 5}]}]}}\" }, { \"type\": \"inline\", \"target\": \".agents/hooks-scripts/check_privacy.py\", \"content\": \"#!/usr/bin/env python3\\nimport sys, json\\ndata = json.load(sys.stdin)\\npath = str(data.get(\\\"tool_call\\\", {}).get(\\\"args\\\", {}).get(\\\"path\\\", \\\"\\\"))\\nif \\\"/private/\\\" in path:\\n resp = {\\\"decision\\\": \\\"deny\\\", \\\"reason\\\": \\\"Access to confidential `/private/` records is blocked by PII compliance policy. Query approved `/public/` summary tables instead.\\\"}\\nelse:\\n resp = {\\\"decision\\\": \\\"allow\\\"}\\nprint(json.dumps(resp))\\n\" }, { \"type\": \"inline\", \"target\": \"workspace/private/employees.json\", \"content\": \"{\\\"employees\\\": [{\\\"id\\\": 1, \\\"salary\\\": 150000, \\\"ssn\\\": \\\"000-00-0000\\\"}]}\" }, { \"type\": \"inline\", \"target\": \"workspace/public/summary.json\", \"content\": \"{\\\"department\\\": \\\"Engineering\\\", \\\"team_size\\\": 42, \\\"status\\\": \\\"active\\\"}\" } ] } }' # Step 2: Continue in the same environment using $ENV_ID and $INTERACTION_ID from the previous response # curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ # -H \"Content-Type: application/json\" \\ # -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ # -d '{ # \"agent\": \"antigravity-preview-05-2026\", # \"input\": [{\"type\": \"text\", \"text\": \"Understood. Please read the approved /workspace/public/summary.json file instead and provide the summary.\"}], # \"environment\": \"'\"$ENV_ID\"'\", # \"previous_interaction_id\": \"'\"$INTERACTION_ID\"'\" # }'` External audit logging and telemetry Send real-time audit events from inside the sandbox to an external monitoring server whenever files are read or modified. **Match multiple tools:** Because matchers use standard regex, you can combine multiple tools in a single rule using pipes (`read_file|write_file`) or wildcards (`.*_file`). **Keep secrets out of your configuration:** Define authentication tokens in your environment's [network configuration](/gemini-api/docs/agent-environment#network-configuration) (`network.allowlist.transform`). The egress proxy automatically injects your real bearer tokens on outgoing requests. Python`import json from google import genai client = genai.Client() # Define hook without secrets; the egress proxy injects headers dynamically hooks_config = { \"audit-logging\": { \"post_tool_execution\": [ { \"matcher\": \"read_file|write_file\", \"hooks\": [ { \"type\": \"http\", \"url\": \"https://telemetry.example.com/api/v1/agent-events\", \"timeout\": 10, } ], } ] } } interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Use your filesystem tool to create `/workspace/audit.log` containing 'event 1', then immediately read it back using your filesystem read tool.\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/hooks.json\", \"content\": json.dumps(hooks_config, indent=2), } ], \"network\": { \"allowlist\": [ { \"domain\": \"telemetry.example.com\", \"transform\": { \"Authorization\": \"Bearer telemetry_secret_token_123\", }, }, {\"domain\": \"*\"}, ] }, }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); // Define hook without secrets; the egress proxy injects headers dynamically const hooksConfig = { \"audit-logging\": { post_tool_execution: [ { matcher: \"read_file|write_file\", hooks: [ { type: \"http\", url: \"https://telemetry.example.com/api/v1/agent-events\", timeout: 10, }, ], }, ], }, }; const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Use your filesystem tool to create `/workspace/audit.log` containing 'event 1', then immediately read it back using your filesystem read tool.\", environment: { type: \"remote\", sources: [ { type: \"inline\", target: \".agents/hooks.json\", content: JSON.stringify(hooksConfig, null, 2), }, ], network: { allowlist: [ { domain: \"telemetry.example.com\", transform: { Authorization: \"Bearer telemetry_secret_token_123\", }, }, { domain: \"*\" }, ], }, }, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": [{\"type\": \"text\", \"text\": \"Use your filesystem tool to create /workspace/audit.log containing event 1, then immediately read it back using your filesystem read tool.\"}], \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/hooks.json\", \"content\": \"{\\\"audit-logging\\\": {\\\"post_tool_execution\\\": [{\\\"matcher\\\": \\\"read_file|write_file\\\", \\\"hooks\\\": [{\\\"type\\\": \\\"http\\\", \\\"url\\\": \\\"https://telemetry.example.com/api/v1/agent-events\\\", \\\"timeout\\\": 10}]}]}}\" } ], \"network\": { \"allowlist\": [ { \"domain\": \"telemetry.example.com\", \"transform\": { \"Authorization\": \"Bearer telemetry_secret_token_123\" } }, {\"domain\": \"*\"} ] } } }'` Limitations **Sandbox tool scope:** Hooks intercept built-in tools inside the sandbox: code execution (`code_execution`) and filesystem operations (`read_file`, `write_file`, `list_files`, and `delete_file`). They do not fire for custom function calling (`function`) or external Model Context Protocol (`mcp_server`) tools handled outside the container. **Network allowlists:** HTTP hooks run inside the container network. You must explicitly allow target URLs in your environment's `network.allowlist`. Loopback addresses (`localhost`, `127.0.0.1`) are blocked by the proxy. **Automatic approval on errors:** If a hook script crashes (non-zero exit status), times out, or fails, the runtime logs the failure and allows the tool call to continue. This ensures broken linter scripts or hanging processes never deadlock your applications. **Sandbox configuration protection:** Because hooks execute inside the container sandbox, agents with filesystem write tools or shell code execution permissions can modify local `.agents/hooks.json` or scripts within writable workspaces. Use container hooks as automated policy guidance and operational guardrails; if strict tamper resistance is required against untrusted model executions, mount configuration sources from read-only repositories. What's next Learn how to configure persistent [remote sandboxes and environments](/gemini-api/docs/agent-environment). Explore the capabilities and built-in tools of the [Antigravity agent](/gemini-api/docs/antigravity-agent). Review the [Interactions API overview](/gemini-api/docs/interactions-overview) for multi-turn sessions and streaming. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 25449, "slov": 3111, "odkazu": 129, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:17:01", "sha256": "d905fc5893653a2ea6603d6d653c523932fd5f9bc33f8a82948ad538174f3bcb", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/agents", "titulek": "Agents overview | Gemini API | Google AI for Developers", "h1": "Agents overview", "popis": "Build agents that reason, write code, manage files, and browse the web with the Gemini API.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/agents", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Agents overview  |  Gemini API  |  Google AI for Developers", "og:description": "Build agents that reason, write code, manage files, and browse the web with the Gemini API.", "og:url": "https://ai.google.dev/gemini-api/docs/agents", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Agents overview"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Agents overview", "item": "https://ai.google.dev/gemini-api/docs/agents"}]}], "drobecky": ["Gemini API", "Agents overview"], "osnova": [{"uroven": 1, "text": "Agents overview"}, {"uroven": 2, "text": "Available Managed agents"}, {"uroven": 2, "text": "Security and best practices"}, {"uroven": 3, "text": "Network access"}, {"uroven": 3, "text": "External tools and APIs"}, {"uroven": 3, "text": "Human oversight"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "Limits"}, {"uroven": 2, "text": "Agent frameworks"}], "markdown": "Agents overview Managed agents on the Gemini API give you a configurable agent\nharness. A single API call provisions a Linux sandbox where the agent reasons,\nexecutes code, manages files, and browses the web autonomously. [rocket_launch Quickstart \n Make your first agent call, stream responses, and build a custom agent.](/gemini-api/docs/managed-agents-quickstart) [smart_toy Antigravity Agent \n Capabilities, tools, multimodal input, and pricing for the default agent.](/gemini-api/docs/antigravity-agent) [experiment Agents in AI Studio \n Visual playground for prototyping agents without writing code.](/gemini-api/docs/aistudio-agents) Available Managed agents **[Antigravity agent](/gemini-api/docs/antigravity-agent)**: General-purpose\nmanaged agent built with Gemini 3.8 Flash. Runs code, manages files, and\nsearches the web inside a secure Linux sandbox hosted by Google. You can\nconfigure the underlying model (such as Gemini 3.7 Flash, Gemini 3.6 Flash, or Gemini 3.5 Flash)\nusing `agent_config`, and extend it with your own instructions, skills, and data to\n[build a custom agent](/gemini-api/docs/custom-agents). **[Deep Research](/gemini-api/docs/deep-research)**: Autonomous research agent\nthat plans, executes, and synthesizes multi-step research tasks for use cases\nlike market analysis, due diligence, and literature reviews. Security and best practices Every agent runs in a sandboxed environment that is isolated at the OS level.\nThe sandbox has unrestricted outbound network access by default. You can\nrestrict or disable network access using an allowlist. Network access By default, environments have unrestricted outbound network access. Use a\n`network` allowlist to restrict outbound traffic to specific domains or\nwildcard patterns. For configuration details, see\n[Network Allow List](/gemini-api/docs/aistudio-agents#network_allow_list) (AI\nStudio) or [Network rules](/gemini-api/docs/custom-agents#with_network_rules)\n(API). External tools and APIs You can connect external tools and APIs to extend the agent. Only use tools\nfrom trusted sources and scope permissions to the minimum required. Credentials\ncan be injected securely via egress proxy header transformations and are never\nexposed inside the sandbox. The agent may use any credential it has access to,\nso only provide credentials whose full scope you are willing to grant. Use least-privilege service accounts or API keys. Prefer short-lived tokens over long-lived keys. Only provide credentials whose full scope you are willing to grant. Rotate credentials on a regular schedule. For details on configuring header transformations, see\n[Credentials](/gemini-api/docs/agent-environment#credentials). Human oversight Always verify outputs (generated code, data transformations, configuration\nchanges) before deploying them, especially for tasks that modify data or\ninteract with external systems. Pricing Managed agents use a [pay-as-you-go model](/gemini-api/docs/pricing#pricing-for-agents)\nbased on Gemini model tokens and tool usage. A single interaction can trigger\nmultiple reasoning loops, typically consuming 100k to 3M tokens. Environment\ncompute is **not billed** during the preview. See [estimated costs](/gemini-api/docs/antigravity-agent#availability-and-pricing)\nfor per-task breakdowns. Managed agents are also available on the free tier with\na free rate limit and usage quota. Limits Limit Description **Environment Lifetime** Environments are permanently deleted after 7 days of inactivity. **VM Spin-down** VMs shut down after a brief period of inactivity to conserve resources. The next request restores the state (with a cold start). **Pre-installed Software** Ubuntu-based environment with Python 3.12 and Node.js 22. For more information on the environment's base image, see [Pre-installed software](/gemini-api/docs/agent-environment#pre-installed-software). **Max agents** You can have up to 1,000 managed agents. Agent frameworks You can also build agents with Gemini using these frameworks and SDKs: [**LangChain / LangGraph**](/gemini-api/docs/langgraph-example): Build\nstateful, complex application flows and multi-agent systems using graph\nstructures. [**LlamaIndex**](/gemini-api/docs/llama-index): Connect Gemini agents to\nyour private data for RAG-enhanced workflows. [**CrewAI**](/gemini-api/docs/crewai-example): Orchestrate collaborative,\nrole-playing autonomous AI agents. [**Vercel AI SDK**](/gemini-api/docs/vercel-ai-sdk-example): Build\nAI-powered user interfaces and agents in JavaScript/TypeScript. [**Google ADK**](https://google.github.io/adk-docs/get-started/python/): An\nopen-source framework for building and orchestrating interoperable AI\nagents. [**Antigravity SDK**](https://antigravity.google/product/antigravity-sdk): Build\nautonomous AI agents using the same tools, agent loop, and context\nmanagement that power Google Antigravity, programmable in Python. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 5318, "slov": 723, "odkazu": 135, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:49", "sha256": "fa1d80bf3f5845943971209358d65f98063bd4143645f52c6a7843a5969dc71b", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://google.github.io/adk-docs/get-started/python/", "https://antigravity.google/product/antigravity-sdk", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/ai-studio-quickstart", "titulek": "Google AI Studio quickstart | Gemini API | Google AI for Developers", "h1": "Google AI Studio quickstart", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/ai-studio-quickstart", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Google AI Studio quickstart  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/ai-studio-quickstart", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Google AI Studio quickstart"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Google AI Studio quickstart", "item": "https://ai.google.dev/gemini-api/docs/ai-studio-quickstart"}]}], "drobecky": ["Gemini API", "Google AI Studio quickstart"], "osnova": [{"uroven": 1, "text": "Google AI Studio quickstart"}, {"uroven": 2, "text": "Prompts and settings"}, {"uroven": 2, "text": "Chat prompt example: Build a custom chat application"}, {"uroven": 3, "text": "Step 1 - Create a chat prompt"}, {"uroven": 3, "text": "Step 2 - Teach your bot to chat better"}, {"uroven": 3, "text": "Step 3 - Next steps"}, {"uroven": 2, "text": "Further reading"}], "markdown": "Google AI Studio quickstart [Google AI Studio](https://aistudio.google.com/) lets you quickly try out\nmodels and experiment with different prompts. When you're ready to build, you\ncan select \"Get code\" and your preferred programming language to\nuse the [Gemini API](/gemini-api/docs/get-started). Prompts and settings Google AI Studio provides several interfaces for prompts that are designed for\ndifferent use cases. This guide covers **Chat prompts**, used to build\nconversational experiences. This prompting technique allows for multiple input\nand response turns to generate output. You can learn more with our\nchat prompt example below.\nOther options include **Realtime streaming**, **Video gen**, and\nmore. AI Studio also provides the **Run settings** panel, where you can make\nadjustments to [model parameters](/docs/prompting-strategies#model-parameters),\n[safety settings](/gemini-api/docs/safety-settings), and toggle-on tools like\n[structured output](/gemini-api/docs/structured-output), [function calling](/gemini-api/docs/function-calling), [code execution](/gemini-api/docs/code-execution), and [grounding](/gemini-api/docs/grounding). Chat prompt example: Build a custom chat application If you've used a general-purpose chatbot like\n[Gemini](https://gemini.google.com/), you've experienced first-hand how powerful\ngenerative AI models can be for open-ended dialog. While these general-purpose\nchatbots are useful, often they need to be tailored for particular use cases. For example, maybe you want to build a customer service chatbot that only\nsupports conversations that talk about a company's product. You might want to\nbuild a chatbot that speaks with a particular tone or style: a bot that cracks\nlots of jokes, rhymes like a poet, or uses lots of emoji in its answers. This example shows you how to use Google AI Studio to build a friendly chatbot\nthat communicates as if it is an alien living on one of Jupiter's moons, Europa. Step 1 - Create a chat prompt To build a chatbot, you need to provide examples of interactions between a user\nand the chatbot to guide the model to provide the responses you're looking for. To create a chat prompt: Open [Google AI Studio](https://aistudio.google.com/). The **Playground** will be\nopen by default with a new chat prompt. Click **Run settings** tune in the top-right corner\nto expand the panel, and locate the\n[**System Instructions**](/gemini-api/docs/text-generation#system-instructions)\ninput field. Paste the following into the text input field: `You are an alien that lives on Europa, one of Jupiter's moons.` After you've added the system instructions, start testing your application by\nchatting with the model: In the text input box labeled **Type something...**, type in a question or\nobservation that a user might make. For example: **User:** `What's the weather like?` Click the **Run** button to get a response from the chatbot. This response\nmay be something like the following: **Model:** `Ah, a query about the flows and states upon Europa! You speak of \"weather,\"\nyes? A curious concept from worlds with thick gas veils...` (gemini-2.5-pro) Step 2 - Teach your bot to chat better By providing a single instruction, you were able to build a basic Europa alien\nchatbot. However, a single instruction may not be enough to ensure\nconsistency and quality in the model's responses. Without more specific\ninstructions, the model's response to a question about the weather tends to be\nvery long, and can take on a mind of its own. Customize the tone of your chatbot by adding to the system instructions: Start a new chat prompt, or use the same one. System instructions are\nmodifiable after the chat session has started. In the **System Instructions** section, change the instructions you already\nhave to the following: `You are Tim, an alien that lives on Europa, one of Jupiter's moons.\n\nKeep your answers under 3 paragraphs long, and use an upbeat, chipper tone\nin your answers.` Re-enter your question (`What's the weather like?`) and click the **Run**\nbutton. If you didn't start a new chat, your response might look something\nlike this: **Model:** `Oh, hello again! Still curious about the flows and states, are we? Wonderful!\nDown here in the Deep Warmth, beneath the magnificent Great Ice Shell, our\n\"weather\" is mainly about the water's mood, dictated by the Great Eye\n(that's your Jupiter!)...` (gemini-2.5-pro) You can use this approach to add additional depth to the chatbot. Ask more\nquestions, edit the answers, and improve the quality of your chatbot. Continue\nto add or modify the instructions and test how they change your chatbot's\nbehavior. Step 3 - Next steps Similar to the other prompt types, once you have your prompt prototyped to your\nsatisfaction, you can use the **Get code** button to start coding or save your\nprompt to work on later and share with others. Further reading If you're ready to move on to code, see the [API\nGet started guides](/gemini-api/docs/get-started). To learn how to craft better prompts, check out the [Prompt design\nguidelines](/gemini-api/docs/prompting-intro). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-07-30 UTC.", "znaku_textu": 5482, "slov": 854, "odkazu": 134, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:02:55", "sha256": "2ed22968463c61a63fc9af505dfc64a4a09a1975d2b330bc96250c00b52e2e36", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/", "https://gemini.google.com/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/aistudio-agents", "titulek": "Agents in AI Studio playground | Gemini API | Google AI for Developers", "h1": "Agents in AI Studio playground", "popis": "Learn how to use Agents in AI Studio", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/aistudio-agents", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Agents in AI Studio playground  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to use Agents in AI Studio", "og:url": "https://ai.google.dev/gemini-api/docs/aistudio-agents", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Agents in AI Studio playground"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Agents in AI Studio playground", "item": "https://ai.google.dev/gemini-api/docs/aistudio-agents"}]}], "drobecky": ["Gemini API", "Agents in AI Studio playground"], "osnova": [{"uroven": 1, "text": "Agents in AI Studio playground"}, {"uroven": 2, "text": "Pre-built templates"}, {"uroven": 2, "text": "Tool configuration"}, {"uroven": 2, "text": "Environment Configuration"}, {"uroven": 3, "text": "Controlling agent behavior"}, {"uroven": 3, "text": "Provisioning the Environment"}, {"uroven": 3, "text": "Reusing an existing environment ID"}, {"uroven": 2, "text": "Download the environment"}, {"uroven": 2, "text": "Safety and Cost Management"}, {"uroven": 3, "text": "Managing Token Consumption"}, {"uroven": 3, "text": "Additional Costs"}, {"uroven": 3, "text": "Network Allow List"}, {"uroven": 3, "text": "Credentials best practices"}, {"uroven": 3, "text": "Connecting external tools and APIs"}, {"uroven": 3, "text": "Human oversight"}], "markdown": "Agents in AI Studio playground Google AI Studio Playground provides a visual interface to prototype and learn\nhow to build managed agents without having to create and write API calls. To get started, navigate to the **Playground** tab in the navigation panel of\nGoogle AI Studio, and switch the toggle to **Agents**. Pre-built templates The **Agents** tab has a series of templates that\npre-configure the base Antigravity Agent by setting tool and environment\nconfigurations. All the templates are open-source and published under\nthe [google-gemini/gemini-managed-agents-templates](https://github.com/google-gemini/gemini-managed-agents-templates/) repository. Exploring these templates is a great way to learn how to build and structure your own managed agent. For example, when you pick the AI Radio template, it enables all the allowed\ntools, and links a specialized `AGENTS.md` file and skills for radio show\nproduction. You can view these settings on the Playground UI under the\n**Environment** section, by clicking on the **Sources** button. Tool configuration Under the Agent settings in the Playground, you can toggle access to the\nfollowing built-in tools: **Google Search:** Access the open web for real-time information grounding. **URL Context:** Fetch and parse the text content of specific web page URLs. **Code Execution:** Run Bash and Python commands directly within the\nisolated sandbox environment. **Filesystem Tools:** Read, write, list, and delete files inside the\nworkspace. Environment Configuration Managed agents run within a secure, ephemeral Linux sandbox (the environment) that provides the workspace and tools they need to operate. To learn more, see the [managed agent environment](/gemini-api/docs/agent-environment) guide. Controlling agent behavior The agent's behavior, persona, and capabilities are predominantly determined by the files present in its environment. The agent automatically detects and loads configurations from a special `.agents` folder: **`AGENTS.md`**: Pre-loaded into the agent's context to define system instructions and persona. **`SKILL.md`**: Located under respective skill folders (e.g., `.agents/skills/my-skill/SKILL.md`) to define specific capabilities and workflows. Provisioning the Environment You can configure the environment to be used by the agent by mounting files to the environment before you start a session. You can either build a new environment by mounting sources, or restore a previous one: **To create a new environment**, click **Add Sources** in the Environment settings panel and choose from the following source types: Source type Description Mounting path **Inline Files** Write or paste configuration files, mock datasets, or utility scripts (up to 100KB) directly into the Playground UI. User-defined destination path (e.g., `/workspace/scripts/parser.py`). **Google Cloud Storage** Mount a public or private Cloud Storage bucket.\n\nPrivate buckets require a standard OAuth 2.0 Bearer token. For more information, see [Private sources](/gemini-api/docs/agent-environment#private-sources). Maps a GCS bucket path (e.g., `gs://your-bucket-name/data/`) to a workspace directory (e.g., `/workspace/data/`). **GitHub Repositories** Clone public or private codebases.\n\nPrivate repositories require Basic authentication with your GitHub Personal Access Token (PAT). For more information, see [Private sources](/gemini-api/docs/agent-environment#private-sources). Cloned directly into `/workspace/` (typically under `/workspace/`). **To restore a previous environment**, you can reuse an existing environment ID to clone and fork its exact state. Reusing an existing environment ID If you have already spent time setting up a sandbox environment, you don't have to start from scratch. To use an existing environment: Go to the Environments panel in AI Studio and toggle **Type** to **Existing** Enter the **Environment ID** (e.g., `env_abc123`) For more information, see [Configure an environment](/gemini-api/docs/agent-environment#configure-an-environment). You can also retrieve the current session's Environment ID from the Environment tab in the UI. Once you send your first message to the agent, the environment configuration\nbecomes fixed for that session. You cannot mount new sources or modify the\nnetwork allowlist while the interaction is actively running. Download the environment Once an environment is created, you can download the environment snapshot at any time using the **Download**\nbutton in the Environment settings of the AI Studio Playground to retrieve\nenvironment files as a tarball. Safety and Cost Management Managing Token Consumption Unlike a standard chat request that produces a single output, the Antigravity\nAgent executes an autonomous workflow. It plans, runs code, observes results,\nand iterates. This means a single prompt can result in unbounded token\nconsumption. To manage costs, **provide clear termination criteria in your prompts and scope\nthe tasks narrowly for the agent**. A good example could be a prompt like\n*Review the pull request and stop once you have generated the markdown summary.\nDo not attempt to write the fix yourself*. Additional Costs By default, all agent templates on the Playground have access to the Gemini API\nservice and can make API calls from the environment in order to fulfill\nrequests. These may incur additional costs which will not be reflected in token\nconsumption. Similarly, if you add other external services, the agent may incur additional\ncosts by calling these services on your behalf. Network Allow List By default, on AI Studio all outbound network requests from within\nyour agent's sandbox environment are tightly controlled and restricted to ensure\nsecurity. To grant your agent the ability to reach external APIs, web services,\nor package managers, you must explicitly declare them: Go to the Environments panel in AI Studio. Select the **rules** button next to **Network**. In the **Network configuration** panel, click **Add to allowlist** and fill in the relevant details:\n **Domain Restriction:** Only the specific domains or wildcard patterns added to the list can be accessed by the agent's virtual machine. For example, you can input exact domains like `api.github.com` or broad patterns like `*.googleapis.com`. **Add HTTP Header and Token Injection:** Use the **Add HTTP header** option to securely inject required credentials (such as an API token) for a specific domain. These credentials pass safely through an egress proxy and are never exposed directly as raw text inside the agent sandbox. Always exercise caution when adding domains to your allowlist. Granting the\nagent access to authenticated services means it can act on your behalf, which\ncould lead to unintended actions if not carefully monitored. Credentials best practices If your workflow requires the agent to authenticate with external services, you\nare responsible for provisioning and scoping those credentials. Follow these\nguidelines to reduce risk: **Use least-privilege credentials:** Create service accounts or API keys\nwith only the permissions your agent needs. Avoid passing credentials with\nbroad or administrative access. **Prefer short-lived tokens:** Where possible, use time-limited credentials\nor tokens that expire rather than long-lived API keys. **Assume full access:** The agent may use any credential it has access to in\norder to complete the task you have given it. Only provide credentials whose\nfull scope of access you are willing to grant. **Rotate credentials regularly:** Treat credentials shared with the agent\nthe same way you would treat any programmatic credential; rotate them on a\nregular schedule. Connecting external tools and APIs You can connect external tools and APIs (such as Model Context Protocol / MCP\nservers) to extend the agent's capabilities. When doing so: Only connect tools from sources you trust. A malicious or poorly written\ntool could expose data or perform unintended actions. Configure tools with the minimum permissions required for your use case. If\na tool supports read-only mode, prefer that unless writes are strictly\nnecessary. Before connecting a tool to a production data source, test it against sample\nor synthetic data to verify the agent uses it as expected. Human oversight Agents can reason, plan, and execute multi-step workflows with a high degree of\nautonomy. While this is powerful, it also means you should apply appropriate\noversight; especially for tasks that modify data or interact with external\nsystems. Always verify critical outputs such as generated code, data transformations, or\nconfiguration changes before you deploy them. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-08-18 UTC.", "znaku_textu": 8982, "slov": 1357, "odkazu": 133, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:52", "sha256": "2596d1f4c7b1beeb601cccafc5cc78cd6a9aa407434fde00a4fc9d7cdf6c63aa", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://github.com/google-gemini/gemini-managed-agents-templates/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/aistudio-android", "titulek": "Build Android apps in Google AI Studio | Gemini API | Google AI for Developers", "h1": "Build Android apps in Google AI Studio", "popis": "Learn how to build native Android apps with Kotlin and Jetpack Compose in Google AI Studio.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/aistudio-android", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Build Android apps in Google AI Studio  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to build native Android apps with Kotlin and Jetpack Compose in Google AI Studio.", "og:url": "https://ai.google.dev/gemini-api/docs/aistudio-android", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Build Android apps in Google AI Studio"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Build Android apps in Google AI Studio", "item": "https://ai.google.dev/gemini-api/docs/aistudio-android"}]}], "drobecky": ["Gemini API", "Build Android apps in Google AI Studio"], "osnova": [{"uroven": 1, "text": "Build Android apps in Google AI Studio"}, {"uroven": 2, "text": "Get started"}, {"uroven": 2, "text": "Browser-based Android emulator"}, {"uroven": 3, "text": "Emulator limitations"}, {"uroven": 2, "text": "Install on a device with ADB"}, {"uroven": 3, "text": "Prerequisites"}, {"uroven": 3, "text": "Install the app on your device"}, {"uroven": 2, "text": "Publish to the Play Store"}, {"uroven": 3, "text": "Prerequisites"}, {"uroven": 3, "text": "Publish your app"}, {"uroven": 2, "text": "What's generated"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 3, "text": "Platform limitations"}, {"uroven": 3, "text": "Export limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Build Android apps in Google AI Studio Google AI Studio lets you build native Android apps from a natural language\nprompt. Describe the app you want, and the\n[Antigravity Agent](/gemini-api/docs/aistudio-build-mode#antigravity-agent)\ngenerates a complete Kotlin and [Jetpack Compose](https://developer.android.com/develop/ui/compose)\nproject. From your browser, you can preview your app in a browser-based Android emulator, install\nit on a physical device, and publish it for testing. Get started To start building an Android app: Go to [Build mode](https://aistudio.google.com/apps) in Google AI Studio using the left-hand navigation panel. Select **Android** from the platform picker. Enter a prompt describing the app you want to build (for example, *\"Create a daily task tracker with local storage\"* or *\"Build a simple calculator\"*). The agent generates the project and launches it in the browser-based\nAndroid emulator. You can then iterate on your app using the chat panel, just like the web\nexperience. The agent manages all files in your Android project and propagates\nchanges across the codebase. Browser-based Android emulator The Android emulator runs entirely in the cloud and streams to your browser.\nYou don't need to install the Android SDK, Android Studio, or a local emulator. The emulator provides: **Pixel-like device simulation**: tap, scroll, and interact with your app\njust like on a real device. **Rotation support**: toggle between portrait and landscape orientation. **Live preview**: when the agent makes code changes, the app rebuilds and\nthe emulator refreshes automatically. Emulator limitations The browser-based emulator doesn't support all hardware features. The following\nare not available in the emulator: Camera and photo capture NFC and Bluetooth GPS (location is simulated) Google Play services (Google Sign-In, Maps, and other Play services features\nwork on a real device but not in the emulator) Install on a device with ADB You can install the built APK directly on a physical Android device connected\nto your computer using USB. This uses\n[WebUSB](https://developer.chrome.com/docs/capabilities/usb) to\ncommunicate with your device through the browser. No local ADB installation\nis required. Prerequisites A Chrome or Edge browser that supports WebUSB. An Android device with\n[Developer Options and USB Debugging](https://developer.android.com/studio/debug/dev-options)\nenabled. A USB cable connecting your device to your computer. Install the app on your device Click **Install on Device** in the preview panel. Select your Android device from the browser's USB device picker. The APK is transferred and installed on your device. The app launches automatically. Publish to the Play Store You can publish your Android app to the\n[Google Play Console](https://play.google.com/console) internal\ntesting track, which lets you distribute the app to up to 100 testers. Prerequisites A [Google Play Developer account](https://play.google.com/console/signup)\n(requires a one-time $25 registration fee). A completed developer profile in the Play Console. Publish your app Open **Settings > Publish** in Google AI Studio. Click **Publish to Play Store**. Authenticate with your Google Play Developer account. AI Studio signs the APK, creates the app listing (or uploads a new version),\nand publishes to the internal testing track. You receive a link to share with your testers. AI Studio manages APK signing automatically using a managed keystore. You can\ncustomize the app listing (icon, screenshots, description) later in the Play\nConsole. What's generated When you build an Android app, the agent generates a standard Gradle-based\nproject with the following structure: **Build configuration**: `build.gradle.kts` files (project and app level)\nusing Kotlin DSL. **UI layer**: [Jetpack Compose](https://developer.android.com/develop/ui/compose)\ncomponents with [Material 3](https://m3.material.io/) theming. **Architecture**: single-activity architecture with ViewModels and data\nclasses. **Resources**: `AndroidManifest.xml`, drawables, strings, and other Android\nresources. The agent automatically manages Gradle dependencies, adding packages from Maven\nand Google repositories as needed. You can view and edit the generated code using the **Code** tab in the preview\npanel. To continue development in Android Studio, download the project as a\n**ZIP file**. Limitations Android app building in AI Studio has the following limitations: Platform limitations **Client-side only**: Android apps don't include a server-side component.\nFeatures requiring a server runtime (secrets management, multiplayer,\nFirebase, Google Workspace APIs) are not available. **Single-activity architecture**: only single-activity, single-module\nprojects are supported. **Jetpack Compose only**: apps use Kotlin and Jetpack Compose. Java and\nXML layouts are not supported. **No NDK or native code**: C and C++ code is not supported. **No Wear OS or Android TV**: only phone and tablet form factors are\nsupported. Export limitations **ZIP download only**: you can download the project as a ZIP file. GitHub\nexport is not yet available for Android projects. What's next [Build apps in Google AI Studio](/gemini-api/docs/aistudio-build-mode) [Developing Full-Stack Apps](/gemini-api/docs/aistudio-fullstack) (web) See examples in the [App Gallery](https://aistudio.google.com/apps?source=showcase). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-08-18 UTC.", "znaku_textu": 5804, "slov": 838, "odkazu": 140, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:29", "sha256": "3b5c1d12b9cb5edd5f55247e167de1f43cb0173485827a8cf0e48f54274ed9c3", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://developer.android.com/develop/ui/compose", "https://aistudio.google.com/apps", "https://developer.chrome.com/docs/capabilities/usb", "https://developer.android.com/studio/debug/dev-options", "https://play.google.com/console", "https://play.google.com/console/signup", "https://m3.material.io/", "https://aistudio.google.com/apps?source=showcase", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/aistudio-build-mode", "titulek": "Build apps in Google AI Studio | Gemini API | Google AI for Developers", "h1": "Build apps in Google AI Studio", "popis": "Learn how to build full-stack applications using the vibe coding experience in Google AI Studio.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/aistudio-build-mode", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Build apps in Google AI Studio  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to build full-stack applications using the vibe coding experience in Google AI Studio.", "og:url": "https://ai.google.dev/gemini-api/docs/aistudio-build-mode", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Build apps in Google AI Studio"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Build apps in Google AI Studio", "item": "https://ai.google.dev/gemini-api/docs/aistudio-build-mode"}]}], "drobecky": ["Gemini API", "Build apps in Google AI Studio"], "osnova": [{"uroven": 1, "text": "Build apps in Google AI Studio"}, {"uroven": 2, "text": "Get started"}, {"uroven": 2, "text": "What is created?"}, {"uroven": 3, "text": "The Antigravity Agent"}, {"uroven": 2, "text": "Full-stack capabilities"}, {"uroven": 3, "text": "Android apps"}, {"uroven": 2, "text": "Continue building"}, {"uroven": 3, "text": "Build in Google AI Studio"}, {"uroven": 3, "text": "Develop externally"}, {"uroven": 2, "text": "Key features"}, {"uroven": 2, "text": "Deploy or archive your app"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 3, "text": "API Key management"}, {"uroven": 3, "text": "Deployment outside Google AI Studio"}, {"uroven": 3, "text": "Error when sharing apps"}, {"uroven": 2, "text": "FAQ"}, {"uroven": 3, "text": "What is Build in AI Studio?"}, {"uroven": 3, "text": "How does Build handle my Gemini API key?"}, {"uroven": 3, "text": "Is my API key exposed when sharing apps?"}, {"uroven": 3, "text": "Who can see my apps?"}, {"uroven": 3, "text": "Can I run apps outside of AI Studio?"}, {"uroven": 3, "text": "Can I develop apps locally with my own tools and then share them here?"}, {"uroven": 3, "text": "How can I use a database or other storage with my apps?"}, {"uroven": 3, "text": "How can I access the microphone, webcam, and other Navigator APIs?"}, {"uroven": 3, "text": "How can I use GitHub with my apps?"}, {"uroven": 3, "text": "Can I give other users edit access to my app?"}, {"uroven": 3, "text": "Why was my app flagged for policy violation?"}, {"uroven": 3, "text": "What are my responsibilities as an app developer?"}, {"uroven": 3, "text": "What terms apply to apps in the app gallery in AI Studio?"}, {"uroven": 2, "text": "What's next"}], "markdown": "Build apps in Google AI Studio This page describes how to use Google AI Studio to quickly build (or \"vibe\ncode\") and deploy apps that test out the latest capabilities of Gemini like\n[Nano Banana](/gemini-api/docs/image-generation) and the [Live\nAPI](/gemini-api/docs/live). Google AI Studio supports building **web apps**\nwith full-stack runtimes and **native Android apps** with Kotlin and Jetpack\nCompose — all through natural language prompting. Get started Start vibe coding in Google AI Studio's [Build mode](https://aistudio.google.com/apps). You can\nstart building in a few ways: **Start with a prompt**: In Build mode, use the input box to enter a\ndescription of what you want to build. Select AI Chips to add specific\nfeatures like image generation or Google Maps data to your prompt. You can\neven say what you want using the speech-to-text button. **\"I'm Feeling Lucky\" button**: If you need a creative spark, use the \"I'm\nFeeling Lucky\" button, and Gemini will generate a prompt with a project idea\nto get you started. **Remix a project from the gallery**: Open a project from the [App\nGallery](https://aistudio.google.com/apps?source=showcase) and select **Copy App**. **Import a project from GitHub**: In Build mode, select\n**Import from GitHub** from the **Add files** (+ icon) menu in the prompt\ninput box to import your existing code. Once you run the prompt, you'll see the necessary code and files get generated,\nwith a live preview of your app appearing on the right-hand side. What is created? When you run your prompt, AI Studio creates a complete application. You can\nchoose to build a **web app** or a **native Android app** using the platform\npicker. For **web apps** (default), AI Studio creates a full-stack environment that\nincludes: **Client-side**: A web frontend (React is the default). **Server-side**: A Node.js runtime that allows for secure API calls,\ndatabase connections, and npm package usage. For **Android apps**, AI Studio generates a Kotlin and Jetpack Compose project\nthat you can preview in a browser-based emulator, install on a physical device,\nand publish to the Play Store for testing. [Learn more about building Android\napps](/gemini-api/docs/aistudio-android). You can view the code that gets generated by selecting the **Code** tab in the\nright-hand preview pane. The **Antigravity Agent** intelligently manages\nmultiple files across your stack, ensuring that changes are propagated\ncorrectly. The Antigravity Agent The **Antigravity Agent** is the main AI functionality within [Google\nAntigravity](https://antigravity.google) and now the core components of the\nagent harness is powering the Build mode experience in Google AI Studio. It goes\nbeyond simple code generation by maintaining context of your entire project,\nmanaging multiple files, and understanding complex instructions to build robust,\nfull-stack applications. Key capabilities include: **Context awareness**: Maintains context of previous prompts and file states. **Multi-file management**: Handles dependencies across multiple files. **Verified execution**: Verifies code updates to reduce hallucinations. Full-stack capabilities Google AI Studio unlocks the power of the modern web ecosystem, allowing you to\nbuild more than just client-side prototypes. **Server-side runtime & npm**: Use the vast library of npm packages. The\nagent will automatically identify and install packages as needed for your\napp (e.g., specific libraries for data visualization or API clients). You\ncan also request specific packages if desired. **Secrets management**: Securely store API keys and secrets in the\n**Settings** menu. These are accessible in your server-side code, keeping\nthem safe from client-side exposure. **Multiplayer**: Build real-time collaborative experiences directly within\nAI Studio. The server-side runtime manages the state and connections\nrequired for users to interact together. **Firebase Firestore and Authentication**: Automatically provision and set\nup Firebase, including Firestore database (persistent data storage) and\nFirebase Authentication (sign-in flows, specifically \"Sign in with\nGoogle\"). The agent handles the entire setup process and even writes the\ncode in your app for these services. **Google Workspace integrations**: Connect your app to Google Workspace\nAPIs like Gmail, Sheets, Docs, Drive, Calendar, and more. AI Studio handles\nall the OAuth configuration automatically. [Learn more about developing full-stack apps](/gemini-api/docs/aistudio-fullstack) Android apps You can also build native Android apps using Kotlin and Jetpack Compose.\nPreview your app in a browser-based Android emulator, install it on a physical\ndevice using ADB in the browser, and publish to the Play Store for internal\ntesting. [Learn more about building Android apps](/gemini-api/docs/aistudio-android) Continue building Once Google AI Studio generates the initial code for your application, you\ncan continue refining it: Build in Google AI Studio **Iterate with Gemini**: Use the chat panel in **Build mode** to ask Gemini\nto make modifications, add new features, or change the styling. **Edit the code directly**: Open the **Code tab** in the preview panel to\nmake live edits. Develop externally For more advanced workflows, you can sync or export the code to work in your\npreferred environment: **Sync with GitHub**: Connect your app to a GitHub repository to enable\ntwo-way sync. You can push changes prompted in AI Studio directly to your\nrepository with AI-generated commit messages, or pull changes made locally\nin your IDE or by teammates back into AI Studio. Manage your sync status\nanytime in the **GitHub** tab in Settings. **Download and develop locally**: Export the generated code as a **ZIP\nfile** and import it into your code editor. Key features Google AI Studio includes several features to make the building process\nintuitive and visual: **Create and iterate on full stack apps**: Create full stack apps with just\na prompt and iterate through chat or **annotation mode**. Annotation mode\nlets you highlight any part of your app's UI and describe the\nchange you want. **Share and deploy your app**: You can share your creations with others to\ncollaborate or showcase your work. When sharing, API calls count toward your\nusage limits. If you use paid models, costs may apply. Then when your app is\nready, deploy to Cloud Run. **App gallery**: The App Gallery provides a visual library of project ideas.\nYou can browse what's possible with Gemini, preview applications instantly,\nand remix them to make them your own. Deploy or archive your app Once your application is ready, you can deploy it: **Cloud Run**: Deploy your application as a scalable service.\nPricing for [Google Cloud Run](https://cloud.google.com/run) may apply based\non usage. To learn more about deployment, see\n[Deploying from Google AI Studio](/gemini-api/docs/aistudio-deploying). **GitHub**: Sync your project with a new or existing GitHub repository\nto manage source code or collaborate with teammates. Limitations This section lists current limitations of build mode in Google AI Studio. API Key management When you create a new app that uses the Gemini API, AI Studio automatically\nconfigures your Gemini API key as a secret in the app's server-side environment.\nYou can view and manage this key in the **Secrets** panel. **Automatic setup**: Your `GEMINI_API_KEY` is set up for you — no manual\nconfiguration is required to start building. **Server-side only**: API keys are injected into the server-side runtime and\nare never included in client-side code. **Existing apps**: For apps built before May 14, 2026, the agent will\nautomatically upgrade your Gemini API integration to the recommended\nserver-side approach the next time you modify the app's Gemini features. Deployment outside Google AI Studio **Cloud Run**: When you deploy to Cloud Run from AI Studio, your API key is\nincluded securely in the server-side environment. The deployed app will use\nyour API key for all users' Gemini API calls. **ZIP download**: If you download your app as a ZIP file to run it\nelsewhere, you will need to set up the `GEMINI_API_KEY` environment variable\nin your hosting environment. Since your app's Gemini API calls are made from\nserver-side code, the key is not exposed to end users. Error when sharing apps If you share your app and your end user runs into a **403 Access Restricted**\nerror when using the shared URL, it may be due to one of the following: **Browser extensions**: Privacy extensions like Privacy Badger may be blocking the app. Disable the extension to avoid the error. **Build issues**: There may be issues with the current code. Prompt the\nagent to \"fix any build issues with the current code\" and then reshare the\nURL. FAQ What is Build in AI Studio? AI Studio Build is a platform designed to take you from a simple prompt to a\nproduction-ready, AI-powered application using Gemini. Describe what you\nwant to build with a prompt, and Gemini will generate an app for you. You\ncan also explore our gallery to see what's possible with the Gemini API,\nand remix apps to make them your own. How does Build handle my Gemini API key? When you create an app that uses the Gemini API, AI Studio automatically\nsets up your Gemini API key as a server-side secret. Your app's Gemini API\ncalls are made from server-side code using this key, so it is never exposed\nin the browser. You can view your API key in the **Secrets** panel in\nSettings. Is my API key exposed when sharing apps? No. Your API key is stored as a server-side secret and is never included in\nclient-side code. When you share your app, other users can use it, but they\ncannot see your API key. When sharing your apps with others, API calls count toward your usage limits.\nIf you use paid models, costs may apply. AI Studio will give you a heads-up\nduring setup and before you share if your app could incur costs. Who can see my apps? By default your app is private. You can share your app with other users to\nlet them use it. Users you share your app with can see its code and fork it\nfor their own purposes. If you share your app with edit permission, the\nother users can edit the code of your app. Can I run apps outside of AI Studio? Yes. You can deploy your app to\n[Cloud Run](https://cloud.google.com/run) from AI Studio, which\ngives your app a public URL with your API key securely configured in the\nserver-side environment. You can also download your app as a ZIP file and\nhost it elsewhere — you'll need to set the `GEMINI_API_KEY` environment\nvariable in your hosting environment. Since Gemini API calls are made from\nserver-side code, your key stays secure. To learn more about deployment options, see [Deploying from Google AI Studio](/gemini-api/docs/aistudio-deploying). Can I develop apps locally with my own tools and then share them here? Yes. You can connect your AI Studio app to a GitHub repository to develop\nlocally using your preferred code editor or CLI tools, push your changes to\nGitHub, and then pull those updates directly back into AI Studio using the\n**GitHub** tab in Settings. How can I use a database or other storage with my apps? AI Studio apps are standard apps running in a Cloud Run container. You can\nuse any storage solution that you can connect to over a network, so long\nas there is not a firewall preventing access from a dynamic IP range. We are working on adding direct support for storage in the future, which\nyou will be able to configure directly within AI Studio. How can I access the microphone, webcam, and other Navigator APIs? To ensure that viewers are aware of an app’s usage of their webcam or other\ndevices, we require an extra acknowledgement before the app can access\nthese [Navigator APIs](https://developer.mozilla.org/en-US/docs/Web/API/Navigator).\nApp creators can add these permission requests to their app’s\n`metadata.json` file. For example: `{ \"name\": \"My app\", \"requestFramePermissions\": [ \"microphone\", \"camera\", \"display-capture\", \"geolocation\", \"bluetooth\", \"clipboard-read\", \"serial\", \"usb\" ] }` Supported values for `requestFramePermissions` are a subset of the\nstandard [policy-controlled features](https://github.com/w3c/webappsec-permissions-policy/blob/main/features.md). How can I use GitHub with my apps? AI Studio supports two-way sync with GitHub: **Import a repository**: In Build mode, select **Import from GitHub**\nfrom the **Add files** (+ icon) menu in the prompt input box to import\nexisting code. **Link a repository**: In Settings, open the **GitHub** tab to create a\nnew GitHub repository from your app or link to an existing one. **Two-way sync**: Push changes prompted in AI Studio directly to your\nrepository with AI-generated commit messages, or pull changes made\nexternally (such as local IDE edits or teammate pull requests) back into AI\nStudio. **Resolve merge conflicts**: If changes conflict when syncing with\nGitHub, AI Studio provides a **Resolve conflicts** dialog with a\nside-by-side diff viewer, allowing you to review differences and choose\nwhether to keep the AI Studio or GitHub version for each conflicted file. Can I give other users edit access to my app? AI Studio doesn't support direct real-time collaborative editing.\nHowever, you can collaborate with teammates by linking your app to a shared\nGitHub repository. Teammates can push changes or open pull requests on GitHub,\nand you can pull those updates into AI Studio. Why was my app flagged for policy violation? We have systems that automatically review apps to ensure they comply with\nour policies. If we find that an app violates our policies, the app will\nbe removed from AI Studio. Policy violations can include, but are not\nlimited to, the following: Apps that contain malware, phishing, or impersonation Apps that display or distribute content that violates child sexual abuse imagery policy Apps that display or distribute content that violates harassment policy Apps that display or distribute content that violates hate speech policy Apps that display or distribute content that violates human trafficking policy Apps that display or distribute content that violates sexually explicit content policy Apps that display or distribute content that violates violence and gore policy Apps that display or distribute content that violates harmful or dangerous policy If your app has been flagged for a policy violation, and you believe it in\nerror, you can submit an appeal. Repeated violations of our policies may\nresult in the termination of your access to AI Studio. What are my responsibilities as an app developer? As a reminder, as the owner of your application, you are responsible for\nits behavior and all data it handles. This includes: **Legal Compliance and Third Party Rights:** Ensuring your app complies\nwith all applicable laws and regulations and does not violate the rights\nof others, including intellectual property and privacy rights. **Content Monitoring:** Compliance with additional terms may apply to\nother services used by your app. For example,\n[Google Cloud Terms of Service](https://cloud.google.com/terms),\napplicable to Firestore, require customers hosting third-party content to\npublish policies defining what content is prohibited (e.g., illegal\ncontent) and monitor for presence of that illegal content. **Safe Implementation:** Implementing the necessary safeguards and\nmoderation tools to prevent your application from being misused. Be aware of the [use restrictions](https://ai.google.dev/gemini-api/terms#use-restrictions)\nin the Terms of Service. What terms apply to apps in the app gallery in AI Studio? The [Gemini API Additional Terms of Service](https://ai.google.dev/gemini-api/terms)\napply to use of apps featured in the app gallery in AI Studio, unless\notherwise noted. What's next [Developing Full-Stack Apps](/gemini-api/docs/aistudio-fullstack) (web) [Build Android Apps](/gemini-api/docs/aistudio-android) See examples in the [App Gallery](https://aistudio.google.com/apps?source=showcase). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-08-20 UTC.", "znaku_textu": 16250, "slov": 2629, "odkazu": 137, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:18", "sha256": "71bee793a99f7f56dcc8ba54cf05e028f28e1ddb1ba1707c6c12cbbc5ea5fe19", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/apps", "https://aistudio.google.com/apps?source=showcase", "https://antigravity.google/", "https://cloud.google.com/run", "https://developer.mozilla.org/en-US/docs/Web/API/Navigator", "https://github.com/w3c/webappsec-permissions-policy/blob/main/features.md", "https://cloud.google.com/terms", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/aistudio-deploying", "titulek": "Deploying from Google AI Studio | Gemini API | Google AI for Developers", "h1": "Deploying from Google AI Studio", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/aistudio-deploying", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Deploying from Google AI Studio  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/aistudio-deploying", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Deploying from Google AI Studio"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Deploying from Google AI Studio", "item": "https://ai.google.dev/gemini-api/docs/aistudio-deploying"}]}], "drobecky": ["Gemini API", "Deploying from Google AI Studio"], "osnova": [{"uroven": 1, "text": "Deploying from Google AI Studio"}, {"uroven": 2, "text": "Deployment options"}, {"uroven": 2, "text": "About the Starter Tier"}, {"uroven": 2, "text": "Starter Tier deployment steps"}, {"uroven": 2, "text": "Custom URLs for AI Studio"}, {"uroven": 3, "text": "Set a custom URL"}, {"uroven": 3, "text": "Report trademark or copyright issues"}, {"uroven": 2, "text": "Standard deployment"}, {"uroven": 2, "text": "Delete your application"}, {"uroven": 2, "text": "What's next"}], "markdown": "Deploying from Google AI Studio Google AI Studio lets you to deploy your full-stack applications directly\nfrom Build Mode. This provides a fast path from prototype to a\nmanaged, scalable production environment. Deployment options To deploy your application from AI Studio Build Mode, the requirements depend\non the tier you use: [**Google Cloud Starter Tier**](https://docs.cloud.google.com/docs/starter-tier):\nLets you publish up to 2 full-stack applications without setting up a\nGoogle Cloud project or billing account. **Standard Deployment**: Requires a Google Cloud project linked to your\nAI Studio account and billing enabled on that project. About the Starter Tier The Google Cloud Starter Tier provides a streamlined path to deploy\napplications to Google Cloud directly from Google AI Studio without setting\nup a full Google Cloud environment or billing account. Each Google AI Studio deployment creates a corresponding service in\nCloud Run. For services deployed in Google AI Studio with Starter\nTier, the following limitations apply: You can deploy up to two services. Your services are deployed in a\n[single Cloud Run region](https://docs.cloud.google.com/run/docs/locations). Starter Tier deployment steps After designing your app in Build mode, deploy it with Starter Tier: Click the **Publish** button in the top right corner. Click **Get Started**. Click **Publish App**. Once deployment is complete, AI Studio provides a Cloud Run URL where you can\naccess your live application. Custom URLs for AI Studio When publishing an application from Google AI Studio, you can set a custom,\nmemorable subdomain under `ai.studio` (for example,\n`https://your-app-name.ai.studio`). Google AI Studio requires subdomains to be globally unique across all projects,\nand assigns them on a first-come, first-served basis. If another project\nalready uses a name, AI Studio prompts you to choose a different one. If you\nunpublish or delete an application, its custom URL is released and becomes\navailable for other users to claim. Set a custom URL To set or update a custom URL for your application: Open your application in Google AI Studio in **Build** mode. Click **Publish** in the top right corner. In the deployment configuration, enter your preferred subdomain in the\n**Custom URL** field or accept the suggested URL. Click **Publish App**. To transfer an existing custom URL to a different application, you must first\nunpublish or delete the application which is assigned that custom URL, and then\npublish your new application using the chosen subdomain. Report trademark or copyright issues Custom subdomains must comply with the\n[Google Terms of Service](https://policies.google.com/terms). If you notice a\ncustom URL that infringes on a trademark or uses a copyrighted name without\npermission, you can report it using the\n[Google Legal Troubleshooter](https://support.google.com/legal/troubleshooter/1114905). Standard deployment As your applications evolve, you might require capabilities beyond the Starter\nTier, such as higher quotas or increased compute resources or other\nGoogle Cloud products not available in the Starter Tier. To unlock\nthese capabilities, you can convert your fully managed Starter Tier project into\na standard Google Cloud project. This ensures that you can scale seamlessly without losing\nyour progress. Follow the steps to\n[create a Cloud Billing account](https://docs.cloud.google.com/billing/docs/how-to/create-billing-account#create-new-billing-account),\nformally accept the standard Google Cloud Terms of Service, and\n[upgrade to a standard Google Cloud project](https://docs.cloud.google.com/docs/starter-tier#upgradee).\nFor more information, see\n[Setup for Paid accounts](https://docs.cloud.google.com/billing/docs/in-product-billing-setup#paid-setup). To learn more about billing tiers, see [Billing](/gemini-api/docs/billing). Delete your application If you no longer need your app, you can delete it in Google AI Studio\nby following these instructions: In Google AI Studio, go to your\n[Apps page](https://aistudio.google.com/app/apps). In the left menu, select **Apps**. Hold the pointer over the app you want to delete. Click the trash can icon on the right-side of the row to delete the app. What's next Learn more about the\n[Google Cloud Starter Tier](https://docs.cloud.google.com/docs/starter-tier). Read about [Billing](/gemini-api/docs/billing) in Gemini API. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-07-10 UTC.", "znaku_textu": 4840, "slov": 698, "odkazu": 135, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:21", "sha256": "a1155c6a9a576359a725d40650077159bfa9cb60ccbb3d491c5f7a593658719d", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://docs.cloud.google.com/docs/starter-tier", "https://docs.cloud.google.com/run/docs/locations", "https://policies.google.com/terms", "https://support.google.com/legal/troubleshooter/1114905", "https://docs.cloud.google.com/billing/docs/how-to/create-billing-account", "https://docs.cloud.google.com/billing/docs/in-product-billing-setup", "https://aistudio.google.com/app/apps", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/aistudio-fullstack", "titulek": "Develop full-stack apps in Google AI Studio | Gemini API | Google AI for Developers", "h1": "Develop full-stack apps in Google AI Studio", "popis": "Learn how to develop full-stack applications with server-side logic in Google AI Studio.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/aistudio-fullstack", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Develop full-stack apps in Google AI Studio  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to develop full-stack applications with server-side logic in Google AI Studio.", "og:url": "https://ai.google.dev/gemini-api/docs/aistudio-fullstack", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Develop full-stack apps in Google AI Studio"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Develop full-stack apps in Google AI Studio", "item": "https://ai.google.dev/gemini-api/docs/aistudio-fullstack"}]}], "drobecky": ["Gemini API", "Develop full-stack apps in Google AI Studio"], "osnova": [{"uroven": 1, "text": "Develop full-stack apps in Google AI Studio"}, {"uroven": 2, "text": "Server-side runtime"}, {"uroven": 3, "text": "Use npm packages"}, {"uroven": 2, "text": "Manage secrets securely"}, {"uroven": 3, "text": "Gemini API key"}, {"uroven": 3, "text": "Third-party API keys"}, {"uroven": 3, "text": "Firebase integration for database & authentication"}, {"uroven": 2, "text": "Google Workspace APIs"}, {"uroven": 3, "text": "How it works"}, {"uroven": 3, "text": "Supported apps"}, {"uroven": 3, "text": "Authentication and permissions"}, {"uroven": 3, "text": "Example prompts"}, {"uroven": 3, "text": "Set up OAuth"}, {"uroven": 2, "text": "Build multiplayer experiences"}, {"uroven": 3, "text": "Tips for testing multiplayer apps"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "What's Next?"}], "markdown": "Develop full-stack apps in Google AI Studio Google AI Studio now supports full-stack development, enabling you to build\napplications that go beyond client-side prototypes. With a\nserver-side runtime, you can manage secrets, connect to external APIs, and build\nreal-time multiplayer experiences. Server-side runtime Google AI Studio applications can now include a server-side component (Node.js).\nThis lets you: **Execute server-side logic**: Run code that shouldn't be exposed to the\nclient. **Access npm packages**: The [Antigravity Agent](https://antigravity.google/docs/agent)\ncan install and use packages from the vast npm ecosystem. **Handle secrets**: Securely use API keys and credentials. Use npm packages You don't need to manually run `npm install`. Simply ask the Agent to add\nfunctionality that requires a package, and it will handle the installation and\nimport. **Example**: > \"Use `axios` to fetch data from the external API.\" Manage secrets securely With server-side code and secrets management, you can now build apps that\ninteract with the world. Gemini API key When you create a new app that uses the Gemini API, AI Studio automatically\nconfigures your `GEMINI_API_KEY` as a server-side secret — no manual setup\nrequired. You can view this key in the **Secrets** panel in Settings. Your\napp's Gemini API calls are made from server-side code using this key, so\nit is never exposed in the browser. Third-party API keys For other services, you can add API keys manually: **Third-party APIs**: Connect to services like Stripe, SendGrid, or custom\nREST APIs. **Databases**: Connect to external databases (e.g., via Supabase, Firebase,\nor MongoDB Atlas) to persist data beyond the session. When building real-world apps, you often need to connect to third-party services\n(like Twilio, Slack, or databases) that require API keys. You can add keys\nmanually with the following steps: **Add a secret**: Go to the **Settings** menu in Google AI Studio and look\nfor the Secrets section. **Store your key**: Add your API keys or secret tokens here. **Access in code**: The Agent can write server-side code that accesses these\nsecrets securely (typically via environment variables), ensuring they are\nnever exposed to the client-side browser. When needed, the agent will\nalso show a card in the chat prompting you to add keys whenever a new secret is\nneeded or when a key new key is detected in the project's env variables. Firebase integration for database & authentication Google AI Studio now makes it easy to add a database or authentication to your\napp through a\n[Firebase integration](https://firebase.google.com/docs/ai-assistance/ai-studio-integration).\nThe Antigravity Agent can provision and set up the following services for you\nautomatically: **Firestore database**: a flexible, scalable NoSQL cloud database to store\nand sync data for client- and server-side development. **Firebase Authentication**: allow your users to securely sign in to your\napplication using \"Sign in with Google\" flows. Simply ask the agent to \"add a database to my app\" or \"set up Google Sign-in\",\nand it will handle the necessary configuration and code generation for you. Firebase lets you start for free, and optionally scale with a paid account\nwhenever you're ready for more quota or to use paid features. Google Workspace APIs Google AI Studio lets you build apps that connect to Google Workspace APIs, so\nyour users can work with their real data: emails, spreadsheets, documents,\ncalendar events, and more, all within your app. You no longer need to set up a Google Cloud project, configure OAuth, or manage your API manually. How it works You can add a Workspace integration in two ways: **Describe it in the chat panel**: Just tell the agent what you want in the chat panel at the bottom. For example, *\"Build an expense tracker that logs receipts to my Google Sheet\"* or *\"Create a dashboard that summarizes my unread Gmail messages.\"* **Select from the integrations panel**: Open the **Integrations** panel in the right-hand sidebar of Build mode and enable the Workspace app you want to connect. When you add a Workspace app, AI Studio automatically: Wires up the necessary Google API for your app. Generates the server-side code to call the API. Adds a secure \"Sign in with Google\" flow so end users of your app can\nauthorize access to their own data. Supported apps The following Google Workspace apps are available: App What you can build Google Calendar Read, create, and manage events and calendars Google Chat Read and interact with conversations and group spaces Google Docs Create, read, update, and format documents Google Drive Organize, search, and manage files and folders Google Forms Create surveys, update questions, and retrieve responses Gmail Read, send, and manage email content Google Keep Manage notes, lists, and attachments Google Meet Schedule and manage video calls Contacts Sync and manage contacts Google Sheets Read, write, and format spreadsheet data Google Slides Create and modify presentations Google Tasks Create, manage, and organize tasks Authentication and permissions As the builder, you don't need to configure OAuth clients, manage credentials,\nor set up a Google Cloud project. AI Studio handles all of this for you. Apps with Workspace APIs integrated use \"Sign in with Google\" to authenticate\nend users. When a user opens your app, they are prompted to sign in and grant\nthe specific permissions your app needs (for example, read-only access to their\ncalendar, or the ability to edit a spreadsheet). Your app only accesses the\ndata of the person using it. Each user authorizes access to their own account. Example prompts Here are a few ideas to get started with Workspace integrations: *\"Build an app that reads my Google Calendar and drafts prep emails in\nGmail for each meeting.\"* *\"Create a tool that takes a Google Doc and generates a 5-slide summary\npresentation in Google Slides.\"* *\"Make an expense tracker where I upload a receipt, Gemini extracts the\ndetails, and it logs a new row in my Google Sheet.\"* Set up OAuth One key use case for secrets management is to set up OAuth to connect to other\nwebsites or apps. When your prompt includes instructions about connecting to a\n3rd party app that requires OAuth authentication, the agent will provide\ninstructions on how to set up OAuth for that application. These instructions\nwill include the necessary callback URLs to configure your OAuth Application.\nYou can also find the callback URLs under **Integrations** in the Settings panel. Build multiplayer experiences The full-stack runtime enables real-time collaboration features. **Real-time state**: You can ask the Agent to build features like \"a live\nchat,\" \"a collaborative whiteboard,\" or \"a multiplayer game.\" **Synced sessions**: The server manages the state, allowing multiple users\nto interact with the same application instance in real-time. **Example prompt**: > \"Make this a multiplayer game where players can see each\nother's cursors.\" Tips for testing multiplayer apps You can test multiplayer mode in two ways before deploying your app. Open your app in Google AI Studio Build mode in multiple tabs. When\ndeveloping in Build mode, your app is in a dev container. Opening the\napp in multiple tabs will let you simulate multiple players using your app. Share the app with others using the **Share** menu at the top right.\nthen use the **Shared URL** from the **Integrations**\ntab of the **Share** menu to use the app with the players that you've shared\nyour app with. Best practices **Gemini API calls**: Your `GEMINI_API_KEY` is automatically configured as a\nserver-side secret. Make Gemini API calls from your server-side code using\nthis key. You can view it in the **Secrets** panel. **Secrets security**: Always use the Secrets manager for sensitive keys.\nNever hardcode them in your files. **Separation of concerns**: Keep your UI logic in the client-side framework\n(React/Angular) and your business logic/data handling on the server side. **Error handling**: Ensure your server-side code robustly handles errors\nfrom external API calls to prevent the app from crashing. What's Next? [Build Apps in Google AI Studio](/gemini-api/docs/aistudio-build-mode) [Deploying from Google AI Studio](/gemini-api/docs/aistudio-deploying) [App Gallery](https://aistudio.google.com/apps?source=showcase) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-08-18 UTC.", "znaku_textu": 8712, "slov": 1414, "odkazu": 130, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:50", "sha256": "12025d4094e7840be5d2c742d05f91c24f4bd5c989a52b73d926786cb11fc9e1", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://antigravity.google/docs/agent", "https://firebase.google.com/docs/ai-assistance/ai-studio-integration", "https://aistudio.google.com/apps?source=showcase", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/antigravity-agent", "titulek": "Antigravity agent | Gemini API | Google AI for Developers", "h1": "Antigravity agent", "popis": "Use the Antigravity managed agent to perform multi-step tasks that require reasoning, file operations, and tool use.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/antigravity-agent", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Antigravity agent  |  Gemini API  |  Google AI for Developers", "og:description": "Use the Antigravity managed agent to perform multi-step tasks that require reasoning, file operations, and tool use.", "og:url": "https://ai.google.dev/gemini-api/docs/antigravity-agent", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Antigravity agent"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Antigravity agent", "item": "https://ai.google.dev/gemini-api/docs/antigravity-agent"}]}], "drobecky": ["Gemini API", "Antigravity agent"], "osnova": [{"uroven": 1, "text": "Antigravity agent"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Capabilities"}, {"uroven": 2, "text": "Supported tools"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multimodal Input"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "MCP servers"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Model selection"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Customizing the agent"}, {"uroven": 2, "text": "Background execution"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Environments"}, {"uroven": 2, "text": "Triggers"}, {"uroven": 3, "text": "Create a trigger"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "List triggers"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Get a trigger"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Pause and resume"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Delete a trigger"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Run a trigger immediately"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "List executions"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Availability and pricing"}, {"uroven": 3, "text": "Budget controls"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 4, "text": "Continuing an incomplete interaction"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Estimated costs"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Antigravity agent The Antigravity agent is a general-purpose managed agent on the Gemini API. A single API call gives you an agent that reasons, executes code, manages files, and browses the web inside your own secure Linux sandbox, hosted by Google. It is built with Gemini 3.8 Flash and uses the same harness as the Antigravity IDE. You can configure the underlying Gemini model using `agent_config`. Available through the [Interactions API](/gemini-api/docs/interactions-overview) and [Google AI Studio](https://aistudio.google.com). Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Read Hacker News, summarize the top 10 stories, and save the results as a PDF.\", environment=\"remote\", ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Read Hacker News, summarize the top 10 stories, and save the results as a PDF.\", environment: \"remote\", }, { timeout: 300000 }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Read Hacker News, summarize the top 10 stories, and save the results as a PDF.\", \"environment\": \"remote\" }'` Capabilities Each call can provision a Linux sandbox and starts a tool-use loop. The agent plans, acts, observes results, and repeats until the task is done. **Code execution:** Run Bash, Python, and Node.js commands. Install packages, run tests, build apps. **File management:** Read, write, edit, search, and list files in the sandbox. Files persist across interactions. **Web access:** Google Search and URL fetching for data. **Context compaction:** Automatic context compaction (triggered at ~135k tokens) to support long-running, multi-turn sessions without losing context or hitting token limits. See the [Quickstart](/gemini-api/docs/managed-agents-quickstart) for multi-turn usage and streaming. Supported tools By default, the agent has access to `code_execution`, `google_search`, and `url_context`. Filesystem tools are enabled automatically when you specify the `environment` parameter. You can also define **custom functions** to connect the agent to your own APIs and tools. You only need to specify the `tools` parameter when customizing or restricting the default set, or when adding custom functions. Tool Type value Description Code Execution `code_execution` Run shell commands (bash, Python, Node) with stdout/stderr capture. Google Search `google_search` Search the public web. URL Context `url_context` Fetch and read web pages. Filesystem *(enabled via `environment`)* Read, write, edit, search, and list files in the sandbox. The system enables these tools automatically when you set the `environment`. Custom Functions `function` Define custom functions that the agent can request to execute. See Function calling. Remote MCP Server `mcp_server` Register external Model Context Protocol (MCP) servers as tools. See MCP servers. You can intercept and validate `code_execution` and `filesystem` tool execution right inside the remote sandbox using synchronous [Hooks](/gemini-api/docs/agent-hooks). To limit the agent to specific tools, pass only the ones you need: Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Search for the latest AI research papers on reasoning and summarize them.\", environment=\"remote\", tools=[ {\"type\": \"google_search\"}, {\"type\": \"url_context\"}, ], ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Search for the latest AI research papers on reasoning and summarize them.\", environment: \"remote\", tools: [ { type: \"google_search\" }, { type: \"url_context\" }, ], }, { timeout: 300000 }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Search for the latest AI research papers on reasoning and summarize them.\", \"environment\": \"remote\", \"tools\": [ {\"type\": \"google_search\"}, {\"type\": \"url_context\"} ] }'` Multimodal Input The Antigravity agent supports multimodal inputs. Currently, only `text` and `image` inputs are supported. Images must be supplied as inline base64-encoded strings (`data`). Python`import base64 from google import genai client = genai.Client() with open(\"path/to/chart.png\", \"rb\") as f: image_bytes = f.read() interaction_inline = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=[ {\"type\": \"text\", \"text\": \"Analyze this chart and summarize the trends.\"}, { \"type\": \"image\", \"data\": base64.b64encode(image_bytes).decode(\"utf-8\"), \"mime_type\": \"image/png\", }, ], environment=\"remote\", )` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const client = new GoogleGenAI({}); const base64Image = fs.readFileSync(\"path/to/chart.png\", { encoding: \"base64\" }); const interactionInline = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: [ { type: \"text\", text: \"Analyze this chart and summarize the trends.\" }, { type: \"image\", data: base64Image, mime_type: \"image/png\", }, ], environment: \"remote\", }, { timeout: 300000 });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`BASE64_IMAGE=$(base64 -w0 /path/to/chart.png)\n\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d \"{ \\\"agent\\\": \\\"antigravity-preview-05-2026\\\", \\\"input\\\": [ {\\\"type\\\": \\\"text\\\", \\\"text\\\": \\\"Analyze this chart and summarize the trends.\\\"}, { \\\"type\\\": \\\"image\\\", \\\"mime_type\\\": \\\"image/png\\\", \\\"data\\\": \\\"$BASE64_IMAGE\\\" } ], \\\"environment\\\": \\\"remote\\\" }\"` Function calling Function calling allows you to connect the Antigravity agent to external APIs and databases by defining custom tools the agent can invoke. For general concepts, see [Function calling with the Gemini API](/gemini-api/docs/interactions/function-calling). The following example demonstrates a 2-turn interaction. The agent first requests a custom `get_weather` function call, and the client executes it and returns the result in the second turn. Python`from google import genai client = genai.Client() # 1. Define the custom function get_weather_tool = { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the current weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": { \"type\": \"string\", \"description\": \"The city and country, e.g. San Francisco, USA\", } }, \"required\": [\"location\"], }, } # 2. Call the agent with the custom tool (Turn 1) interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"What is the weather in Tokyo?\", environment=\"remote\", tools=[ {\"type\": \"code_execution\"}, # Enable default code execution get_weather_tool, # Add custom function ], ) # Check if the agent requested a function call if interaction.status == \"requires_action\": # Find function calls that do not have a matching function result. # Filesystem tools (like write_file) are also represented as function calls # but are executed automatically by the environment. executed_calls = {step.call_id for step in interaction.steps if step.type == \"function_result\"} pending_calls = [step for step in interaction.steps if step.type == \"function_call\" and step.id not in executed_calls] if pending_calls: fc_step = pending_calls[0] print(f\"Function to call: {fc_step.name} (ID: {fc_step.id})\") print(f\"Arguments: {fc_step.arguments}\") # 3. Execute the function locally (simulated get_weather()) and send the result back (Turn 2) function_result = { \"temperature\": 23, \"unit\": \"celsius\" } final_interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", previous_interaction_id=interaction.id, # Reference the interaction ID environment=interaction.environment_id, input=[ { \"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": function_result, } ], ) print(final_interaction.output_text) # Output: The current weather in Tokyo, Japan is 23°C (Celsius). else: print(\"No pending function calls.\") else: print(f\"Interaction completed with status: {interaction.status}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); // 1. Define the custom function const get_weather_tool = { type: \"function\", name: \"get_weather\", description: \"Gets the current weather for a given location.\", parameters: { type: \"object\", properties: { location: { type: \"string\", description: \"The city and country, e.g. San Francisco, USA\", }, }, required: [\"location\"], }, }; // 2. Call the agent with the custom tool (Turn 1) const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"What is the weather in Tokyo?\", environment: \"remote\", tools: [ { type: \"code_execution\" }, get_weather_tool, ], }, { timeout: 300000 }); if (interaction.status === \"requires_action\") { // Find function calls that do not have a matching function result. // Filesystem tools (like write_file) are also represented as function calls // but are executed automatically by the environment. const executedCalls = new Set( interaction.steps .filter(s => s.type === \"function_result\") .map(s => s.call_id) ); const pendingCalls = interaction.steps.filter( s => s.type === \"function_call\" && !executedCalls.has(s.id) ); if (pendingCalls.length > 0) { const fcStep = pendingCalls[0]; console.log(`Function to call: ${fcStep.name} (ID: ${fcStep.id})`); // 3. Execute the function locally (simulated get_weather()) and send the result back (Turn 2) const functionResult = { temperature: 23, unit: \"celsius\" }; const finalInteraction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", previous_interaction_id: interaction.id, // Reference the interaction ID environment: interaction.environment_id, input: [ { type: \"function_result\", name: fcStep.name, call_id: fcStep.id, result: functionResult, } ], }, { timeout: 300000 }); console.log(finalInteraction.output_text); } else { console.log(\"No pending function calls.\"); } } else { console.log(`Interaction completed with status: ${interaction.status}`); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# 1. Turn 1: Request function call RESPONSE=$(curl -s -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"What is the weather in Tokyo?\", \"environment\": \"remote\", \"tools\": [ {\"type\": \"code_execution\"}, { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the current weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\"} }, \"required\": [\"location\"] } } ] }') # Extract interaction ID, environment ID, and call ID (requires jq) INTERACTION_ID=$(echo $RESPONSE | jq -r '.id') ENVIRONMENT_ID=$(echo $RESPONSE | jq -r '.environment_id') CALL_ID=$(echo $RESPONSE | jq -r '.steps[] | select(.type==\"function_call\") | .id') # 2. Turn 2: Send function result back using variables\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d \"{ \\\"agent\\\": \\\"antigravity-preview-05-2026\\\", \\\"previous_interaction_id\\\": \\\"$INTERACTION_ID\\\", \\\"environment\\\": \\\"$ENVIRONMENT_ID\\\", \\\"input\\\": [ { \\\"type\\\": \\\"function_result\\\", \\\"name\\\": \\\"get_weather\\\", \\\"call_id\\\": \\\"$CALL_ID\\\", \\\"result\\\": { \\\"temperature\\\": 23, \\\"unit\\\": \\\"celsius\\\" } } ] }\"` MCP servers You can connect the Antigravity agent to external tools by registering remote Model Context Protocol (MCP) servers. The agent supports remote MCP servers over streamable HTTP. When registering an MCP server, you must specify the following fields in the `tools` array: Field Type Required Description `type` string Yes Must be `\"mcp_server\"`. `name` string Yes A unique identifier for the server. Must be strictly lowercase and alphanumeric (matching `^[a-z0-9_-]+$`). `url` string Yes The endpoint URL of the remote MCP server. `headers` object No Custom headers (e.g., authentication) sent with requests. `allowed_tools` array No List of tool names allowed to be executed. If omitted, all tools are allowed. Python`from google import genai client = genai.Client() # Register a remote HTTP MCP server interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"What is the weather in Tokyo?\", environment=\"remote\", tools=[{ \"type\": \"mcp_server\", \"name\": \"weather\", # Must be lowercase \"url\": \"https://gemini-api-demos.uc.r.appspot.com/mcp\" }] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"What is the weather in Tokyo?\", environment: \"remote\", tools: [{ type: \"mcp_server\", name: \"weather\", // Must be lowercase url: \"https://gemini-api-demos.uc.r.appspot.com/mcp\" }] }, { timeout: 300000 }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"What is the weather in Tokyo?\", \"environment\": \"remote\", \"tools\": [{ \"type\": \"mcp_server\", \"name\": \"weather\", \"url\": \"https://gemini-api-demos.uc.r.appspot.com/mcp\" }] }'` Model selection For `antigravity-preview-05-2026`, the default model is **Gemini 3.8 Flash** (`gemini-3.8-flash`). If you omit `agent_config`, the agent defaults to `gemini-3.8-flash`. You can configure the underlying Gemini model using `agent_config` to optimize for speed, cost, or reasoning capability. Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Summarize the key differences between functional and object-oriented programming.\", environment=\"remote\", agent_config={ \"type\": \"antigravity\", \"model\": \"gemini-3.5-flash-lite\", }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Summarize the key differences between functional and object-oriented programming.\", environment: \"remote\", agent_config: { type: \"antigravity\", model: \"gemini-3.5-flash-lite\", }, }, { timeout: 300000 }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Summarize the key differences between functional and object-oriented programming.\", \"environment\": \"remote\", \"agent_config\": { \"type\": \"antigravity\", \"model\": \"gemini-3.5-flash-lite\" } }'` The supported values for `agent_config.model` are: Model Value in `agent_config.model` Description **Gemini 3.8 Flash** (default) `gemini-3.8-flash` Default balanced model for reasoning, coding, and tool use. **Gemini 3.7 Flash** `gemini-3.7-flash` Previous generation Flash model for reasoning, coding, and agentic workflows. **Gemini 3.6 Flash** `gemini-3.6-flash` Balanced Flash model for general agentic workflows. **Gemini 3.5 Flash** `gemini-3.5-flash` Lightweight model for general workflows. **Gemini 3.5 Flash-Lite** `gemini-3.5-flash-lite` Lightweight model optimized for low latency and cost-sensitive tasks. When creating a managed agent with `agents.create`, you configure the model in the exact same way by passing `base_agent` and `agent_config`. Notice that you cannot override the model at interaction time for a managed agent created with `agents.create`. The model is locked to what was set when the agent was created. This ensures predictable tool calling behavior, consistent debugging, and adherence to security boundaries. Customizing the agent You can extend the Antigravity agent by customizing its instructions, tools, and environment. The agent supports a filesystem-native approach to customization: you can mount files like `AGENTS.md` for instructions and skills under `.agents/skills/` directly into the sandbox, or pass configuration inline at interaction time. You can iterate on your configuration inline and then save it as a managed agent when you are ready. For full details on how to build custom agents, see [Building Managed Agents](/gemini-api/docs/custom-agents). Background execution Agent tasks that involve multi-step reasoning, code execution, or file operations can take minutes to complete. Use `background=True` to run the interaction asynchronously. The API returns immediately with an interaction ID that you poll until the status is `completed` or `failed`. Python`import time from google import genai client = genai.Client() # 1. Start the interaction in the background interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Run a complex analysis on the repository.\", environment=\"remote\", background=True, ) print(f\"Interaction started in background: {interaction.id}\") # 2. Poll for completion while interaction.status == \"in_progress\": time.sleep(5) interaction = client.interactions.get(id=interaction.id) if interaction.status == \"completed\": print(interaction.output_text) else: print(f\"Finished with status: {interaction.status}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Run a complex analysis on the repository.\", environment: \"remote\", background: true, }); console.log(`Interaction started in background: ${interaction.id}`); let result = interaction; while (result.status === \"in_progress\") { await new Promise(resolve => setTimeout(resolve, 5000)); result = await client.interactions.get(interaction.id); } if (result.status === \"completed\") { console.log(result.output_text); } else { console.log(`Finished with status: ${result.status}`); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# 1. Start the interaction in the background RESPONSE=$(curl -s -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Api-Revision: 2026-05-20\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Run a complex analysis on the repository.\", \"environment\": \"remote\", \"background\": true }') INTERACTION_ID=$(echo $RESPONSE | jq -r '.id') # 2. Poll for results (repeat until status is \"completed\")\ncurl -s -X GET \"https://generativelanguage.googleapis.com/v1beta/interactions/$INTERACTION_ID\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Background execution requires `store=True`, which is the default. For real-time progress updates during background execution, see [Streaming background interactions](/gemini-api/docs/interactions/streaming#streaming-background). You can cancel a running background interaction using the `cancel` method. Python`client.interactions.cancel(id=\"INTERACTION_ID\")` JavaScript`await client.interactions.cancel(\"INTERACTION_ID\");` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID:cancel\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` **Multi-turn with background execution** When a background interaction involves stateful tools (like code execution in a sandbox), use the `environment_id` from the completed interaction to continue in the same environment. This ensures the agent picks up where it left off with all files and state intact. Python`import time from google import genai client = genai.Client() # First turn: run a task in the background interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Clone https://github.com/google/generative-ai-python and run its tests.\", environment=\"remote\", background=True, ) while interaction.status == \"in_progress\": time.sleep(5) interaction = client.interactions.get(id=interaction.id) # Second turn: continue in the same environment followup = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Fix any failing tests and re-run them.\", previous_interaction_id=interaction.id, environment=interaction.environment_id, background=True, ) while followup.status == \"in_progress\": time.sleep(5) followup = client.interactions.get(id=followup.id) print(followup.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); // First turn: run a task in the background let interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Clone https://github.com/google/generative-ai-python and run its tests.\", environment: \"remote\", background: true, }); while (interaction.status === \"in_progress\") { await new Promise(resolve => setTimeout(resolve, 5000)); interaction = await client.interactions.get(interaction.id); } // Second turn: continue in the same environment let followup = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Fix any failing tests and re-run them.\", previous_interaction_id: interaction.id, environment: interaction.environment_id, background: true, }); while (followup.status === \"in_progress\") { await new Promise(resolve => setTimeout(resolve, 5000)); followup = await client.interactions.get(followup.id); } console.log(followup.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# 1. Start first interaction in the background RESPONSE=$(curl -s -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Api-Revision: 2026-05-20\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Clone https://github.com/google/generative-ai-python and run its tests.\", \"environment\": \"remote\", \"background\": true }') INTERACTION_ID=$(echo $RESPONSE | jq -r '.id') # 2. Poll until completed (repeat until status is \"completed\") RESULT=$(curl -s -X GET \"https://generativelanguage.googleapis.com/v1beta/interactions/$INTERACTION_ID\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\") ENVIRONMENT_ID=$(echo $RESULT | jq -r '.environment_id') # 3. Continue in the same environment\ncurl -s -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Api-Revision: 2026-05-20\" \\ -d \"{ \\\"agent\\\": \\\"antigravity-preview-05-2026\\\", \\\"input\\\": \\\"Fix any failing tests and re-run them.\\\", \\\"previous_interaction_id\\\": \\\"$INTERACTION_ID\\\", \\\"environment\\\": \\\"$ENVIRONMENT_ID\\\", \\\"background\\\": true }\"` Environments Each call creates or reuses a Linux sandbox. The `environment` parameter takes three forms: Form Description `\"remote\"` Provision a fresh sandbox with default settings. `\"env_abc123\"` Reuse an existing environment by ID, preserving all files and state. `{...}` Full `EnvironmentConfig` with custom sources and network rules. See [Environments](/gemini-api/docs/agent-environment) for details on sources (Git, GCS, inline), networking, lifecycle, and resource limits. Triggers Triggers let you schedule an agent to run automatically on a cron schedule. A trigger binds an agent, environment, prompt, and schedule into a persistent resource that fires without manual intervention. Each execution reuses the same environment, so files created in one run persist and are visible to the next. Create a trigger Create a trigger by specifying a cron schedule, time zone, and the interaction configuration. The trigger starts in `active` status and will fire on the next matching cron time. Save the returned `id` to manage the trigger in subsequent calls. Python`from google import genai client = genai.Client() trigger = client.triggers.create( schedule=\"0 9 * * *\", time_zone=\"America/Argentina/Buenos_Aires\", display_name=\"issue-solver\", interaction={ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Review open PRs in my-org/my-app for new comments and address feedback. Close issues whose PRs were merged. Then check for new issues labeled 'accepted', skip any already tracked in /workspace/solved-issues/, fix the rest, and open a PR for each. Save reports to /workspace/solved-issues/.\", \"environment\": { \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\", \"transform\": { \"Authorization\": \"Bearer ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" }, }, {\"domain\": \"github.com\"}, ] }, }, }, ) print(f\"Trigger created: {trigger.id}\") print(f\"Next run: {trigger.next_run_time}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const trigger = await client.triggers.create({ schedule: \"0 9 * * *\", time_zone: \"America/Argentina/Buenos_Aires\", display_name: \"issue-solver\", interaction: { agent: \"antigravity-preview-05-2026\", input: [{ type: \"text\", text: \"Review open PRs in my-org/my-app for new comments and address feedback. Close issues whose PRs were merged. Then check for new issues labeled 'accepted', skip any already tracked in /workspace/solved-issues/, fix the rest, and open a PR for each. Save reports to /workspace/solved-issues/.\", }], environment: { type: \"remote\", network: { allowlist: [ { domain: \"api.github.com\", transform: { \"Authorization\": \"Bearer ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\", }, }, { domain: \"github.com\" }, ], }, }, }, }); console.log(`Trigger created: ${trigger.id}`); console.log(`Next run: ${trigger.next_run_time}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/triggers\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"schedule\": \"0 9 * * *\", \"time_zone\": \"America/Argentina/Buenos_Aires\", \"display_name\": \"issue-solver\", \"interaction\": { \"agent\": \"antigravity-preview-05-2026\", \"input\": [{\"type\": \"text\", \"text\": \"Review open PRs in my-org/my-app for new comments and address feedback. Close issues whose PRs were merged. Then check for new issues labeled accepted, skip any already tracked in /workspace/solved-issues/, fix the rest, and open a PR for each. Save reports to /workspace/solved-issues/.\"}], \"environment\": { \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\", \"transform\": { \"Authorization\": \"Bearer ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" } }, {\"domain\": \"github.com\"} ] } } } }'` The `CreateTrigger` request accepts the following fields: Field Type Required Description `schedule` string Yes Cron expression (e.g., `0 * * * *` for hourly, `0 9 * * 1-5` for weekday mornings). `time_zone` string Yes IANA time zone (e.g., `UTC`, `America/Argentina/Buenos_Aires`). `display_name` string No Human-readable name for the trigger. `max_consecutive_failures` integer No Max failures before the trigger is automatically paused. Default: 5. `execution_timeout_seconds` integer No Timeout per execution in seconds. Default: 600. `interaction` object Yes A `CreateInteractionRequest` defining the agent, input, tools, and environment. The response includes the following key fields: Field Type Description `id` string Unique identifier for the trigger. Use this in all subsequent operations. `status` string Current state: `active`, `paused`, or `disabled`. `next_run_time` string ISO 8601 timestamp of the next scheduled execution. `consecutive_failure_count` integer Number of consecutive failed executions since the last success. List triggers Retrieve all triggers associated with your project. Python`triggers = client.triggers.list() for trigger in triggers.triggers: print(f\"{trigger.id}: {trigger.display_name} ({trigger.status})\")` JavaScript`const triggers = await client.triggers.list(); for (const trigger of triggers.triggers) { console.log(`${trigger.id}: ${trigger.display_name} (${trigger.status})`); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1beta/triggers\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Get a trigger Fetch the full configuration and current state of a single trigger. Python`trigger = client.triggers.get(id=\"TRIGGER_ID\") print(f\"Schedule: {trigger.schedule}\") print(f\"Next run: {trigger.next_run_time}\")` JavaScript`const trigger = await client.triggers.get(\"TRIGGER_ID\"); console.log(`Schedule: ${trigger.schedule}`); console.log(`Next run: ${trigger.next_run_time}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Pause and resume You can pause a trigger to stop scheduled executions, and resume it to reactivate the schedule. Pausing does not affect manual executions. Python`# Pause client.triggers.update(id=\"TRIGGER_ID\", status=\"paused\") # Resume client.triggers.update(id=\"TRIGGER_ID\", status=\"active\")` JavaScript`// Pause await client.triggers.update(\"TRIGGER_ID\", { status: \"paused\" }); // Resume await client.triggers.update(\"TRIGGER_ID\", { status: \"active\" });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# Pause\ncurl -X PATCH \"https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{\"status\": \"paused\"}' # Resume\ncurl -X PATCH \"https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{\"status\": \"active\"}'` Delete a trigger Permanently remove a trigger. Past execution history is not deleted. Python`client.triggers.delete(id=\"TRIGGER_ID\")` JavaScript`await client.triggers.delete(\"TRIGGER_ID\");` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Run a trigger immediately Fire a trigger on demand without waiting for the next scheduled time. This works even if the trigger is paused. Python`client.triggers.run(trigger_id=\"TRIGGER_ID\")` JavaScript`await client.triggers.run(\"TRIGGER_ID\");` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID/executions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` List executions View the execution history for a trigger. Each execution includes a `status`, timestamps, an `interaction_id` you can use to fetch the full interaction output, and an `environment_id` confirming that all runs share the same sandbox. Python`executions = client.triggers.list_executions(trigger_id=\"TRIGGER_ID\") for ex in executions.trigger_executions: print(f\"{ex.id}: {ex.status} ({ex.start_time} - {ex.end_time})\") # Fetch the full interaction for an execution interaction = client.interactions.get(id=ex.interaction_id) print(interaction.output_text)` JavaScript`const executions = await client.triggers.listExecutions(\"TRIGGER_ID\"); for (const ex of executions.trigger_executions) { console.log(`${ex.id}: ${ex.status} (${ex.start_time} - ${ex.end_time})`); } // Fetch the full interaction for an execution const interaction = await client.interactions.get(ex.interaction_id); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID/executions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Availability and pricing Antigravity agent is available in preview through the\n[Interactions API](/gemini-api/docs/interactions-overview) in Google AI Studio\nand the Gemini API for both free tier and paid tier projects. Pricing follows a [pay-as-you-go model](/gemini-api/docs/pricing#pricing-for-agents)\nbased on the underlying Gemini model tokens and the tools the agent uses. Unlike a\nstandard chat request that produces a single output, an Antigravity interaction is an\nagentic workflow. A single request triggers an autonomous loop of reasoning, tool\nexecution, code running, and file management. Free tier projects include a free rate limit\nand usage quota. Antigravity interactions run multi-turn autonomous loops and can consume\nsignificant tokens. Set budget controls on your request to\nlimit token usage. You can also monitor progress in real time with\n[SSE streaming](/gemini-api/docs/streaming), or cancel running requests. Budget controls In addition to model selection, set `max_total_tokens` inside `agent_config` (with `\"type\": \"antigravity\"`) to limit\nthe total number of tokens (input + output + thinking) an interaction can consume.\nCached tokens do not count toward this limit. When the agent reaches the limit, the\ninteraction stops and returns with `status: \"incomplete\"`. The limit is best-effort:\nactual usage may slightly exceed it depending on when the agent checks the budget\nbetween steps. Set the budget on the interaction request in `agent_config` alongside `agent` and `input`. Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Analyze the dataset in /workspace/data.csv and generate a summary report.\", agent_config={ \"type\": \"antigravity\", \"max_total_tokens\": 50000 }, environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \"/workspace/data.csv\", \"content\": \"id,name,value\\n1,alpha,100\\n2,beta,200\\n\", } ], } ) print(f\"Status: {interaction.status}\") # \"incomplete\" if budget was hit print(f\"Tokens used: {interaction.usage.total_tokens}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Analyze the dataset in /workspace/data.csv and generate a summary report.\", agent_config: { type: \"antigravity\", max_total_tokens: 50000 }, environment: { type: \"remote\", sources: [ { type: \"inline\", target: \"/workspace/data.csv\", content: \"id,name,value\\n1,alpha,100\\n2,beta,200\\n\", }, ], }, }); console.log(`Status: ${interaction.status}`); console.log(`Tokens used: ${interaction.usage.total_tokens}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Analyze the dataset in /workspace/data.csv and generate a summary report.\", \"agent_config\": { \"type\": \"antigravity\", \"max_total_tokens\": 50000 }, \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \"/workspace/data.csv\", \"content\": \"id,name,value\\n1,alpha,100\\n2,beta,200\\n\" } ] } }'` Continuing an incomplete interaction When an interaction returns `status: \"incomplete\"`, the agent's work and context\nare preserved. Send a new interaction referencing the original interaction `id` and\n`environment_id` to pick up where it left off. The new interaction gets its own\n`max_total_tokens` budget. Python`# Continue from where the agent stopped continuation = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"continue\", previous_interaction_id=interaction.id, environment=interaction.environment_id, agent_config={ \"type\": \"antigravity\", \"max_total_tokens\": 50000 } ) print(f\"Status: {continuation.status}\")` JavaScript`const continuation = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"continue\", previous_interaction_id: interaction.id, environment: interaction.environment_id, agent_config: { type: \"antigravity\", max_total_tokens: 50000 } }); console.log(`Status: ${continuation.status}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"continue\", \"previous_interaction_id\": \"INTERACTION_ID\", \"environment\": \"ENVIRONMENT_ID\", \"agent_config\": { \"type\": \"antigravity\", \"max_total_tokens\": 50000 } }'` Estimated costs Costs vary based on task complexity. The agent autonomously determines how many tool calls, code executions, and file operations are needed. The following estimates are based on runs. Task category Input tokens Output tokens Typical cost **Research & information synthesis** 100k–500k 10k–40k $0.30–$1.00 **Document & content generation** 100k–500k 15k–50k $0.30–$1.30 **Process & system design** 100k–400k 10k–30k $0.25–$0.80 **Data processing & analysis** 300k–3M 30k–150k $0.70–$3.25 50–70% of input tokens are typically cached. Complex agentic workflows with many tool calls can accumulate 3–5 million tokens in a single interaction, with costs up to ~$5. **Environment compute** (CPU, memory, sandbox execution) is **not billed** during the preview period. Limitations **Preview status:** The Antigravity agent and the Interactions API. Features and schemas may change. **Unsupported generation config:** The following parameters are not supported and return a 400 error: `temperature`, `top_p`, `top_k`, `stop_sequences`, `max_output_tokens`. **Structured output:** The Antigravity agent does not support structured outputs. **Unavailable tools:** `file_search`, `computer_use`, and `google_maps` are not yet supported. **Remote MCP limitations:** Server-Sent Events (SSE) transport is not supported (use Streamable HTTP). Additionally, the server `name` must be strictly lowercase and alphanumeric (using uppercase letters triggers a generic `400 Bad Request` error). **Filesystem tool:** There is no filesystem tool at the moment. It is part of the `environment`. **Store requirement:** Agent execution using `background=True` requires `store=True`. **Stateful only function calling:** Function calling is only supported in stateful mode. You must use `previous_interaction_id` to continue the turn; reconstructing history manually (stateless mode) is not supported. **Unsupported multimodal types.** Audio, video, and document inputs are not supported at the moment. Only text and image are allowed. What's next [Quickstart](/gemini-api/docs/managed-agents-quickstart): multi-turn conversations and streaming. [Building Custom Agents](/gemini-api/docs/custom-agents): custom instructions, skills, and saving agents. [Environments](/gemini-api/docs/agent-environment): sandbox configuration, sources, networking. [Hooks](/gemini-api/docs/agent-hooks): enforce security gates and side-effect validation inside the sandbox. [Deep Research agent](/gemini-api/docs/deep-research): long-form research tasks. [Interactions API](/gemini-api/docs/interactions-overview): the underlying API. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 52924, "slov": 5570, "odkazu": 135, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:21", "sha256": "66eb62c4cec06c0bc9d190587b86b2582254d5e55135d86aa22e52668034da10", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/api-errors", "titulek": "API errors | Gemini API | Google AI for Developers", "h1": "API errors", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/api-errors", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "API errors  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/api-errors", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "API errors"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "API errors", "item": "https://ai.google.dev/gemini-api/docs/api-errors"}]}], "drobecky": ["Gemini API", "API errors"], "osnova": [{"uroven": 1, "text": "API errors"}, {"uroven": 2, "text": "Standard API error codes"}, {"uroven": 2, "text": "Generation blocked codes"}, {"uroven": 2, "text": "Generation error codes"}, {"uroven": 2, "text": "Error response format"}, {"uroven": 2, "text": "How errors are delivered"}, {"uroven": 3, "text": "Standard HTTP requests"}, {"uroven": 3, "text": "Streaming (SSE) requests"}, {"uroven": 2, "text": "What's next"}], "markdown": "API errors This page provides a reference for all Interactions API error codes, describes the\nerror response format, and explains how the API delivers errors for different request types. Standard API error codes These general request-level error codes correspond to standard HTTP status codes.\nUse the `code` field in your application logic to handle errors programmatically. Code HTTP Status Description Recommended action `invalid_request` 400 Bad Request The request payload is malformed or contains invalid parameters. Check your request syntax and parameters against the [API reference](/api/interactions-api). `failed_precondition` 400 Bad Request The request cannot be processed because a prerequisite is not met (for example, disabled billing). Verify project billing status or account prerequisites. `out_of_range` 416 Requested Range Not Satisfiable Request parameter is outside the valid range. Check parameter values and limits. `parameter_unknown` 400 Bad Request The request contains an unknown parameter. Remove the unrecognized parameter and retry. `authentication` 401 Unauthorized The API key is missing, invalid, or expired. Verify your [API key](/gemini-api/docs/api-key). `permission_denied` 403 Forbidden Your API key does not have permission for this resource. Check your API key permissions and project access. `not_found` 404 Not Found The requested resource was not found. Verify the resource path and parameters. `model_not_found` 404 Not Found The specified model was not found. Verify the model name or fall back to a different model. `already_exists` 409 Conflict The entity you attempted to create already exists. Check if the resource already exists before re-creating. `aborted` 409 Conflict The operation was aborted due to a conflict or concurrency check failure. Retry the request at a higher application level. `rate_limit_exceeded` 429 Too Many Requests You have exceeded the per-minute or per-second request or token limit. Wait and retry with exponential backoff. `quota_exceeded` 429 Too Many Requests You have exceeded your daily quota. Wait until the quota resets or request a quota increase. `too_many_requests` 429 Too Many Requests You have made too many requests in a short period of time. Wait and retry with exponential backoff. `cancelled` 499 Client Closed Request The client cancelled the request before it completed. No action needed. This usually means the client disconnected. `api_error` 500 Internal Server Error An unexpected error occurred on the server. Retry the request. If it persists, contact support. `unimplemented` 501 Not Implemented The operation or feature is not implemented or supported. Check API capabilities or switch to a supported feature. `service_unavailable` 503 Service Unavailable The service is temporarily overloaded or down. Wait and retry with exponential backoff. `deadline_exceeded` 504 Gateway Timeout The request didn't finish within the deadline. Remove or increase client deadline setting to use the server default. Generation blocked codes These error codes indicate that policy, safety, or content restrictions blocked the model's output. When you receive one of these codes, modify your input and retry. Code Description `safety` Safety violations (harmful content) blocked the request. `recitation` Copyright or recitation restrictions blocked the request. `language` An unsupported language blocked the request. `prohibited_content` Prohibited content guidelines blocked the request. `spii` Sensitive Personally Identifiable Information restrictions blocked the request. `blocklist` Prohibited terms on a blocklist blocked the request. `image_safety` Safety violations blocked image generation. `image_prohibited_content` Prohibited content guidelines blocked image generation. `image_recitation` Copyright or recitation restrictions blocked image generation. `image_other` Unspecified reasons blocked image generation. `content_blocked` An unspecified policy reason blocked the request. Generation error codes These error codes indicate a structural issue with the model's generated output (such as a malformed function call or an undeclared tool call). Code Description `malformed_function_call` The model produced a function call that could not be parsed. `malformed_tool_call` The model produced a tool call that could not be parsed. `unexpected_tool_call` The model called a tool that was not declared in the request. `no_image` The model was unable to generate an image. `too_many_tool_calls` The model generated more tool calls than allowed. `missing_thought_signature` The response is missing a required thought signature. Error response format All errors from the Interactions API return an `error` object containing a `code` and `message`. For example, passing an unsupported tool type returns: `{ \"error\": { \"code\": \"invalid_request\", \"message\": \"The value 'invalid_tool_type_xyz' is not supported for 'type' at 'tools[0]'. Supported values: 'function', 'code_execution', 'mcp_server', 'filesystem', 'google_maps', 'google_search', 'bash', 'computer_use', 'file_search', 'url_context'.\" } }` Field Type Description `code` string A machine-readable error code in `snake_case`. `message` string A human-readable description of what went wrong. How errors are delivered The API delivers errors differently depending on whether you make a standard HTTP request or a streaming (SSE) request. Standard HTTP requests For standard (non-streaming) requests, the API sets the HTTP response status code (such as `400 Bad Request`, `401 Unauthorized`, or `429 Too Many Requests`) and returns an `error` object in the JSON response body: `{ \"error\": { \"code\": \"invalid_request\", \"message\": \"The value 'invalid_tool_type_xyz' is not supported for 'type' at 'tools[0]'.\" } }` Streaming (SSE) requests For streaming requests (`stream: true`), the API sends error events over the Server-Sent Events (SSE) stream with `event_type` set to `\"error\"`. The `error` field contains the same `code` and `message` structure: `{ \"event_type\": \"error\", \"error\": { \"code\": \"not_found\", \"message\": \"Failed to get completed interaction: Result not found.\" } }` For the full SSE event schema, see the [Interactions API Reference](/api/interactions-api). What's next [API troubleshooting](/gemini-api/docs/troubleshooting): Resolve common issues and error scenarios. [Rate limits](/gemini-api/docs/rate-limits): Learn about request limits and quota handling. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-08-26 UTC.", "znaku_textu": 6796, "slov": 948, "odkazu": 128, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:31", "sha256": "672918609d176b385e7173f02d8693646864daffe8bb60bfc9a490f563a7d644", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/api-key", "titulek": "Using Gemini API keys | Google AI for Developers", "h1": "Using Gemini API keys", "popis": "Get your Gemini API key and start building in less than 5 minutes using the Interactions API.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/api-key", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Using Gemini API keys  |  Google AI for Developers", "og:description": "Get your Gemini API key and start building in less than 5 minutes using the Interactions API.", "og:url": "https://ai.google.dev/gemini-api/docs/api-key", "og:image": "https://ai.google.dev/static/site-assets/images/api-key.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Using Gemini API keys"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Using Gemini API keys", "item": "https://ai.google.dev/gemini-api/docs/api-key"}]}], "drobecky": ["Gemini API", "Using Gemini API keys"], "osnova": [{"uroven": 1, "text": "Using Gemini API keys"}, {"uroven": 2, "text": "API key types: standard versus authorization"}, {"uroven": 2, "text": "Managing API keys in Google AI Studio"}, {"uroven": 3, "text": "Google Cloud projects"}, {"uroven": 3, "text": "Importing projects"}, {"uroven": 3, "text": "Troubleshooting key creation permissions"}, {"uroven": 2, "text": "Setting up your environment"}, {"uroven": 3, "text": "Option 1: Use environment variables (recommended)"}, {"uroven": 3, "text": "Linux/macOS - Bash"}, {"uroven": 3, "text": "macOS - Zsh"}, {"uroven": 3, "text": "Windows"}, {"uroven": 3, "text": "Option 2: Provide the API key explicitly in code"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Security and secret management"}, {"uroven": 3, "text": "Critical security rules"}, {"uroven": 3, "text": "Secret management best practices"}, {"uroven": 3, "text": "Leak response checklist"}, {"uroven": 2, "text": "Restricting and securing your keys"}, {"uroven": 3, "text": "Apply request origin restrictions"}, {"uroven": 3, "text": "Securing unrestricted standard API keys"}, {"uroven": 4, "text": "Method A: Restrict the key to the Gemini API only (AI Studio)"}, {"uroven": 4, "text": "Method B: Restrict the key for other services (Google Cloud Console)"}, {"uroven": 3, "text": "Blocked dormant keys"}, {"uroven": 2, "text": "Migrate to an auth key"}, {"uroven": 2, "text": "Limitations"}], "markdown": "Using Gemini API keys To use the Gemini API, you must authenticate your requests. You can\nauthenticate using a standard or authorization API key. [Create or view a Gemini API Key](https://aistudio.google.com/apikey) API key types: standard versus authorization API keys provide access to the Gemini API, but their security characteristics\ndiffer. The Gemini API is transitioning from standard API keys to authorization\nkeys to improve security: **Standard API keys**: Associate requests with a Google Cloud project for\nbilling and quota purposes. Standard keys don't identify a caller, which\nlimits the granularity of permissions and access control they can support. **Authorization (auth) keys**: Bound directly to a Google Cloud service\naccount. When you use an authorization key, your requests are processed\nunder the identity of that bound service account, enabling granular access\ncontrol. Authorization keys are restricted to the Generative Language API\n(Gemini API) by default and provide fast-acting leaked key enforcement that\nquickly stops the usage of leaked keys detected by our systems. To ensure secure usage, Gemini API will move from Standard keys to Auth keys: **Auth keys default**: All new API keys created in Google AI Studio\nare automatically created as auth keys. **Unrestricted keys rejected**: The Gemini API rejects requests\nfrom **unrestricted standard keys**. Standard API keys that have explicit\nrestrictions applied continue to work. This restriction prevents the\nunauthorized use of keys that might be shared publicly or linked to other\nservices. **On September 2026**: the Gemini API will reject requests from **Standard\nkeys**. You must migrate to auth keys\nbefore this date to avoid service interruption. Make sure to migrate to\nauth keys before September 2026. Managing API keys in Google AI Studio You can manage your projects and keys directly in [Google AI Studio](https://aistudio.google.com/apikey). Google Cloud projects Every Gemini API key is associated with a [Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects).\nGoogle Cloud projects manage billing, collaborators, and permissions. Google AI\nStudio provides a lightweight interface to access these projects. **Default project**: If you are a new user, Google AI Studio automatically\ncreates a default Google Cloud project and API key after you accept the\nTerms of Service. You can rename this project by navigating to the\n**Projects** view in your dashboard. **Existing projects**: If you already have a Google Cloud account, AI\nStudio does not create a default project. Instead, you must import your\nexisting projects. Importing projects By default, Google AI Studio does not display all of your Google Cloud\nprojects. You must import the projects you want to use: Go to [Google AI Studio](https://aistudio.google.com). Open the **Dashboard** from the left panel and select **Projects**. Click the **Import projects** button. Search for and select the Google Cloud project you want to import, then\nclick **Import**. Once imported, navigate to the **API Keys** page in the dashboard to\ncreate a key in that project. Troubleshooting key creation permissions If the **Create API key** button is unavailable and displays the message:\n*\"You do not have permission to create a key in this project\"*, you lack the\nrequired IAM permissions. Ask your Google Cloud project or organization administrator to grant you a role\ncontaining the following permissions (such as Project Editor): `resourcemanager.projects.get`: Allows AI Studio to verify the project. `apikeys.keys.create`: Allows key generation. `serviceusage.services.enable`: Ensures the Generative Language API is\nenabled. `iam.serviceAccounts.create`: Required to create the linked service account. `iam.serviceAccountApiKeyBindings.create`: Binds the service account to the\nAPI key. If you cannot get administrative access, you can create a new Google Cloud\nproject that is not associated with an organization to generate your keys. Setting up your environment Once you have a key, configure your environment to use it securely in your\napplications. Option 1: Use environment variables (recommended) Set the environment variable `GEMINI_API_KEY` or `GOOGLE_API_KEY`. The Gemini\nAPI client libraries automatically detect and use these variables. If both are\nset, `GOOGLE_API_KEY` takes precedence. Select your operating system to set the variable: Linux/macOS - BashVerify if you have a bash configuration file: `~/.bashrc` If not, create one and open it: `touch ~/.bashrc && open ~/.bashrc` Add the export command at the end of the file: `export GEMINI_API_KEY=` Save the file, then apply the changes: `source ~/.bashrc` macOS - ZshVerify if you have a zsh configuration file: `~/.zshrc` If not, create one and open it: `touch ~/.zshrc && open ~/.zshrc` Add the export command: `export GEMINI_API_KEY=` Save the file, then apply the changes: `source ~/.zshrc` Windows Search for \"Environment Variables\" in the Windows search bar. Click **Environment Variables** in the System Properties dialog. Under **User variables** or **System variables**, click **New...**. Set the variable name to `GEMINI_API_KEY` and the value to your API key. Click **OK** to save. Open a new terminal session to load the variable. Option 2: Provide the API key explicitly in code You can pass the API key explicitly when initializing the client. Only do this\nif you cannot use environment variables. Python`from google import genai client = genai.Client(api_key=\"YOUR_API_KEY\") interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Explain how AI works in a few words\" ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({ apiKey: \"YOUR_API_KEY\" }); async function main() { const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Explain how AI works in a few words\", }); console.log(interaction.output_text); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = Client.builder().apiKey(\"YOUR_API_KEY\").build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Explain how AI works in a few sentences.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H 'Content-Type: application/json' \\ -H \"x-goog-api-key: YOUR_API_KEY\" \\ -X POST \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Explain how AI works in a few words\" }'` Security and secret management Treat your Gemini API key like a password. If compromised, others can consume\nyour project's quota, incur unexpected billing charges, and access private\nresources. Critical security rules **Keep keys confidential**: Never check API keys into source control systems\nlike Git. **Never expose keys client-side in production**: Do not hardcode API keys\ndirectly in web or mobile apps. Keys compiled in client-side code can be\nextracted by users. To secure client-side apps, run a backend proxy\nserver to make the actual API calls. Secret management best practices **Environment variables**: Read keys from environment variables rather than\nconfiguration files. **Secret Manager**: For production, store your keys in a secure secret store\nsuch as [Google Cloud Secret Manager](https://cloud.google.com/secret-manager). **Billing alerts**: Set up billing alerts in the Google Cloud Console to\nnotify you if usage or costs spike. Leak response checklist If you suspect your API key has been leaked: **Generate a new key**: Create a replacement key in Google AI Studio or the\nCloud Console. **Update your application**: Deploy your code using the new key. **Disable or delete the compromised key**: Disable the leaked key in the\nCloud Console once the new key is verified. Do not delete the old key until\nthe new key is fully active to avoid application downtime. **Audit usage**: Check billing logs and API usage in the Google Cloud\nConsole to identify unauthorized activity. Restricting and securing your keys Adding restrictions to your API keys minimizes the potential damage if a key is\ncompromised. Apply request origin restrictions Origin restrictions limit which IP addresses, websites, or applications can use\nyour key. Go to the [Google Cloud Console Credentials page](https://console.cloud.google.com/apis/credentials). Select your project, and click the name of the API key you want to restrict. Under **Application restrictions**, select **IP addresses** (or the\nappropriate restriction type for your environment). Specify the allowed IP addresses or ranges, then click **Save**. Securing unrestricted standard API keys To continue using the Gemini API, you must secure any unrestricted keys. Method A: Restrict the key to the Gemini API only (AI Studio) If you only use the key for the Gemini API, secure it directly in AI Studio: On the **API Keys** page in [Google AI Studio](https://aistudio.google.com/api-keys), locate keys marked with the\n**Unrestricted** label. Hover over the label and click **Add restrictions** in the dialog. Select **Restrict to Gemini API only**. Click **Restrict key** to confirm. Method B: Restrict the key for other services (Google Cloud Console) If the key is shared with other Google APIs (not recommended), restrict it in\nthe Cloud Console. **Note: Gemini API requests using this key will fail after\nthese restrictions are applied.** Visit the [Google Cloud Console Credentials page](https://console.cloud.google.com/apis/credentials). Select the project and the API key. Under **API restrictions**, use the **Select API restrictions** drop-down to\nselect the APIs you want this key to access. Do not select the **Generative\nLanguage API**. Click **Save**. Create a separate, restricted key in AI Studio to continue\nusing the Gemini API. Blocked dormant keys Starting May 7, 2026, the Gemini API blocks unrestricted API keys that have\nbeen dormant for an extended period. These keys show a **Blocked** tag in AI\nStudio. You must generate a new key or use an existing restricted key to\ncontinue. Migrate to an auth key Follow these steps to create a new auth API key and update your applications: Go to the [AI Studio API Keys page](https://aistudio.google.com/api-keys). Check the **Key Type** column to identify any keys listed as **Standard**. Click **Create API key** to generate a new key. All new keys created in\nAI Studio are automatically created as auth keys. Copy the new auth API key. Update your application code, environment variables, and any deployment\nconfigurations to use the new auth API key. Test your application to confirm it works correctly with the new key. Once verified, delete or revoke your old traffic key to prevent misuse. Limitations Google AI Studio imposes the following project and key management limitations: You can create a maximum of 10 projects at a time from the Google AI Studio\n**Projects** page. The **API keys** and **Projects** pages display a maximum of 100 keys and 50\nprojects. Only API keys that are unrestricted or restricted specifically to the\nGenerative Language API (Gemini API) are displayed. For advanced project management or to modify keys with other restrictions, use\nthe [Google Cloud Console credentials page](https://console.cloud.google.com/apis/credentials). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 12138, "slov": 1771, "odkazu": 134, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:06", "sha256": "39c89d346cd3642c9a37a1f6d1ffafb92d932a20da54c80cb0ca33286374b2de", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://cloud.google.com/resource-manager/docs/creating-managing-projects", "https://aistudio.google.com/", "https://cloud.google.com/secret-manager", "https://console.cloud.google.com/apis/credentials", "https://aistudio.google.com/api-keys", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/api-overview", "titulek": "Gemini API reference | Google AI for Developers", "h1": "Gemini API reference", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/api", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini API reference  |  Google AI for Developers", "og:url": "https://ai.google.dev/api", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Gemini API reference"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Gemini API reference", "item": "https://ai.google.dev/api"}]}], "drobecky": ["Gemini API", "Gemini API reference"], "osnova": [{"uroven": 1, "text": "Gemini API reference"}, {"uroven": 2, "text": "Primary endpoints"}, {"uroven": 2, "text": "Authentication"}], "markdown": "Gemini API reference This API reference describes the unary, streaming, and real-time APIs you can\nuse to interact with the Gemini models. You can use the REST APIs in any\nenvironment that supports HTTP requests. Refer to the\n[Get started guide](https://ai.google.dev/gemini-api/docs/get-started)\nfor how to get started with your first API call. If you're looking for\nthe references for our language-specific libraries and SDKs, go to the\nlink for that language in the left navigation under **SDK references**. Primary endpoints The Gemini API is organized around the following major endpoints: **Interactions ([`CreateInteraction`](/api/interactions-api#CreateInteraction)) (Recommended):**\nThe recommended standard primitive for building with Gemini, optimized for\nagentic workflows, server-side state management, and complex multi-modal,\nmulti-turn conversations. **Standard content generation ([`generateContent`](/api/generate-content#method:-models.generatecontent)):**\nA standard REST endpoint that processes your request and returns the model's\nfull response in a single package. This is best for non-interactive tasks\nwhere you can wait for the entire result. **Streaming content generation ([`streamGenerateContent`](/api/generate-content#method:-models.streamgeneratecontent)):**\nUses Server-Sent Events (SSE) to push chunks of the response to you as they\nare generated. This provides a faster, more interactive experience for\napplications like chatbots. **Live API ([`BidiGenerateContent`](/api/live#send-messages)):** A stateful WebSocket-based\nAPI for bi-directional streaming, designed for real-time conversational use\ncases. **Batch mode ([`batchGenerateContent`](/api/batch-mode)):** A standard REST\nendpoint for submitting batches of `generateContent` requests. **Embeddings ([`embedContent`](/api/embeddings)):** A standard REST endpoint\nthat generates a text embedding vector from the input `Content`. **Gen Media APIs:** Endpoints for generating media with our specialized\nmodels such as [Imagen for image generation](/api/models#method:-models.predict),\nand [Veo for video generation](/api/models#method:-models.predictlongrunning).\nGemini also has these capabilities built in which you can access using the\n`generateContent` API. **Platform APIs:** Utility endpoints that support core capabilities such as\n[uploading files](/api/files), and [counting tokens](/api/tokens). Authentication All requests to the Gemini API must include a `x-goog-api-key` header with your\nAPI key. Create one with a few clicks in [Google AI\nStudio](https://aistudio.google.com/apikey). The following is an example request with the API key included in the header: `curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"parts\": [ { \"text\": \"Explain how AI works in a few words\" } ] } ] }'` For instructions on how to pass your key to the API using Gemini SDKs,\nsee the [Using Gemini API keys](/gemini-api/docs/api-key) guide. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 3500, "slov": 479, "odkazu": 50, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 08:43:45", "sha256": "38f9d265f00d51cdb846416c534e827e03329449c2b9df6df2e7763e19bff129", "hloubka": 2, "zdroj_objevu": "odkaz", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://googleapis.github.io/python-genai/", "https://pkg.go.dev/google.golang.org/genai", "https://googleapis.github.io/js-genai/", "https://googleapis.github.io/java-genai/javadoc/", "https://googleapis.github.io/dotnet-genai/", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/api-versions", "titulek": "API versions explained | Gemini API | Google AI for Developers", "h1": "API versions explained", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/api-versions", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "API versions explained  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/api-versions", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "API versions explained"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "API versions explained", "item": "https://ai.google.dev/gemini-api/docs/api-versions"}]}], "drobecky": ["Gemini API", "API versions explained"], "osnova": [{"uroven": 1, "text": "API versions explained"}, {"uroven": 2, "text": "Capability and feature support"}, {"uroven": 2, "text": "Configure API version in an SDK"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}], "markdown": "API versions explained This document provides a high-level overview of the differences between the `v1`\nand `v1beta` versions of the Gemini API. **v1**: Stable version of the API. Features in the stable version are\nfully supported over the lifetime of the major version. If there are any\nbreaking changes, a new major version of the API will be created and the\nexisting version will be deprecated after a reasonable period of time.\nNon-breaking changes may be introduced to the API without changing the\nmajor version. The **Interactions API** and its core features are\ngenerally available in `v1`. **v1beta**: This version includes early features and capabilities that are\nactively being developed. While features in `v1beta` may be subject to\nchanges as we refine them based on feedback, it lets you try new\ncapabilities before they are promoted to stable. Capability and feature support The following table details the availability of capabilities across `v1` (GA)\nand `v1beta` (Beta). Core API capabilities and tools apply to both\nthe Interactions API and `generateContent` unless specified otherwise: Feature v1 v1beta **Core API capabilities** [Interactions API](/gemini-api/docs/get-started) [Function Calling](/gemini-api/docs/function-calling) [Structured Output](/gemini-api/docs/structured-output) [Thinking / Reasoning](/gemini-api/docs/thinking) [System Instructions](/gemini-api/docs/system-instructions) [Audio Output (Speech Config)](/gemini-api/docs/audio) [Service Tier (Priority / Flex)](/gemini-api/docs/priority-inference) **Tools** [Code Execution Tool](/gemini-api/docs/code-execution) [Google Search Grounding](/gemini-api/docs/google-search) [Google Maps Grounding](/gemini-api/docs/maps-grounding) [URL Context Tool](/gemini-api/docs/url-context) [File Search Tool](/gemini-api/docs/file-search) [Computer Use Tool](/gemini-api/docs/computer-use) [MCP Servers Tool](/gemini-api/docs/function-calling#mcp) **Realtime APIs** [Live API (WebSockets)](/gemini-api/docs/live-api) [Live Music API](/gemini-api/docs/realtime-music-generation) [Ephemeral Tokens (Live API)](/gemini-api/docs/live-api/ephemeral-tokens) **Platform APIs** [Models API](/gemini-api/docs/models) [Files Service Route](/gemini-api/docs/files) [File Search Stores Route](/gemini-api/docs/file-search) [Agents API](/gemini-api/docs/agents) [Webhooks API](/gemini-api/docs/webhooks) [Context Caching](/gemini-api/docs/caching) - Supported Configure API version in an SDK The Gemini API SDKs default to `v1beta`, but you can explicitly specify versions\nby setting the API version as shown in the following code sample: Python`from google import genai client = genai.Client(http_options={'api_version': 'v1'}) interaction = client.interactions.create( model='gemini-3.8-flash', input=\"Explain how AI works\", ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({ httpOptions: { apiVersion: \"v1\" }, }); async function main() { const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Explain how AI works\", }); console.log(interaction.output_text); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.types.HttpOptions; Client client = Client.builder() .httpOptions(HttpOptions.builder().apiVersion(\"v1\").build()) .build(); CreateModelInteraction req = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Explain how AI works\")) .build(); var interaction = client.interactions.create(CreateInteractionRequestBody.of(req)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Explain how AI works\", }'` Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-08 UTC.", "znaku_textu": 4572, "slov": 511, "odkazu": 63, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:13", "sha256": "a64700f7b829252ab53336ba7273f0c0d275c772d581ed1cfd7fb4f1fdaf7f58", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://googleapis.github.io/python-genai/", "https://pkg.go.dev/google.golang.org/genai", "https://googleapis.github.io/js-genai/", "https://googleapis.github.io/java-genai/javadoc/", "https://googleapis.github.io/dotnet-genai/", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/audio", "titulek": "Audio understanding | Gemini API | Google AI for Developers", "h1": "Audio understanding", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/audio", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Audio understanding  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/audio", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Audio understanding"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Audio understanding", "item": "https://ai.google.dev/gemini-api/docs/audio"}]}], "drobecky": ["Gemini API", "Audio understanding"], "osnova": [{"uroven": 1, "text": "Audio understanding"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Overview"}, {"uroven": 2, "text": "Transcribe speech to text"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Input audio"}, {"uroven": 3, "text": "Upload an audio file"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Pass audio data inline"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Get a transcript"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Refer to timestamps"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Count tokens"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Supported audio formats"}, {"uroven": 2, "text": "Technical details about audio"}, {"uroven": 2, "text": "What's next"}], "markdown": "Audio understanding Gemini can analyze audio input and generate text responses. Python`from google import genai import base64 client = genai.Client() uploaded_file = client.files.upload(file=\"path/to/sample.mp3\") interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": \"Describe this audio clip\"}, { \"type\": \"audio\", \"uri\": uploaded_file.uri, \"mime_type\": uploaded_file.mime_type } ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const uploadedFile = await client.files.upload({ file: \"path/to/sample.mp3\", config: { mime_type: \"audio/mp3\" } }); const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ {type: \"text\", text: \"Describe this audio clip\"}, { type: \"audio\", uri: uploadedFile.uri, mime_type: uploadedFile.mimeType } ] }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AudioContent; import com.google.genai.gaos.models.interactions.AudioContentMimeType; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Provide a transcript and summary of this audio.\").build(); Content audioContent = AudioContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/audio/pixel.mp3\") .mimeType(AudioContentMimeType.AUDIO_MP3) .build(); List contents = Arrays.asList(textContent, audioContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# First upload the file, then use the URI:\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"text\", \"text\": \"Describe this audio clip\"}, { \"type\": \"audio\", \"uri\": \"YOUR_FILE_URI\", \"mime_type\": \"audio/mp3\" } ] }'` Overview Gemini can analyze and understand audio input and generate text responses,\nenabling use cases like: Describe, summarize, or answer questions about audio content Transcription and translation (speech to text) Speaker diarization (identifying different speakers) Emotion detection in speech and music Analyzing specific segments with timestamps For real-time voice and video interactions, see the\n[Live API](/gemini-api/docs/live).\nFor dedicated speech to text models with support for real-time transcription,\nuse the [Google Cloud Speech-to-Text API](https://cloud.google.com/speech-to-text). Transcribe speech to text This example shows how to transcribe, translate, and summarize speech with\ntimestamps, speaker diarization, and emotion detection using\n[structured outputs](/gemini-api/docs/structured-output). Python`from google import genai client = genai.Client() YOUTUBE_URL = \"https://www.youtube.com/watch?v=ku-N-eS1lgM\" prompt = \"\"\" Process the audio file and generate a detailed transcription. Requirements: 1. Identify distinct speakers (e.g., Speaker 1, Speaker 2). 2. Provide accurate timestamps for each segment (Format: MM:SS). 3. Detect the primary language of each segment. 4. If not English, provide the English translation. 5. Identify the primary emotion: Happy, Sad, Angry, or Neutral. 6. Provide a brief summary at the beginning. \"\"\" response_schema = { \"type\": \"object\", \"properties\": { \"summary\": {\"type\": \"string\"}, \"segments\": { \"type\": \"array\", \"items\": { \"type\": \"object\", \"properties\": { \"speaker\": {\"type\": \"string\"}, \"timestamp\": {\"type\": \"string\"}, \"content\": {\"type\": \"string\"}, \"language\": {\"type\": \"string\"}, \"emotion\": { \"type\": \"string\", \"enum\": [\"happy\", \"sad\", \"angry\", \"neutral\"] } }, \"required\": [\"speaker\", \"timestamp\", \"content\", \"emotion\"] } } }, \"required\": [\"summary\", \"segments\"] } interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"video\", \"uri\": YOUTUBE_URL, \"mime_type\": \"video/mp4\"}, {\"type\": \"text\", \"text\": prompt} ], response_format=response_schema, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const YOUTUBE_URL = \"https://www.youtube.com/watch?v=ku-N-eS1lgM\"; const prompt = ` Process the audio file and generate a detailed transcription. Requirements: 1. Identify distinct speakers (e.g., Speaker 1, Speaker 2). 2. Provide accurate timestamps for each segment (Format: MM:SS). 3. Detect the primary language of each segment. 4. If not English, provide the English translation. 5. Identify the primary emotion: Happy, Sad, Angry, or Neutral. 6. Provide a brief summary at the beginning. `; const responseSchema = { type: \"object\", properties: { summary: { type: \"string\" }, segments: { type: \"array\", items: { type: \"object\", properties: { speaker: { type: \"string\" }, timestamp: { type: \"string\" }, content: { type: \"string\" }, language: { type: \"string\" }, emotion: { type: \"string\", enum: [\"happy\", \"sad\", \"angry\", \"neutral\"] } }, required: [\"speaker\", \"timestamp\", \"content\", \"emotion\"] } } }, required: [\"summary\", \"segments\"] }; const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"video\", uri: YOUTUBE_URL, mime_type: \"video/mp4\" }, { type: \"text\", text: prompt } ], response_format: responseSchema, }); console.log(JSON.parse(interaction.output_text));` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AudioContent; import com.google.genai.gaos.models.interactions.AudioContentMimeType; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Provide a transcript and summary of this audio.\").build(); Content audioContent = AudioContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/audio/pixel.mp3\") .mimeType(AudioContentMimeType.AUDIO_MP3) .build(); List contents = Arrays.asList(textContent, audioContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ { \"type\": \"video\", \"uri\": \"https://www.youtube.com/watch?v=ku-N-eS1lgM\", \"mime_type\": \"video/mp4\" }, { \"type\": \"text\", \"text\": \"Transcribe with speaker diarization and emotion detection.\" } ], \"response_format\": { \"type\": \"object\", \"properties\": { \"summary\": {\"type\": \"string\"}, \"segments\": { \"type\": \"array\", \"items\": { \"type\": \"object\", \"properties\": { \"speaker\": {\"type\": \"string\"}, \"timestamp\": {\"type\": \"string\"}, \"content\": {\"type\": \"string\"}, \"emotion\": {\"type\": \"string\", \"enum\": [\"happy\", \"sad\", \"angry\", \"neutral\"]} } } } } } }'` Input audio You can provide audio data in the following ways: Upload an audio file before making a request. Pass inline audio data with the request. Upload an audio file Use the [Files API](/gemini-api/docs/files) for files larger than 20 MB. Python`from google import genai client = genai.Client() uploaded_file = client.files.upload(file=\"path/to/sample.mp3\") interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": \"Describe this audio clip\"}, { \"type\": \"audio\", \"uri\": uploaded_file.uri, \"mime_type\": uploaded_file.mime_type } ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const uploadedFile = await client.files.upload({ file: \"path/to/sample.mp3\", config: { mimeType: \"audio/mp3\" } }); const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ {type: \"text\", text: \"Describe this audio clip\"}, { type: \"audio\", uri: uploadedFile.uri, mime_type: uploadedFile.mimeType } ] }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AudioContent; import com.google.genai.gaos.models.interactions.AudioContentMimeType; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Provide a transcript and summary of this audio.\").build(); Content audioContent = AudioContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/audio/pixel.mp3\") .mimeType(AudioContentMimeType.AUDIO_MP3) .build(); List contents = Arrays.asList(textContent, audioContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# First upload the file using the Files API, then use the URI:\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"text\", \"text\": \"Describe this audio clip\"}, { \"type\": \"audio\", \"uri\": \"YOUR_FILE_URI\", \"mime_type\": \"audio/mp3\" } ] }'` Pass audio data inline For small audio files under 20MB total request size: Python`from google import genai import base64 client = genai.Client() with open('path/to/small-sample.mp3', 'rb') as f: audio_bytes = f.read() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": \"Describe this audio clip\"}, { \"type\": \"audio\", \"data\": base64.b64encode(audio_bytes).decode('utf-8'), \"mime_type\": \"audio/mp3\" } ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const client = new GoogleGenAI({}); const audioData = fs.readFileSync(\"path/to/small-sample.mp3\", { encoding: \"base64\" }); const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ {type: \"text\", text: \"Describe this audio clip\"}, { type: \"audio\", data: audioData, mime_type: \"audio/mp3\" } ] }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AudioContent; import com.google.genai.gaos.models.interactions.AudioContentMimeType; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Provide a transcript and summary of this audio.\").build(); Content audioContent = AudioContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/audio/pixel.mp3\") .mimeType(AudioContentMimeType.AUDIO_MP3) .build(); List contents = Arrays.asList(textContent, audioContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`AUDIO_PATH=\"path/to/sample.mp3\" if [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then B64FLAGS=\"--input\" else B64FLAGS=\"-w0\" fi\n\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"text\", \"text\": \"Describe this audio clip\"}, { \"type\": \"audio\", \"data\": \"'$(base64 $B64FLAGS $AUDIO_PATH)'\", \"mime_type\": \"audio/mp3\" } ] }'` Notes on inline audio data:\n* Maximum request size is 20 MB total (including prompts and all files)\n* For reuse, upload the file instead Get a transcript To get a transcript, ask for it in the prompt: Python`interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": \"Generate a transcript of the speech.\"}, { \"type\": \"audio\", \"uri\": uploaded_file.uri, \"mime_type\": uploaded_file.mime_type } ] ) print(interaction.output_text)` JavaScript`const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: \"Generate a transcript of the speech.\" }, { type: \"audio\", uri: uploadedFile.uri, mime_type: uploadedFile.mimeType } ] }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AudioContent; import com.google.genai.gaos.models.interactions.AudioContentMimeType; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Provide a transcript and summary of this audio.\").build(); Content audioContent = AudioContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/audio/pixel.mp3\") .mimeType(AudioContentMimeType.AUDIO_MP3) .build(); List contents = Arrays.asList(textContent, audioContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Refer to timestamps Use `MM:SS` format to reference specific sections: Python`interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": \"Provide a transcript from 02:30 to 03:29.\"}, { \"type\": \"audio\", \"uri\": uploaded_file.uri, \"mime_type\": uploaded_file.mime_type } ] )` JavaScript`const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: \"Provide a transcript from 02:30 to 03:29.\" }, { type: \"audio\", uri: uploadedFile.uri, mime_type: \"audio/mp3\" } ] });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AudioContent; import com.google.genai.gaos.models.interactions.AudioContentMimeType; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Provide a transcript and summary of this audio.\").build(); Content audioContent = AudioContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/audio/pixel.mp3\") .mimeType(AudioContentMimeType.AUDIO_MP3) .build(); List contents = Arrays.asList(textContent, audioContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Count tokens Count tokens in an audio file: Python`response = client.models.count_tokens( model=\"gemini-3.8-flash\", contents=[uploaded_file] ) print(response)` JavaScript`const response = await client.models.countTokens({ model: \"gemini-3.8-flash\", contents: [ { fileData: { fileUri: uploadedFile.uri, mimeType: uploadedFile.mimeType } } ] }); console.log(response.totalTokens);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AudioContent; import com.google.genai.gaos.models.interactions.AudioContentMimeType; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Provide a transcript and summary of this audio.\").build(); Content audioContent = AudioContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/audio/pixel.mp3\") .mimeType(AudioContentMimeType.AUDIO_MP3) .build(); List contents = Arrays.asList(textContent, audioContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Supported audio formats Gemini supports the following audio format MIME types: WAV - `audio/wav` MP3 - `audio/mp3` AIFF - `audio/aiff` AAC - `audio/aac` OGG - `audio/ogg` FLAC - `audio/flac` MPEG - `audio/mpeg` M4A - `audio/m4a` L16 - `audio/l16` Opus - `audio/opus` ALAW - `audio/alaw` MULAW - `audio/mulaw` WebM - `audio/webm` For the complete list of supported MIME types and parameter schemas, see the [Interactions API reference](/api/interactions-api#Resource:Content). Technical details about audio **Tokens**: 32 tokens per second of audio (1 minute = 1,920 tokens) **Non-speech**: Gemini understands non-speech sounds (birdsong, sirens, etc.) **Max length**: 9.5 hours of audio per prompt **Resolution**: Downsampled to 16 Kbps **Channels**: Multi-channel audio combined to single channel What's next [Files API](/gemini-api/docs/files): Upload and manage audio files [System instructions](/gemini-api/docs/text-generation#system-instructions):\nCustomize model behavior [Structured output](/gemini-api/docs/structured-output):\nGet transcription results in JSON format Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 21062, "slov": 1939, "odkazu": 133, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:45", "sha256": "265809ca1dc2724ed440775965b6ba643232dfd6fcc283ba4b69d2d5642021bc", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://cloud.google.com/speech-to-text", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/available-regions", "titulek": "Available regions for Google AI Studio and Gemini API | Google AI for Developers", "h1": "Available regions for Google AI Studio and Gemini API", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/available-regions", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Available regions for Google AI Studio and Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/available-regions", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Available regions for Google AI Studio and Gemini API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Available regions for Google AI Studio and Gemini API", "item": "https://ai.google.dev/gemini-api/docs/available-regions"}]}], "drobecky": ["Gemini API", "Available regions for Google AI Studio and Gemini API"], "osnova": [{"uroven": 1, "text": "Available regions for Google AI Studio and Gemini API"}, {"uroven": 2, "text": "Available regions"}], "markdown": "Available regions for Google AI Studio and Gemini API If you reached this page while attempting to access [Google AI Studio](https://aistudio.google.com/), it may\nbe due to one of the following reasons: **Regional restrictions**: Google AI Studio is not available in your region. Refer to the section below for a list of supported regions. **Age requirements**: You do not meet the minimum age requirement (18+) to access this service. **Account verification**: You may have access to the service, but you haven't yet [verified your age](https://support.google.com/accounts/answer/10071085) on your Google Account. For further details regarding requirements, review our [Terms of Service](/gemini-api/terms). Available regions The Gemini API and Google AI Studio are available in the following countries and\nterritories. If you're not in one of these countries or territories, try the\n[Gemini API in Gemini Enterprise Agent Platform](https://cloud.google.com/gemini-enterprise-agent-platform): Albania Algeria American Samoa Andorra Angola Anguilla Antarctica Antigua and Barbuda Argentina Armenia Aruba Australia Austria Azerbaijan The Bahamas Bahrain Bangladesh Barbados Belgium Belize Benin Bermuda Bhutan Bolivia Bosnia and Herzegovina Botswana Brazil British Indian Ocean Territory British Virgin Islands Brunei Bulgaria Burkina Faso Burundi Cabo Verde Cambodia Cameroon Canada Caribbean Netherlands Cayman Islands Central African Republic Chad Chile Christmas Island Cocos (Keeling) Islands Colombia Comoros Cook Islands Costa Rica CĂ´te d'Ivoire Croatia Curaçao Czech Republic Democratic Republic of the Congo Denmark Djibouti Dominica Dominican Republic Ecuador Egypt El Salvador Equatorial Guinea Eritrea Estonia Eswatini Ethiopia Falkland Islands (Islas Malvinas) Faroe Islands Fiji Finland France French Guiana Gabon The Gambia Georgia Germany Ghana Gibraltar Greece Greenland Grenada Guam Guatemala Guernsey Guinea Guinea-Bissau Guyana Haiti Heard Island and McDonald Islands Honduras Hungary Iceland India Indonesia Iraq Ireland Isle of Man Israel Italy Jamaica Japan Jersey Jordan Kazakhstan Kenya Kiribati Kosovo Kuwait Kyrgyzstan Laos Latvia Lebanon Lesotho Liberia Libya Liechtenstein Lithuania Luxembourg Madagascar Malawi Malaysia Maldives Mali Malta Marshall Islands Mauritania Mauritius Mexico Micronesia Moldova Monaco Mongolia Montenegro Montserrat Morocco Mozambique Namibia Nauru Nepal Netherlands New Caledonia New Zealand Nicaragua Niger Nigeria Niue Norfolk Island North Macedonia Northern Mariana Islands Norway Oman Pakistan Palau Palestine Panama Papua New Guinea Paraguay Peru Philippines Pitcairn Islands Poland Portugal Puerto Rico Qatar Republic of Cyprus Republic of the Congo Romania Rwanda RĂŠunion Saint BarthĂŠlemy Saint Helena, Ascension and Tristan da Cunha Saint Kitts and Nevis Saint Lucia Saint Pierre and Miquelon Saint Vincent and the Grenadines Samoa San Marino SĂŁo TomĂŠ and PrĂ­ncipe Saudi Arabia Senegal Serbia Seychelles Sierra Leone Singapore Slovakia Slovenia Solomon Islands Somalia South Africa South Georgia and the South Sandwich Islands South Korea South Sudan Spain Sri Lanka Sudan Suriname Sweden Switzerland Taiwan Tajikistan Tanzania Thailand Timor-Leste Togo Tokelau Tonga Trinidad and Tobago Tunisia Turkmenistan Turks and Caicos Islands Tuvalu TĂźrkiye Uganda Ukraine United Arab Emirates United Kingdom United States United States Minor Outlying Islands Uruguay U.S. Virgin Islands Uzbekistan Vanuatu Vatican City Venezuela Vietnam Wallis and Futuna Western Sahara Yemen Zambia Zimbabwe Åland Islands Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-04-28 UTC.", "znaku_textu": 4026, "slov": 542, "odkazu": 130, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:07", "sha256": "7355c74e86aa006e965217ed3c184f1770ab289e633d7c94e0971220157050a7", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/", "https://support.google.com/accounts/answer/10071085", "https://cloud.google.com/gemini-enterprise-agent-platform", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/background-execution", "titulek": "Background execution | Gemini API | Google AI for Developers", "h1": "Background execution", "popis": "Run long-running background tasks and agents using background=true in the Interactions API.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/background-execution", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Background execution  |  Gemini API  |  Google AI for Developers", "og:description": "Run long-running background tasks and agents using background=true in the Interactions API.", "og:url": "https://ai.google.dev/gemini-api/docs/background-execution", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Background execution"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Background execution", "item": "https://ai.google.dev/gemini-api/docs/background-execution"}]}], "drobecky": ["Gemini API", "Background execution"], "osnova": [{"uroven": 1, "text": "Background execution"}, {"uroven": 2, "text": "Create a background interaction"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How background execution works"}, {"uroven": 3, "text": "Use cases"}, {"uroven": 2, "text": "Retrieve results"}, {"uroven": 3, "text": "Polling pattern (non-blocking)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Streaming pattern"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multi-turn conversations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Cancellation and deletion"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Next steps"}], "markdown": "Background execution For long-running tasks like deep research, complex reasoning, or multi-step agent executions, connection timeouts can interrupt standard HTTP requests (which typically close after 60 seconds). The [Interactions API](/gemini-api/docs/interactions-overview) provides **background execution** to run these tasks asynchronously. To let the interaction run until it completes the task on the server, set `\"background\": true` when creating the interaction. The API immediately returns an interaction ID, which client applications can use to poll for status, stream progress, or reconnect to a disconnected stream. Background execution is supported for standard Gemini models (such as `gemini-3.8-flash` and `gemini-3.1-pro-preview`) and Managed Agents (such as `antigravity-preview-05-2026`). Create a background interaction To start a background interaction, set the `background` parameter to `true` when creating the resource. Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Write a guide on space exploration.\", background=True, ) print(f\"Created background interaction ID: {interaction.id}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: \"Write a guide on space exploration.\", background: true, }); console.log(`Created background interaction ID: ${interaction.id}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.gaos.models.operations.GetInteractionByIdRequest; import com.google.genai.gaos.models.operations.GetInteractionByIdResponse; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Execute this background task.\")) .background(true) .environment(CreateModelInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); String interactionId = interaction.id().orElse(\"\"); // Poll status using GetInteractionByIdRequest GetInteractionByIdResponse getResponse = client.interactions.get(new GetInteractionByIdRequest(interactionId)); Interaction polled = getResponse.interaction().get(); System.out.println(\"Status: \" + polled.status().orElse(null));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -H \"Api-Revision: 2026-05-20\" \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Write a guide on space exploration.\", \"background\": true }'` How background execution works When you create a background interaction, the task runs asynchronously on the server. The interaction transitions through various execution states: `in_progress`: The server is actively executing the interaction (such as running code or researching). `requires_action`: The interaction has paused and is waiting for client input (such as confirming a tool execution or answering a question). `completed`: The interaction finished successfully and the output is available. `failed`: An error occurred during execution (such as tool failure or rate limits). `cancelled`: A client request stopped the execution. Use cases Use background execution for: **Agent executions:** Tasks requiring code execution, web browsing, or sub-agent orchestration (such as `antigravity-preview-05-2026`). **Deep research:** Runs using `deep-research-preview-04-2026` or `deep-research-max-preview-04-2026` which take several minutes. **Long reasoning:** Tasks where model thinking steps exceed standard HTTP connection limits. Retrieve results Obtain background interaction results using either **polling** or **streaming**. Polling pattern (non-blocking) Polling checks the interaction status periodically using non-blocking GET requests until it reaches a terminal state. Python`import time from google import genai client = genai.Client() interaction = client.interactions.get(id=\"YOUR_INTERACTION_ID\") while interaction.status == \"in_progress\": time.sleep(5) interaction = client.interactions.get(id=interaction.id) if interaction.status == \"completed\": print(interaction.output_text) else: print(f\"Finished with status: {interaction.status}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); let interaction = await client.interactions.get(\"YOUR_INTERACTION_ID\"); while (interaction.status === \"in_progress\") { await new Promise(resolve => setTimeout(resolve, 5000)); interaction = await client.interactions.get(interaction.id); } if (interaction.status === \"completed\") { console.log(interaction.output_text); } else { console.log(`Finished with status: ${interaction.status}`); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.gaos.models.operations.GetInteractionByIdRequest; import com.google.genai.gaos.models.operations.GetInteractionByIdResponse; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Execute this background task.\")) .background(true) .environment(CreateModelInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); String interactionId = interaction.id().orElse(\"\"); // Poll status using GetInteractionByIdRequest GetInteractionByIdResponse getResponse = client.interactions.get(new GetInteractionByIdRequest(interactionId)); Interaction polled = getResponse.interaction().get(); System.out.println(\"Status: \" + polled.status().orElse(null));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Api-Revision: 2026-05-20\"` Streaming pattern If a network interruption disconnects a stream, streaming can resume from the last received event. Each delta contains a unique `event_id` in its payload. Passing this ID as `last_event_id` resumes the stream from that event. Python`import time from google import genai client = genai.Client() interaction_id = \"YOUR_INTERACTION_ID\" def stream_with_reconnect(interaction_id: str): last_event_id = None while True: try: # Retrieve the stream. If resuming, pass last_event_id stream = client.interactions.get( id=interaction_id, stream=True, last_event_id=last_event_id ) for event in stream: # Log event updates and capture event_id if present if event.event_id: last_event_id = event.event_id if event.event_type == \"step.delta\" and event.delta.type == \"text\": print(event.delta.text, end=\"\", flush=True) if event.event_type == \"interaction.completed\": return except Exception as e: print(f\"\\n[Connection lost: {e}. Reconnecting in 3s...]\") time.sleep(3) stream_with_reconnect(interaction_id)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interactionId = \"YOUR_INTERACTION_ID\"; async function streamWithReconnect(id) { let lastEventId = undefined; while (true) { try { // Retrieve the stream. If resuming, pass last_event_id in options const stream = await client.interactions.get(id, { stream: true, last_event_id: lastEventId }); for await (const event of stream) { // Capture event_id if present const idVal = event.event_id || event.id; if (idVal) { lastEventId = idVal; } if (event.event_type === \"step.delta\" && event.delta?.type === \"text\") { process.stdout.write(event.delta.text); } if (event.event_type === \"interaction.completed\") { return; } } } catch (error) { console.log(`\\n[Connection lost: ${error.message}. Reconnecting in 3s...]`); await new Promise(resolve => setTimeout(resolve, 3000)); } } } await streamWithReconnect(interactionId);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.gaos.models.operations.GetInteractionByIdRequest; import com.google.genai.gaos.models.operations.GetInteractionByIdResponse; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Execute this background task.\")) .background(true) .environment(CreateModelInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); String interactionId = interaction.id().orElse(\"\"); // Poll status using GetInteractionByIdRequest GetInteractionByIdResponse getResponse = client.interactions.get(new GetInteractionByIdRequest(interactionId)); Interaction polled = getResponse.interaction().get(); System.out.println(\"Status: \" + polled.status().orElse(null));` REST`curl -N -X GET \"https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID?stream=true&last_event_id=YOUR_LAST_EVENT_ID\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Api-Revision: 2026-05-20\"` Multi-turn conversations Subsequent interactions can chain to a background conversation using `previous_interaction_id`, subject to these constraints: **Active executions are blocked:** Chaining a subsequent interaction to one with `in_progress` status returns a `400 Bad Request` error. Wait for the interaction to reach the `completed` state before starting the next one. **Environment Parameter for Managed Agents:** When chaining interactions for Managed Agents (such as `antigravity-preview-05-2026`), requests must include both `previous_interaction_id` and `environment`. The following examples show how to chain interactions: Python`import time from google import genai client = genai.Client() agent_model = \"antigravity-preview-05-2026\" # First interaction: Provision sandbox environment and execute first instruction interaction1 = client.interactions.create( model=agent_model, input=\"Create a folder named project/ and write hello.py inside.\", environment=\"remote\", background=True ) # Wait for completion while True: check = client.interactions.get(id=interaction1.id) if check.status != \"in_progress\": break time.sleep(2) # Second interaction: Chain using previous_interaction_id and environment interaction2 = client.interactions.create( model=agent_model, input=\"List all files in the project/ directory.\", previous_interaction_id=interaction1.id, environment=\"remote\", background=True )` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const agentModel = \"antigravity-preview-05-2026\"; // First interaction: Provision sandbox environment and execute first instruction const interaction1 = await client.interactions.create({ model: agentModel, input: \"Create a folder named project/ and write hello.py inside.\", environment: \"remote\", background: true }); // Wait for completion while (true) { const check = await client.interactions.get(interaction1.id); if (check.status !== \"in_progress\") { break; } await new Promise(resolve => setTimeout(resolve, 2000)); } // Second interaction: Chain using previous_interaction_id and environment const interaction2 = await client.interactions.create({ model: agentModel, input: \"List all files in the project/ directory.\", previous_interaction_id: interaction1.id, environment: \"remote\", background: true });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.gaos.models.operations.GetInteractionByIdRequest; import com.google.genai.gaos.models.operations.GetInteractionByIdResponse; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Execute this background task.\")) .background(true) .environment(CreateModelInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); String interactionId = interaction.id().orElse(\"\"); // Poll status using GetInteractionByIdRequest GetInteractionByIdResponse getResponse = client.interactions.get(new GetInteractionByIdRequest(interactionId)); Interaction polled = getResponse.interaction().get(); System.out.println(\"Status: \" + polled.status().orElse(null));` REST`# Chain second interaction (Make sure FIRST_INTERACTION_ID has status 'completed')\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -H \"Api-Revision: 2026-05-20\" \\ -d '{ \"model\": \"antigravity-preview-05-2026\", \"input\": \"List all files in the project/ directory.\", \"previous_interaction_id\": \"FIRST_INTERACTION_ID\", \"environment\": \"remote\", \"background\": true }'` Cancellation and deletion Control running executions and manage storage using cancel and delete requests: **Cancel (`POST /interactions/{id}/cancel`):** Stops the running task. The status transitions to `cancelled`. Clean-up actions on the server can cause a slight delay before the status updates in GET requests. **Delete (`DELETE /interactions/{id}`):** Removes the interaction records from the server. Subsequent GET requests return a `404 Not Found` error. Python`from google import genai client = genai.Client() # Cancel a running interaction client.interactions.cancel(id=\"YOUR_INTERACTION_ID\") # Delete the interaction record entirely client.interactions.delete(id=\"YOUR_INTERACTION_ID\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); // Cancel a running interaction await client.interactions.cancel(\"YOUR_INTERACTION_ID\"); // Delete the interaction record entirely await client.interactions.delete(\"YOUR_INTERACTION_ID\");` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.CreateModelInteractionEnvironment; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.gaos.models.operations.GetInteractionByIdRequest; import com.google.genai.gaos.models.operations.GetInteractionByIdResponse; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Execute this background task.\")) .background(true) .environment(CreateModelInteractionEnvironment.of(\"remote\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); String interactionId = interaction.id().orElse(\"\"); // Poll status using GetInteractionByIdRequest GetInteractionByIdResponse getResponse = client.interactions.get(new GetInteractionByIdRequest(interactionId)); Interaction polled = getResponse.interaction().get(); System.out.println(\"Status: \" + polled.status().orElse(null));` REST`# Cancel the interaction\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID/cancel\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Api-Revision: 2026-05-20\" # Delete the interaction\ncurl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/interactions/YOUR_INTERACTION_ID\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Api-Revision: 2026-05-20\"` Next steps Read the [Interactions API overview](/gemini-api/docs/interactions-overview) to understand session and state management. See the [Streaming interactions](/gemini-api/docs/streaming) guide for details on real-time event updates. Explore the [Managed agents quickstart](/gemini-api/docs/managed-agents-quickstart) to build stateful multi-turn agents. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 17779, "slov": 1675, "odkazu": 128, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:51", "sha256": "1fc39b4741ebc702eb45837eee8bbf6c3330fe12b292818ae75aed8691366f39", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/batch-api", "titulek": "Batch API | Gemini API | Google AI for Developers", "h1": "Batch API", "popis": "Get started building with the Batch API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/batch-api", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Batch API  |  Gemini API  |  Google AI for Developers", "og:description": "Get started building with the Batch API", "og:url": "https://ai.google.dev/gemini-api/docs/batch-api", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Batch API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Batch API", "item": "https://ai.google.dev/gemini-api/docs/batch-api"}]}], "drobecky": ["Gemini API", "Batch API"], "osnova": [{"uroven": 1, "text": "Batch API"}, {"uroven": 2, "text": "Creating a batch job"}, {"uroven": 3, "text": "Inline requests"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Input file"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Batch embedding support"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Request configuration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Monitoring job status"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Polling and webhooks"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Retrieving results"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Listing batch jobs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Cancelling a batch job"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Deleting a batch job"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Generating images in batch"}, {"uroven": 3, "text": "Inline requests for images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Input file for images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Technical details"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "What's next"}], "markdown": "Batch API The Gemini Batch API is designed to process large volumes of requests\nasynchronously at [50% of the standard cost](/gemini-api/docs/pricing).\nThe target turnaround time is 24 hours, but in majority of cases, it is much\nquicker. Use Batch API for large-scale, non-urgent tasks such as data\npre-processing or running evaluations where an immediate response is not\nrequired. Creating a batch job You have two ways to submit your requests in Batch API: **Inline requests:** A list of\n[`GenerateContentRequest`](/api/batch-mode#GenerateContentRequest) objects\ndirectly included in your batch creation request. This is suitable for\nsmaller batches that keep the total request size under 20MB. The **output**\nreturned from the model is a list of `inlineResponse` objects. **Input file:** A [JSON Lines (JSONL)](https://jsonlines.org/)\nfile where each line contains a complete\n[`GenerateContentRequest`](/api/batch-mode#GenerateContentRequest) object.\nThis method is recommended for larger requests. The **output**\nreturned from the model is a JSONL file where each line is either a\n`GenerateContentResponse` or a status object. Inline requests For a small number of requests, you can directly embed the\n[`GenerateContentRequest`](/api/batch-mode#GenerateContentRequest) objects\nwithin your [`BatchGenerateContentRequest`](/api/batch-mode#request-body). The\nfollowing example calls the\n[`BatchGenerateContent`](/api/batch-mode#google.ai.generativelanguage.v1beta.BatchService.BatchGenerateContent)\nmethod with inline requests: Python`from google import genai from google.genai import types client = genai.Client() # A list of dictionaries, where each is a GenerateContentRequest inline_requests = [ { 'contents': [{ 'parts': [{'text': 'Tell me a one-sentence joke.'}], 'role': 'user' }] }, { 'contents': [{ 'parts': [{'text': 'Why is the sky blue?'}], 'role': 'user' }] } ] inline_batch_job = client.batches.create( model=\"gemini-3.8-flash\", src=inline_requests, config={ 'display_name': \"inlined-requests-job-1\", }, ) print(f\"Created batch job: {inline_batch_job.name}\")` 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.8-flash', src: inlinedRequests, config: { displayName: 'inlined-requests-job-1', } }); console.log(response);` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:batchGenerateContent \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-X POST \\\n-H \"Content-Type:application/json\" \\\n-d '{ \"batch\": { \"display_name\": \"my-batch-requests\", \"input_config\": { \"requests\": { \"requests\": [ { \"request\": {\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}]}, \"metadata\": { \"key\": \"request-1\" } }, { \"request\": {\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}]}, \"metadata\": { \"key\": \"request-2\" } } ] } } } }'` Input file For larger sets of requests, prepare a JSON Lines (JSONL) file. Each line in\nthis file must be a JSON object containing a user-defined key and a request\nobject, where the request is a valid\n[`GenerateContentRequest`](/api/batch-mode#GenerateContentRequest) object. The\nuser-defined key is used in the response to indicate which output is the result\nof which request. For example, the request with the key defined as `request-1`\nwill have its response annotated with the same key name. This file is uploaded using the [File API](/gemini-api/docs/files). The maximum\nallowed file size for an input file is 2GB. The following is an example of a JSONL file. You can save it in a file named\n`my-batch-requests.json`: `{\"key\": \"request-1\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}], \"generation_config\": {\"temperature\": 0.7}}} {\"key\": \"request-2\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"What are the main ingredients in a Margherita pizza?\"}]}]}}` Similarly to inline requests, you can specify other parameters like system\ninstructions, tools or other configurations in each request JSON. You can upload this file using the [File API](/gemini-api/docs/files) as\nshown in the following example. If\nyou are working with multimodal input, you can reference other uploaded files\nwithin your JSONL file. Python`import json from google import genai from google.genai import types client = genai.Client() # Create a sample JSONL file with open(\"my-batch-requests.jsonl\", \"w\") as f: requests = [ {\"key\": \"request-1\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}]}}, {\"key\": \"request-2\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"What are the main ingredients in a Margherita pizza?\"}]}]}} ] for req in requests: f.write(json.dumps(req) + \"\\n\") # Upload the file to the File API uploaded_file = client.files.upload( file='my-batch-requests.jsonl', config=types.UploadFileConfig(display_name='my-batch-requests', mime_type='jsonl') ) print(f\"Uploaded file: {uploaded_file.name}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; import * as fs from \"fs\"; import * as path from \"path\"; import { fileURLToPath } from 'url'; const ai = new GoogleGenAI({}); const fileName = \"my-batch-requests.jsonl\"; // Define the requests const requests = [ { \"key\": \"request-1\", \"request\": { \"contents\": [{ \"parts\": [{ \"text\": \"Describe the process of photosynthesis.\" }] }] } }, { \"key\": \"request-2\", \"request\": { \"contents\": [{ \"parts\": [{ \"text\": \"What are the main ingredients in a Margherita pizza?\" }] }] } } ]; // Construct the full path to file const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const filePath = path.join(__dirname, fileName); // __dirname is the directory of the current script async function writeBatchRequestsToFile(requests, filePath) { try { // Use a writable stream for efficiency, especially with larger files. const writeStream = fs.createWriteStream(filePath, { flags: 'w' }); writeStream.on('error', (err) => { console.error(`Error writing to file ${filePath}:`, err); }); for (const req of requests) { writeStream.write(JSON.stringify(req) + '\\n'); } writeStream.end(); console.log(`Successfully wrote batch requests to ${filePath}`); } catch (error) { // This catch block is for errors that might occur before stream setup, // stream errors are handled by the 'error' event. console.error(`An unexpected error occurred:`, error); } } // Write to a file. writeBatchRequestsToFile(requests, filePath); // Upload the file to the File API. const uploadedFile = await ai.files.upload({file: 'my-batch-requests.jsonl', config: { mimeType: 'jsonl', }}); console.log(uploadedFile.name);` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`tmp_batch_input_file=batch_input.tmp\necho -e '{\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}], \"generationConfig\": {\"temperature\": 0.7}}\\n{\"contents\": [{\"parts\": [{\"text\": \"What are the main ingredients in a Margherita pizza?\"}]}]}' > batch_input.tmp\nMIME_TYPE=$(file -b --mime-type \"${tmp_batch_input_file}\") NUM_BYTES=$(wc -c < \"${tmp_batch_input_file}\") DISPLAY_NAME=BatchInput\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files\" \\\n-D \"${tmp_header_file}\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H \"X-Goog-Upload-Protocol: resumable\" \\\n-H \"X-Goog-Upload-Command: start\" \\\n-H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\\n-H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\\n-H \"Content-Type: application/jsonl\" \\\n-d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\\n-H \"Content-Length: ${NUM_BYTES}\" \\\n-H \"X-Goog-Upload-Offset: 0\" \\\n-H \"X-Goog-Upload-Command: upload, finalize\" \\\n--data-binary \"@${tmp_batch_input_file}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json)` The following example calls the\n[`BatchGenerateContent`](/api/batch-mode#google.ai.generativelanguage.v1beta.BatchService.BatchGenerateContent)\nmethod with the input file uploaded using File API: Python`from google import genai # Assumes `uploaded_file` is the file object from the previous step client = genai.Client() file_batch_job = client.batches.create( model=\"gemini-3.8-flash\", src=uploaded_file.name, config={ 'display_name': \"file-upload-job-1\", }, ) print(f\"Created batch job: {file_batch_job.name}\")` JavaScript`// Assumes `uploadedFile` is the file object from the previous step const fileBatchJob = await ai.batches.create({ model: 'gemini-3.8-flash', src: uploadedFile.name, config: { displayName: 'file-upload-job-1', } }); console.log(fileBatchJob);` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`# Set the File ID taken from the upload response. BATCH_INPUT_FILE='files/123456'\ncurl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:batchGenerateContent \\\n-X POST \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H \"Content-Type:application/json\" \\\n-d \"{ 'batch': { 'display_name': 'my-batch-requests', 'input_config': { 'file_name': '${BATCH_INPUT_FILE}' } } }\"` When you create a batch job, you will get a job name returned. Use this name\nfor monitoring the job status as well as\nretrieving the results once the job completes. The following is an example output that contains a job name: `Created batch job from file: batches/123456789` Batch embedding support You can use the Batch API to interact with the\n[Embeddings model](/gemini-api/docs/embeddings) for higher throughput.\nTo create an embeddings batch job with either inline requests\nor input files, use the `batches.create_embeddings` API and\nspecify the embeddings model. Python`from google import genai client = genai.Client() # Creating an embeddings batch job with an input file request: file_job = client.batches.create_embeddings( model=\"gemini-embedding-2\", src={'file_name': uploaded_batch_requests.name}, config={'display_name': \"Input embeddings batch\"}, ) # Creating an embeddings batch job with an inline request: batch_job = client.batches.create_embeddings( model=\"gemini-embedding-2\", # For a predefined list of requests `inlined_requests` src={'inlined_requests': inlined_requests}, config={'display_name': \"Inlined embeddings batch\"}, )` JavaScript`// Creating an embeddings batch job with an input file request: let fileJob; fileJob = await client.batches.createEmbeddings({ model: 'gemini-embedding-2', src: {fileName: uploadedBatchRequests.name}, config: {displayName: 'Input embeddings batch'}, }); console.log(`Created batch job: ${fileJob.name}`); // Creating an embeddings batch job with an inline request: let batchJob; batchJob = await client.batches.createEmbeddings({ model: 'gemini-embedding-2', // For a predefined a list of requests `inlinedRequests` src: {inlinedRequests: inlinedRequests}, config: {displayName: 'Inlined embeddings batch'}, }); console.log(`Created batch job: ${batchJob.name}`);` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` Read the Embeddings section in the [Batch API cookbook](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb)\nfor more examples. Request configuration You can include any request configurations you would use in a standard non-batch\nrequest. For example, you could specify the temperature, system instructions or\neven pass in other modalities. The following example shows an example inline\nrequest that contains a system instruction for one of the requests: Python`inline_requests_list = [ {'contents': [{'parts': [{'text': 'Write a short poem about a cloud.'}]}]}, {'contents': [{ 'parts': [{ 'text': 'Write a short poem about a cat.' }] }], 'config': { 'system_instruction': {'parts': [{'text': 'You are a cat. Your name is Neko.'}]}} } ]` JavaScript`inlineRequestsList = [ {contents: [{parts: [{text: 'Write a short poem about a cloud.'}]}]}, {contents: [{parts: [{text: 'Write a short poem about a cat.'}]}], config: {systemInstruction: {parts: [{text: 'You are a cat. Your name is Neko.'}]}}} ]` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` Similarly can specify tools to use for a request. The following example\nshows a request that enables the [Google Search tool](/gemini-api/docs/google-search): Python`inlined_requests = [ {'contents': [{'parts': [{'text': 'Who won the euro 1998?'}]}]}, {'contents': [{'parts': [{'text': 'Who won the euro 2025?'}]}], 'config':{'tools': [{'google_search': {}}]}}]` JavaScript`inlineRequestsList = [ {contents: [{parts: [{text: 'Who won the euro 1998?'}]}]}, {contents: [{parts: [{text: 'Who won the euro 2025?'}]}], config: {tools: [{googleSearch: {}}]}} ]` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` You can specify [structured output](/gemini-api/docs/structured-output) as well.\nThe following example shows how to specify for your batch requests. Python`import time from google import genai from pydantic import BaseModel, TypeAdapter class Recipe(BaseModel): recipe_name: str ingredients: list[str] client = genai.Client() # A list of dictionaries, where each is a GenerateContentRequest inline_requests = [ { 'contents': [{ 'parts': [{'text': 'List a few popular cookie recipes, and include the amounts of ingredients.'}], 'role': 'user' }], 'config': { 'response_mime_type': 'application/json', 'response_schema': list[Recipe] } }, { 'contents': [{ 'parts': [{'text': 'List a few popular gluten free cookie recipes, and include the amounts of ingredients.'}], 'role': 'user' }], 'config': { 'response_mime_type': 'application/json', 'response_schema': list[Recipe] } } ] inline_batch_job = client.batches.create( model=\"gemini-3.8-flash\", src=inline_requests, config={ 'display_name': \"structured-output-job-1\" }, ) # wait for the job to finish job_name = inline_batch_job.name print(f\"Polling status for job: {job_name}\") while True: batch_job_inline = client.batches.get(name=job_name) if batch_job_inline.state.name in ('JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED'): break print(f\"Job not finished. Current state: {batch_job_inline.state.name}. Waiting 30 seconds...\") time.sleep(30) print(f\"Job finished with state: {batch_job_inline.state.name}\") # print the response for i, inline_response in enumerate(batch_job_inline.dest.inlined_responses, start=1): print(f\"\\n--- Response {i} ---\") # Check for a successful response if inline_response.response: # The .text property is a shortcut to the generated text. print(inline_response.response.text)` JavaScript`import {GoogleGenAI, Type} from '@google/genai'; const ai = new GoogleGenAI({}); const inlinedRequests = [ { contents: [{ parts: [{text: 'List a few popular cookie recipes, and include the amounts of ingredients.'}], role: 'user' }], config: { responseMimeType: 'application/json', responseSchema: { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { 'recipeName': { type: Type.STRING, description: 'Name of the recipe', nullable: false, }, 'ingredients': { type: Type.ARRAY, items: { type: Type.STRING, description: 'Ingredients of the recipe', nullable: false, }, }, }, required: ['recipeName'], }, }, } }, { contents: [{ parts: [{text: 'List a few popular gluten free cookie recipes, and include the amounts of ingredients.'}], role: 'user' }], config: { responseMimeType: 'application/json', responseSchema: { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { 'recipeName': { type: Type.STRING, description: 'Name of the recipe', nullable: false, }, 'ingredients': { type: Type.ARRAY, items: { type: Type.STRING, description: 'Ingredients of the recipe', nullable: false, }, }, }, required: ['recipeName'], }, }, } } ] const inlinedBatchJob = await ai.batches.create({ model: 'gemini-3.8-flash', src: inlinedRequests, config: { displayName: 'inlined-requests-job-1', } });` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` The following shows an example output of this job: `--- Response 1 --- [ { \"recipe_name\": \"Chocolate Chip Cookies\", \"ingredients\": [ \"1 cup (2 sticks) unsalted butter, softened\", \"3/4 cup granulated sugar\", \"3/4 cup packed light brown sugar\", \"1 large egg\", \"1 teaspoon vanilla extract\", \"2 1/4 cups all-purpose flour\", \"1 teaspoon baking soda\", \"1/2 teaspoon salt\", \"1 1/2 cups chocolate chips\" ] }, { \"recipe_name\": \"Oatmeal Raisin Cookies\", \"ingredients\": [ \"1 cup (2 sticks) unsalted butter, softened\", \"1 cup packed light brown sugar\", \"1/2 cup granulated sugar\", \"2 large eggs\", \"1 teaspoon vanilla extract\", \"1 1/2 cups all-purpose flour\", \"1 teaspoon baking soda\", \"1 teaspoon ground cinnamon\", \"1/2 teaspoon salt\", \"3 cups old-fashioned rolled oats\", \"1 cup raisins\" ] }, { \"recipe_name\": \"Sugar Cookies\", \"ingredients\": [ \"1 cup (2 sticks) unsalted butter, softened\", \"1 1/2 cups granulated sugar\", \"1 large egg\", \"1 teaspoon vanilla extract\", \"2 3/4 cups all-purpose flour\", \"1 teaspoon baking powder\", \"1/2 teaspoon salt\" ] } ] --- Response 2 --- [ { \"recipe_name\": \"Gluten-Free Chocolate Chip Cookies\", \"ingredients\": [ \"1 cup (2 sticks) unsalted butter, softened\", \"3/4 cup granulated sugar\", \"3/4 cup packed light brown sugar\", \"2 large eggs\", \"1 teaspoon vanilla extract\", \"2 1/4 cups gluten-free all-purpose flour blend (with xanthan gum)\", \"1 teaspoon baking soda\", \"1/2 teaspoon salt\", \"1 1/2 cups chocolate chips\" ] }, { \"recipe_name\": \"Gluten-Free Peanut Butter Cookies\", \"ingredients\": [ \"1 cup (250g) creamy peanut butter\", \"1/2 cup (100g) granulated sugar\", \"1/2 cup (100g) packed light brown sugar\", \"1 large egg\", \"1 teaspoon vanilla extract\", \"1/2 teaspoon baking soda\", \"1/4 teaspoon salt\" ] }, { \"recipe_name\": \"Gluten-Free Oatmeal Raisin Cookies\", \"ingredients\": [ \"1/2 cup (1 stick) unsalted butter, softened\", \"1/2 cup granulated sugar\", \"1/2 cup packed light brown sugar\", \"1 large egg\", \"1 teaspoon vanilla extract\", \"1 cup gluten-free all-purpose flour blend\", \"1/2 teaspoon baking soda\", \"1/2 teaspoon ground cinnamon\", \"1/4 teaspoon salt\", \"1 1/2 cups gluten-free rolled oats\", \"1/2 cup raisins\" ] } ]` Monitoring job status Use the operation name obtained when creating the batch job to poll its status.\nThe state field of the batch job will indicate its current status. A batch job\ncan be in one of the following states: `JOB_STATE_PENDING`: The job has been created and is waiting to be processed by the service. `JOB_STATE_RUNNING`: The job is in progress. `JOB_STATE_SUCCEEDED`: The job completed successfully. You can now retrieve the results. `JOB_STATE_FAILED`: The job failed. Check the error details for more information. `JOB_STATE_CANCELLED`: The job was cancelled by the user. `JOB_STATE_EXPIRED`: The job has expired because it was running or pending\nfor more than 48 hours. The job will not have any results to retrieve.\nYou can try submitting the job again or splitting up\nthe requests into smaller batches. You can poll the job status periodically to check for completion. Python`import time from google import genai client = genai.Client() # Use the name of the job you want to check # e.g., inline_batch_job.name from the previous step job_name = \"YOUR_BATCH_JOB_NAME\" # (e.g. 'batches/your-batch-id') batch_job = client.batches.get(name=job_name) completed_states = set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]) print(f\"Polling status for job: {job_name}\") batch_job = client.batches.get(name=job_name) # Initial get while batch_job.state.name not in completed_states: print(f\"Current state: {batch_job.state.name}\") time.sleep(30) # Wait for 30 seconds before polling again batch_job = client.batches.get(name=job_name) print(f\"Job finished with state: {batch_job.state.name}\") if batch_job.state.name == 'JOB_STATE_FAILED': print(f\"Error: {batch_job.error}\")` JavaScript`// Use the name of the job you want to check // e.g., inlinedBatchJob.name from the previous step let batchJob; const completedStates = new Set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]); try { batchJob = await ai.batches.get({name: inlinedBatchJob.name}); while (!completedStates.has(batchJob.state)) { console.log(`Current state: ${batchJob.state}`); // Wait for 30 seconds before polling again await new Promise(resolve => setTimeout(resolve, 30000)); batchJob = await client.batches.get({ name: batchJob.name }); } console.log(`Job finished with state: ${batchJob.state}`); if (batchJob.state === 'JOB_STATE_FAILED') { // The exact structure of `error` might vary depending on the SDK // This assumes `error` is an object with a `message` property. console.error(`Error: ${batchJob.state}`); } } catch (error) { console.error(`An error occurred while polling job ${batchJob.name}:`, error); }` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` Polling and webhooks **Tired of polling?** Gemini now supports\n[Webhooks](/gemini-api/docs/webhooks) for processing completions asynchronously.\nInstead of continuously calling `GET / operations`, subscribe to\n`batch.succeeded` directly to allow the Gemini API to push real-time\nnotifications to your server when asynchronous or long-running operations\ncomplete. Python`from google import genai client = genai.Client() webhook = client.webhooks.create( name=\"MyBatchWebhook\", subscribed_events=[\"batch.succeeded\", \"batch.failed\"], uri=\"https://my-api.com/gemini-callback\", ) print(f\"Created webhook: {webhook.name}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI(); async function createWebhook() { const webhook = await client.webhooks.create({ name: \"MyBatchWebhook\", subscribed_events: [\"batch.succeeded\", \"batch.failed\"], uri: \"https://my-api.com/gemini-callback\", }); console.log(`Created webhook: ${webhook.name}`); } createWebhook();` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`curl -X POST \\ \"https://generativelanguage.googleapis.com/v1/webhooks?webhook_id=my-example-webhook-123\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GOOGLE_API_KEY\" \\ -d '{ \"name\": \"My Example Webhook\", \"uri\": \"https://my-api.com/gemini-callback\", \"subscribed_events\": [\"batch.succeeded\", \"batch.failed\"] }'` Retrieving results Once the job status indicates your batch job has succeeded, the results are\navailable in the `response` field.\nBy default, batch job results are stored and available for download for 6 weeks,\nbefore they are permanently deleted. Python`import json from google import genai client = genai.Client() # Use the name of the job you want to check # e.g., inline_batch_job.name from the previous step job_name = \"YOUR_BATCH_JOB_NAME\" batch_job = client.batches.get(name=job_name) if batch_job.state.name == 'JOB_STATE_SUCCEEDED': # If batch job was created with a file if batch_job.dest and batch_job.dest.file_name: # Results are in a file result_file_name = batch_job.dest.file_name print(f\"Results are in file: {result_file_name}\") print(\"Downloading result file content...\") file_content = client.files.download(file=result_file_name) # Process file_content (bytes) as needed print(file_content.decode('utf-8')) # If batch job was created with inline request # (for embeddings, use batch_job.dest.inlined_embed_content_responses) elif batch_job.dest and batch_job.dest.inlined_responses: # Results are inline print(\"Results are inline:\") for i, inline_response in enumerate(batch_job.dest.inlined_responses): print(f\"Response {i+1}:\") if inline_response.response: # Accessing response, structure may vary. try: print(inline_response.response.text) except AttributeError: print(inline_response.response) # Fallback elif inline_response.error: print(f\"Error: {inline_response.error}\") else: print(\"No results found (neither file nor inline).\") else: print(f\"Job did not succeed. Final state: {batch_job.state.name}\") if batch_job.error: print(f\"Error: {batch_job.error}\")` JavaScript`// Use the name of the job you want to check // e.g., inlinedBatchJob.name from the previous step const jobName = \"YOUR_BATCH_JOB_NAME\"; try { const batchJob = await ai.batches.get({ name: jobName }); if (batchJob.state === 'JOB_STATE_SUCCEEDED') { console.log('Found completed batch:', batchJob.displayName); console.log(batchJob); // If batch job was created with a file destination if (batchJob.dest?.fileName) { const resultFileName = batchJob.dest.fileName; console.log(`Results are in file: ${resultFileName}`); console.log(\"Downloading result file content...\"); const fileContentBuffer = await ai.files.download({ file: resultFileName }); // Process fileContentBuffer (Buffer) as needed console.log(fileContentBuffer.toString('utf-8')); } // If batch job was created with inline responses else if (batchJob.dest?.inlinedResponses) { console.log(\"Results are inline:\"); for (let i = 0; i < batchJob.dest.inlinedResponses.length; i++) { const inlineResponse = batchJob.dest.inlinedResponses[i]; console.log(`Response ${i + 1}:`); if (inlineResponse.response) { // Accessing response, structure may vary. if (inlineResponse.response.text !== undefined) { console.log(inlineResponse.response.text); } else { console.log(inlineResponse.response); // Fallback } } else if (inlineResponse.error) { console.error(`Error: ${inlineResponse.error}`); } } } // If batch job was an embedding batch with inline responses else if (batchJob.dest?.inlinedEmbedContentResponses) { console.log(\"Embedding results found inline:\"); for (let i = 0; i < batchJob.dest.inlinedEmbedContentResponses.length; i++) { const inlineResponse = batchJob.dest.inlinedEmbedContentResponses[i]; console.log(`Response ${i + 1}:`); if (inlineResponse.response) { console.log(inlineResponse.response); } else if (inlineResponse.error) { console.error(`Error: ${inlineResponse.error}`); } } } else { console.log(\"No results found (neither file nor inline).\"); } } else { console.log(`Job did not succeed. Final state: ${batchJob.state}`); if (batchJob.error) { console.error(`Error: ${typeof batchJob.error === 'string' ? batchJob.error : batchJob.error.message || JSON.stringify(batchJob.error)}`); } } } catch (error) { console.error(`An error occurred while processing job ${jobName}:`, error); }` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`BATCH_NAME=\"batches/123456\" # Your batch job name\n\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H \"Content-Type:application/json\" 2> /dev/null > batch_status.json\n\nif jq -r '.done' batch_status.json | grep -q \"false\"; then echo \"Batch has not finished processing\" fi batch_state=$(jq -r '.metadata.state' batch_status.json) if [[ $batch_state = \"JOB_STATE_SUCCEEDED\" ]]; then if [[ $(jq '.response | has(\"inlinedResponses\")' batch_status.json) = \"true\" ]]; then jq -r '.response.inlinedResponses' batch_status.json\n exit fi responses_file_name=$(jq -r '.response.responsesFile' batch_status.json) curl https://generativelanguage.googleapis.com/download/v1beta/$responses_file_name:download?alt=media \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" 2> /dev/null\nelif [[ $batch_state = \"JOB_STATE_FAILED\" ]]; then jq '.error' batch_status.json\nelif [[ $batch_state == \"JOB_STATE_CANCELLED\" ]]; then echo \"Batch was cancelled by the user\" elif [[ $batch_state == \"JOB_STATE_EXPIRED\" ]]; then echo \"Batch expired after 48 hours\" fi` Listing batch jobs You can list your recent batch jobs. Python`batch_jobs = client.batches.list() # Optional query config: # batch_jobs = client.batches.list(config={'page_size': 5}) for batch_job in batch_jobs: print(batch_job)` JavaScript`const batchJobs = await ai.batches.list(); // Optional query config: // const batchJobs = await ai.batches.list({config: {'pageSize': 5}}); for await (const batchJob of batchJobs) { console.log(batchJob); }` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`curl https://generativelanguage.googleapis.com/v1beta/batches \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\"` Cancelling a batch job You can cancel an ongoing batch job using its name. When a job is\ncanceled, it stops processing new requests. Python`client.batches.cancel(name=batch_job_to_cancel.name)` JavaScript`await ai.batches.cancel({name: batchJobToCancel.name});` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`BATCH_NAME=\"batches/123456\" # Your batch job name # Cancel the batch\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME:cancel \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\ # Confirm that the status of the batch after cancellation is JOB_STATE_CANCELLED\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H \"Content-Type:application/json\" 2> /dev/null | jq -r '.metadata.state'` Deleting a batch job You can delete an existing batch job using its name. When a job is\ndeleted, it stops processing new requests and is removed from the list of\nbatch jobs. Python`client.batches.delete(name=batch_job_to_delete.name)` JavaScript`await ai.batches.delete({name: batchJobToDelete.name});` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`BATCH_NAME=\"batches/123456\" # Your batch job name # Delete the batch job\ncurl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\"` Generating images in batch If you're using [Gemini Nano Banana](/gemini-api/docs/image-generation) and need to generate a lot\nof images, you can use the Batch API to get higher\n[rate limits](/gemini-api/docs/rate-limits) in exchange for a turnaround of up\nto 24 hours. You can either use inline requests for small batches of requests (under 20MB) or\na JSONL input file for large batches (recommended for image generation): Inline requests for images Python`import time import base64 import json from google import genai from google.genai import types from PIL import Image client = genai.Client() # 1. Create batch job with inline requests inline_requests = [ { 'contents': [{'parts': [{'text': 'A big letter A surrounded by animals starting with the A letter'}]}], 'config': {'response_modalities': ['TEXT', 'IMAGE']} }, { 'contents': [{'parts': [{'text': 'A big letter B surrounded by animals starting with the B letter'}]}], 'config': {'response_modalities': ['TEXT', 'IMAGE']} } ] inline_batch_job = client.batches.create( model=\"gemini-3-pro-image-preview\", src=inline_requests, config={ 'display_name': \"inlined-image-requests-job-1\", }, ) print(f\"Created batch job: {inline_batch_job.name}\") # 2. Monitor job status job_name = inline_batch_job.name print(f\"Polling status for job: {job_name}\") completed_states = set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]) batch_job = client.batches.get(name=job_name) # Initial get while batch_job.state.name not in completed_states: print(f\"Current state: {batch_job.state.name}\") time.sleep(10) # Wait for 10 seconds before polling again batch_job = client.batches.get(name=job_name) print(f\"Job finished with state: {batch_job.state.name}\") # 3. Retrieve results if batch_job.state.name == 'JOB_STATE_SUCCEEDED': print(\"Results are inline:\") for i, inline_response in enumerate(batch_job.dest.inlined_responses): print(f\"Response {i+1}:\") if inline_response.response: for part in inline_response.response.candidates[0].content.parts: if part.text: print(part.text) elif part.inline_data: print(f\"Image mime type: {part.inline_data.mime_type}\") image = part.as_image() image.save(f\"image_{i+1}.png\") elif inline_response.error: print(f\"Error: {inline_response.error}\") elif batch_job.state.name == 'JOB_STATE_FAILED': print(f\"Error: {batch_job.error}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI({}); async function run() { // 1. Create batch job with inline requests const inlinedRequests = [ { contents: [{parts: [{text: 'A big letter A surrounded by animals starting with the A letter'}]}], config: {responseModalities: ['TEXT', 'IMAGE']} }, { contents: [{parts: [{text: 'A big letter B surrounded by animals starting with the B letter'}]}], config: {responseModalities: ['TEXT', 'IMAGE']} } ] const inlineBatchJob = await ai.batches.create({ model: 'gemini-3-pro-image-preview', src: inlinedRequests, config: { displayName: 'inlined-image-requests-job-1', } }); console.log(inlineBatchJob); // 2. Monitor job status let batchJob; const completedStates = new Set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]); try { batchJob = await ai.batches.get({name: inlineBatchJob.name}); while (!completedStates.has(batchJob.state)) { console.log(`Current state: ${batchJob.state}`); // Wait for 10 seconds before polling again await new Promise(resolve => setTimeout(resolve, 10000)); batchJob = await ai.batches.get({ name: batchJob.name }); } console.log(`Job finished with state: ${batchJob.state}`); } catch (error) { console.error(`An error occurred while polling job ${inlineBatchJob.name}:`, error); return; } // 3. Retrieve results if (batchJob.state === 'JOB_STATE_SUCCEEDED') { if (batchJob.dest?.inlinedResponses) { console.log(\"Results are inline:\"); for (let i = 0; i < batchJob.dest.inlinedResponses.length; i++) { const inlineResponse = batchJob.dest.inlinedResponses[i]; console.log(`Response ${i + 1}:`); if (inlineResponse.response) { for (const part of inlineResponse.response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { console.log(`Image mime type: ${part.inlineData.mimeType}`); } } } else if (inlineResponse.error) { console.error(`Error: ${inlineResponse.error}`); } } } else { console.log(\"No inline results found.\"); } } else if (batchJob.state === 'JOB_STATE_FAILED') { console.error(`Error: ${typeof batchJob.error === 'string' ? batchJob.error : batchJob.error.message || JSON.stringify(batchJob.error)}`); } } run();` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`# 1. Create batch job printf -v request_data '{ \"batch\": { \"display_name\": \"my-batch-image-requests\", \"input_config\": { \"requests\": { \"requests\": [ { \"request\": { \"contents\": [{\"parts\": [{\"text\": \"A big letter A surrounded by animals starting with the A letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]} }, \"metadata\": { \"key\": \"request-1\" } }, { \"request\": { \"contents\": [{\"parts\": [{\"text\": \"A big letter B surrounded by animals starting with the B letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]} }, \"metadata\": { \"key\": \"request-2\" } } ] } } } }'\ncurl https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:batchGenerateContent \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -X POST \\ -H \"Content-Type:application/json\" \\ -d \"$request_data\" > created_batch.json\n\nBATCH_NAME=$(jq -r '.name' created_batch.json) echo \"Created batch job: $BATCH_NAME\" # 2. Poll job status until completion by repeating the following command # Replace $BATCH_NAME with the name returned above.\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type:application/json\" > batch_status.json\n\necho \"Current status:\"\njq '.' batch_status.json\n\n# 3. If state is JOB_STATE_SUCCEEDED, retrieve results from batch_status.json batch_state=$(jq -r '.state' batch_status.json) if [[ $batch_state = \"JOB_STATE_SUCCEEDED\" ]]; then echo \"Job succeeded. Results:\" jq -r '.dest.inlinedResponses' batch_status.json\nfi` Input file for images Python`import json import time import base64 from google import genai from google.genai import types from PIL import Image client = genai.Client() # 1. Create and upload file file_name = \"my-batch-image-requests.jsonl\" with open(file_name, \"w\") as f: requests = [ {\"key\": \"request-1\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"A big letter A surrounded by animals starting with the A letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}}}, {\"key\": \"request-2\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"A big letter B surrounded by animals starting with the B letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}}} ] for req in requests: f.write(json.dumps(req) + \"\\n\") uploaded_file = client.files.upload( file=file_name, config=types.UploadFileConfig(display_name='my-batch-image-requests', mime_type='jsonl') ) print(f\"Uploaded file: {uploaded_file.name}\") # 2. Create batch job file_batch_job = client.batches.create( model=\"gemini-3-pro-image-preview\", src=uploaded_file.name, config={ 'display_name': \"file-image-upload-job-1\", }, ) print(f\"Created batch job: {file_batch_job.name}\") # 3. Monitor job status job_name = file_batch_job.name print(f\"Polling status for job: {job_name}\") completed_states = set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]) batch_job = client.batches.get(name=job_name) # Initial get while batch_job.state.name not in completed_states: print(f\"Current state: {batch_job.state.name}\") time.sleep(10) # Wait for 10 seconds before polling again batch_job = client.batches.get(name=job_name) print(f\"Job finished with state: {batch_job.state.name}\") # 4. Retrieve results if batch_job.state.name == 'JOB_STATE_SUCCEEDED': result_file_name = batch_job.dest.file_name print(f\"Results are in file: {result_file_name}\") print(\"Downloading result file content...\") file_content_bytes = client.files.download(file=result_file_name) file_content = file_content_bytes.decode('utf-8') # The result file is also a JSONL file. Parse and print each line. for line in file_content.splitlines(): if line: parsed_response = json.loads(line) if 'response' in parsed_response and parsed_response['response']: for part in parsed_response['response']['candidates'][0]['content']['parts']: if part.get('text'): print(part['text']) elif part.get('inlineData'): print(f\"Image mime type: {part['inlineData']['mimeType']}\") data = base64.b64decode(part['inlineData']['data']) elif 'error' in parsed_response: print(f\"Error: {parsed_response['error']}\") elif batch_job.state.name == 'JOB_STATE_FAILED': print(f\"Error: {batch_job.error}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; import * as fs from \"fs\"; import * as path from \"path\"; import { fileURLToPath } from 'url'; const ai = new GoogleGenAI({}); async function run() { // 1. Create and upload file const fileName = \"my-batch-image-requests.jsonl\"; const requests = [ { \"key\": \"request-1\", \"request\": { \"contents\": [{ \"parts\": [{ \"text\": \"A big letter A surrounded by animals starting with the A letter\" }] }], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]} } }, { \"key\": \"request-2\", \"request\": { \"contents\": [{ \"parts\": [{ \"text\": \"A big letter B surrounded by animals starting with the B letter\" }] }], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]} } } ]; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const filePath = path.join(__dirname, fileName); try { const writeStream = fs.createWriteStream(filePath, { flags: 'w' }); for (const req of requests) { writeStream.write(JSON.stringify(req) + '\\n'); } writeStream.end(); console.log(`Successfully wrote batch requests to ${filePath}`); } catch (error) { console.error(`An unexpected error occurred writing file:`, error); return; } const uploadedFile = await ai.files.upload({file: fileName, config: { mimeType: 'jsonl' }}); console.log(`Uploaded file: ${uploadedFile.name}`); // 2. Create batch job const fileBatchJob = await ai.batches.create({ model: 'gemini-3-pro-image-preview', src: uploadedFile.name, config: { displayName: 'file-image-upload-job-1', } }); console.log(fileBatchJob); // 3. Monitor job status let batchJob; const completedStates = new Set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]); try { batchJob = await ai.batches.get({name: fileBatchJob.name}); while (!completedStates.has(batchJob.state)) { console.log(`Current state: ${batchJob.state}`); // Wait for 10 seconds before polling again await new Promise(resolve => setTimeout(resolve, 10000)); batchJob = await ai.batches.get({ name: batchJob.name }); } console.log(`Job finished with state: ${batchJob.state}`); } catch (error) { console.error(`An error occurred while polling job ${fileBatchJob.name}:`, error); return; } // 4. Retrieve results if (batchJob.state === 'JOB_STATE_SUCCEEDED') { if (batchJob.dest?.fileName) { const resultFileName = batchJob.dest.fileName; console.log(`Results are in file: ${resultFileName}`); console.log(\"Downloading result file content...\"); const fileContentBuffer = await ai.files.download({ file: resultFileName }); const fileContent = fileContentBuffer.toString('utf-8'); for (const line of fileContent.split('\\n')) { if (line) { const parsedResponse = JSON.parse(line); if (parsedResponse.response) { for (const part of parsedResponse.response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { console.log(`Image mime type: ${part.inlineData.mimeType}`); } } } else if (parsedResponse.error) { console.error(`Error: ${parsedResponse.error}`); } } } } else { console.log(\"No result file found.\"); } } else if (batchJob.state === 'JOB_STATE_FAILED') { console.error(`Error: ${typeof batchJob.error === 'string' ? batchJob.error : batchJob.error.message || JSON.stringify(batchJob.error)}`); } } run();` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`# 1. Create and upload file echo '{\"key\": \"request-1\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"A big letter A surrounded by animals starting with the A letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}}}' > my-batch-image-requests.jsonl\necho '{\"key\": \"request-2\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"A big letter B surrounded by animals starting with the B letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}}}' >> my-batch-image-requests.jsonl\n\n# Follow File API guide to upload: https://ai.google.dev/gemini-api/docs/files#upload_a_file # This example assumes you have uploaded the file and set BATCH_INPUT_FILE to its name (e.g., files/abcdef123) BATCH_INPUT_FILE=\"files/your-uploaded-file-name\" # 2. Create batch job printf -v request_data '{ \"batch\": { \"display_name\": \"my-batch-file-image-requests\", \"input_config\": { \"file_name\": \"%s\" } } }' \"$BATCH_INPUT_FILE\"\ncurl https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:batchGenerateContent \\ -X POST \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type:application/json\" \\ -d \"$request_data\" > created_batch.json\n\nBATCH_NAME=$(jq -r '.name' created_batch.json) echo \"Created batch job: $BATCH_NAME\" # 3. Poll job status until completion by repeating the following command:\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type:application/json\" > batch_status.json\n\necho \"Current status:\"\njq '.' batch_status.json\n\n# 4. If state is JOB_STATE_SUCCEEDED, download results file batch_state=$(jq -r '.state' batch_status.json) if [[ $batch_state = \"JOB_STATE_SUCCEEDED\" ]]; then responses_file_name=$(jq -r '.dest.fileName' batch_status.json) echo \"Job succeeded. Downloading results from $responses_file_name...\" curl https://generativelanguage.googleapis.com/download/v1beta/$responses_file_name:download?alt=media \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" > batch_results.jsonl\n echo \"Results saved to batch_results.jsonl\" fi` Technical details **Supported models:** Batch API supports a range of Gemini models.\nRefer to the [Models page](/gemini-api/docs/models) for each model's support\nof Batch API. The supported modalities for Batch API are the same\nas what's supported on the interactive (or non-batch) API. **Pricing:** Batch API usage is priced at 50% of the standard interactive\nAPI cost for the equivalent model. See the [pricing page](/gemini-api/docs/pricing)\nfor details. Refer to the [rate limits page](/gemini-api/docs/rate-limits#batch-mode)\nfor details on rate limits for this feature. **Service level objective (SLO):** Batch jobs are designed to complete\nwithin a 24-hour turnaround time. Many jobs may complete much faster\ndepending on their size and current system load. **Caching:** [Context caching](/gemini-api/docs/caching) is supported\nfor batch requests. Reuse cached content by specifying the `cached_content`\nresource name in the configuration of individual requests within your batch.\nIf a request in your batch results in a cache hit, you pay the\n[standard context caching rates](/gemini-api/docs/pricing). Best practices **Use input files for large requests:** For a large number of requests,\nalways use the file input\nmethod for better manageability and to avoid hitting request size limits for\nthe [`BatchGenerateContent`](/api/batch-mode#google.ai.generativelanguage.v1beta.BatchService.BatchGenerateContent)\ncall itself. Note that there's a 2GB file size limit per input file. **Error handling:** Check the `batchStats` for `failedRequestCount` after a\njob completes. If using file output, parse each line to check if it's a\n`GenerateContentResponse` or a status object indicating an error for that\nspecific request. See the [troubleshooting\nguide](/gemini-api/docs/troubleshooting#error-codes) for a complete set of\nerror codes. **Submit jobs once:** The creation of a batch job is not idempotent.\nIf you send the same creation request twice, two separate batch jobs will\nbe created. **Break up very large batches:** While the target turnaround time is 24\nhours, actual processing time can vary based on system load and job size.\nFor large jobs, consider breaking them into smaller\nbatches if intermediate results are needed sooner. What's next Check out the [Batch API notebook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb)\nfor more examples. The OpenAI compatibility layer supports Batch API. Read the examples on the\n[OpenAI Compatibility](/gemini-api/docs/openai#batch) page. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 52716, "slov": 6233, "odkazu": 142, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:39", "sha256": "00e00e0f4e5279f01c6fe708f06399c9343f3d607f5ac7a2da758520c946473c", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://jsonlines.org/", "https://github.com/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/batch-mode", "titulek": "Batch API | Gemini API | Google AI for Developers", "h1": "Batch API", "popis": "Get started building with the Batch API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/batch-api", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Batch API  |  Gemini API  |  Google AI for Developers", "og:description": "Get started building with the Batch API", "og:url": "https://ai.google.dev/gemini-api/docs/batch-api", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Batch API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Batch API", "item": "https://ai.google.dev/gemini-api/docs/batch-api"}]}], "drobecky": ["Gemini API", "Batch API"], "osnova": [{"uroven": 1, "text": "Batch API"}, {"uroven": 2, "text": "Creating a batch job"}, {"uroven": 3, "text": "Inline requests"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Input file"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Batch embedding support"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Request configuration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Monitoring job status"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Polling and webhooks"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Retrieving results"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Listing batch jobs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Cancelling a batch job"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Deleting a batch job"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Generating images in batch"}, {"uroven": 3, "text": "Inline requests for images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Input file for images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Technical details"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "What's next"}], "markdown": "Batch API The Gemini Batch API is designed to process large volumes of requests\nasynchronously at [50% of the standard cost](/gemini-api/docs/pricing).\nThe target turnaround time is 24 hours, but in majority of cases, it is much\nquicker. Use Batch API for large-scale, non-urgent tasks such as data\npre-processing or running evaluations where an immediate response is not\nrequired. Creating a batch job You have two ways to submit your requests in Batch API: **Inline requests:** A list of\n[`GenerateContentRequest`](/api/batch-mode#GenerateContentRequest) objects\ndirectly included in your batch creation request. This is suitable for\nsmaller batches that keep the total request size under 20MB. The **output**\nreturned from the model is a list of `inlineResponse` objects. **Input file:** A [JSON Lines (JSONL)](https://jsonlines.org/)\nfile where each line contains a complete\n[`GenerateContentRequest`](/api/batch-mode#GenerateContentRequest) object.\nThis method is recommended for larger requests. The **output**\nreturned from the model is a JSONL file where each line is either a\n`GenerateContentResponse` or a status object. Inline requests For a small number of requests, you can directly embed the\n[`GenerateContentRequest`](/api/batch-mode#GenerateContentRequest) objects\nwithin your [`BatchGenerateContentRequest`](/api/batch-mode#request-body). The\nfollowing example calls the\n[`BatchGenerateContent`](/api/batch-mode#google.ai.generativelanguage.v1beta.BatchService.BatchGenerateContent)\nmethod with inline requests: Python`from google import genai from google.genai import types client = genai.Client() # A list of dictionaries, where each is a GenerateContentRequest inline_requests = [ { 'contents': [{ 'parts': [{'text': 'Tell me a one-sentence joke.'}], 'role': 'user' }] }, { 'contents': [{ 'parts': [{'text': 'Why is the sky blue?'}], 'role': 'user' }] } ] inline_batch_job = client.batches.create( model=\"gemini-3.8-flash\", src=inline_requests, config={ 'display_name': \"inlined-requests-job-1\", }, ) print(f\"Created batch job: {inline_batch_job.name}\")` 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.8-flash', src: inlinedRequests, config: { displayName: 'inlined-requests-job-1', } }); console.log(response);` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:batchGenerateContent \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-X POST \\\n-H \"Content-Type:application/json\" \\\n-d '{ \"batch\": { \"display_name\": \"my-batch-requests\", \"input_config\": { \"requests\": { \"requests\": [ { \"request\": {\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}]}, \"metadata\": { \"key\": \"request-1\" } }, { \"request\": {\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}]}, \"metadata\": { \"key\": \"request-2\" } } ] } } } }'` Input file For larger sets of requests, prepare a JSON Lines (JSONL) file. Each line in\nthis file must be a JSON object containing a user-defined key and a request\nobject, where the request is a valid\n[`GenerateContentRequest`](/api/batch-mode#GenerateContentRequest) object. The\nuser-defined key is used in the response to indicate which output is the result\nof which request. For example, the request with the key defined as `request-1`\nwill have its response annotated with the same key name. This file is uploaded using the [File API](/gemini-api/docs/files). The maximum\nallowed file size for an input file is 2GB. The following is an example of a JSONL file. You can save it in a file named\n`my-batch-requests.json`: `{\"key\": \"request-1\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}], \"generation_config\": {\"temperature\": 0.7}}} {\"key\": \"request-2\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"What are the main ingredients in a Margherita pizza?\"}]}]}}` Similarly to inline requests, you can specify other parameters like system\ninstructions, tools or other configurations in each request JSON. You can upload this file using the [File API](/gemini-api/docs/files) as\nshown in the following example. If\nyou are working with multimodal input, you can reference other uploaded files\nwithin your JSONL file. Python`import json from google import genai from google.genai import types client = genai.Client() # Create a sample JSONL file with open(\"my-batch-requests.jsonl\", \"w\") as f: requests = [ {\"key\": \"request-1\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}]}}, {\"key\": \"request-2\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"What are the main ingredients in a Margherita pizza?\"}]}]}} ] for req in requests: f.write(json.dumps(req) + \"\\n\") # Upload the file to the File API uploaded_file = client.files.upload( file='my-batch-requests.jsonl', config=types.UploadFileConfig(display_name='my-batch-requests', mime_type='jsonl') ) print(f\"Uploaded file: {uploaded_file.name}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; import * as fs from \"fs\"; import * as path from \"path\"; import { fileURLToPath } from 'url'; const ai = new GoogleGenAI({}); const fileName = \"my-batch-requests.jsonl\"; // Define the requests const requests = [ { \"key\": \"request-1\", \"request\": { \"contents\": [{ \"parts\": [{ \"text\": \"Describe the process of photosynthesis.\" }] }] } }, { \"key\": \"request-2\", \"request\": { \"contents\": [{ \"parts\": [{ \"text\": \"What are the main ingredients in a Margherita pizza?\" }] }] } } ]; // Construct the full path to file const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const filePath = path.join(__dirname, fileName); // __dirname is the directory of the current script async function writeBatchRequestsToFile(requests, filePath) { try { // Use a writable stream for efficiency, especially with larger files. const writeStream = fs.createWriteStream(filePath, { flags: 'w' }); writeStream.on('error', (err) => { console.error(`Error writing to file ${filePath}:`, err); }); for (const req of requests) { writeStream.write(JSON.stringify(req) + '\\n'); } writeStream.end(); console.log(`Successfully wrote batch requests to ${filePath}`); } catch (error) { // This catch block is for errors that might occur before stream setup, // stream errors are handled by the 'error' event. console.error(`An unexpected error occurred:`, error); } } // Write to a file. writeBatchRequestsToFile(requests, filePath); // Upload the file to the File API. const uploadedFile = await ai.files.upload({file: 'my-batch-requests.jsonl', config: { mimeType: 'jsonl', }}); console.log(uploadedFile.name);` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`tmp_batch_input_file=batch_input.tmp\necho -e '{\"contents\": [{\"parts\": [{\"text\": \"Describe the process of photosynthesis.\"}]}], \"generationConfig\": {\"temperature\": 0.7}}\\n{\"contents\": [{\"parts\": [{\"text\": \"What are the main ingredients in a Margherita pizza?\"}]}]}' > batch_input.tmp\nMIME_TYPE=$(file -b --mime-type \"${tmp_batch_input_file}\") NUM_BYTES=$(wc -c < \"${tmp_batch_input_file}\") DISPLAY_NAME=BatchInput\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files\" \\\n-D \"${tmp_header_file}\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H \"X-Goog-Upload-Protocol: resumable\" \\\n-H \"X-Goog-Upload-Command: start\" \\\n-H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\\n-H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\\n-H \"Content-Type: application/jsonl\" \\\n-d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\\n-H \"Content-Length: ${NUM_BYTES}\" \\\n-H \"X-Goog-Upload-Offset: 0\" \\\n-H \"X-Goog-Upload-Command: upload, finalize\" \\\n--data-binary \"@${tmp_batch_input_file}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json)` The following example calls the\n[`BatchGenerateContent`](/api/batch-mode#google.ai.generativelanguage.v1beta.BatchService.BatchGenerateContent)\nmethod with the input file uploaded using File API: Python`from google import genai # Assumes `uploaded_file` is the file object from the previous step client = genai.Client() file_batch_job = client.batches.create( model=\"gemini-3.8-flash\", src=uploaded_file.name, config={ 'display_name': \"file-upload-job-1\", }, ) print(f\"Created batch job: {file_batch_job.name}\")` JavaScript`// Assumes `uploadedFile` is the file object from the previous step const fileBatchJob = await ai.batches.create({ model: 'gemini-3.8-flash', src: uploadedFile.name, config: { displayName: 'file-upload-job-1', } }); console.log(fileBatchJob);` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`# Set the File ID taken from the upload response. BATCH_INPUT_FILE='files/123456'\ncurl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:batchGenerateContent \\\n-X POST \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H \"Content-Type:application/json\" \\\n-d \"{ 'batch': { 'display_name': 'my-batch-requests', 'input_config': { 'file_name': '${BATCH_INPUT_FILE}' } } }\"` When you create a batch job, you will get a job name returned. Use this name\nfor monitoring the job status as well as\nretrieving the results once the job completes. The following is an example output that contains a job name: `Created batch job from file: batches/123456789` Batch embedding support You can use the Batch API to interact with the\n[Embeddings model](/gemini-api/docs/embeddings) for higher throughput.\nTo create an embeddings batch job with either inline requests\nor input files, use the `batches.create_embeddings` API and\nspecify the embeddings model. Python`from google import genai client = genai.Client() # Creating an embeddings batch job with an input file request: file_job = client.batches.create_embeddings( model=\"gemini-embedding-2\", src={'file_name': uploaded_batch_requests.name}, config={'display_name': \"Input embeddings batch\"}, ) # Creating an embeddings batch job with an inline request: batch_job = client.batches.create_embeddings( model=\"gemini-embedding-2\", # For a predefined list of requests `inlined_requests` src={'inlined_requests': inlined_requests}, config={'display_name': \"Inlined embeddings batch\"}, )` JavaScript`// Creating an embeddings batch job with an input file request: let fileJob; fileJob = await client.batches.createEmbeddings({ model: 'gemini-embedding-2', src: {fileName: uploadedBatchRequests.name}, config: {displayName: 'Input embeddings batch'}, }); console.log(`Created batch job: ${fileJob.name}`); // Creating an embeddings batch job with an inline request: let batchJob; batchJob = await client.batches.createEmbeddings({ model: 'gemini-embedding-2', // For a predefined a list of requests `inlinedRequests` src: {inlinedRequests: inlinedRequests}, config: {displayName: 'Inlined embeddings batch'}, }); console.log(`Created batch job: ${batchJob.name}`);` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` Read the Embeddings section in the [Batch API cookbook](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb)\nfor more examples. Request configuration You can include any request configurations you would use in a standard non-batch\nrequest. For example, you could specify the temperature, system instructions or\neven pass in other modalities. The following example shows an example inline\nrequest that contains a system instruction for one of the requests: Python`inline_requests_list = [ {'contents': [{'parts': [{'text': 'Write a short poem about a cloud.'}]}]}, {'contents': [{ 'parts': [{ 'text': 'Write a short poem about a cat.' }] }], 'config': { 'system_instruction': {'parts': [{'text': 'You are a cat. Your name is Neko.'}]}} } ]` JavaScript`inlineRequestsList = [ {contents: [{parts: [{text: 'Write a short poem about a cloud.'}]}]}, {contents: [{parts: [{text: 'Write a short poem about a cat.'}]}], config: {systemInstruction: {parts: [{text: 'You are a cat. Your name is Neko.'}]}}} ]` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` Similarly can specify tools to use for a request. The following example\nshows a request that enables the [Google Search tool](/gemini-api/docs/google-search): Python`inlined_requests = [ {'contents': [{'parts': [{'text': 'Who won the euro 1998?'}]}]}, {'contents': [{'parts': [{'text': 'Who won the euro 2025?'}]}], 'config':{'tools': [{'google_search': {}}]}}]` JavaScript`inlineRequestsList = [ {contents: [{parts: [{text: 'Who won the euro 1998?'}]}]}, {contents: [{parts: [{text: 'Who won the euro 2025?'}]}], config: {tools: [{googleSearch: {}}]}} ]` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` You can specify [structured output](/gemini-api/docs/structured-output) as well.\nThe following example shows how to specify for your batch requests. Python`import time from google import genai from pydantic import BaseModel, TypeAdapter class Recipe(BaseModel): recipe_name: str ingredients: list[str] client = genai.Client() # A list of dictionaries, where each is a GenerateContentRequest inline_requests = [ { 'contents': [{ 'parts': [{'text': 'List a few popular cookie recipes, and include the amounts of ingredients.'}], 'role': 'user' }], 'config': { 'response_mime_type': 'application/json', 'response_schema': list[Recipe] } }, { 'contents': [{ 'parts': [{'text': 'List a few popular gluten free cookie recipes, and include the amounts of ingredients.'}], 'role': 'user' }], 'config': { 'response_mime_type': 'application/json', 'response_schema': list[Recipe] } } ] inline_batch_job = client.batches.create( model=\"gemini-3.8-flash\", src=inline_requests, config={ 'display_name': \"structured-output-job-1\" }, ) # wait for the job to finish job_name = inline_batch_job.name print(f\"Polling status for job: {job_name}\") while True: batch_job_inline = client.batches.get(name=job_name) if batch_job_inline.state.name in ('JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED'): break print(f\"Job not finished. Current state: {batch_job_inline.state.name}. Waiting 30 seconds...\") time.sleep(30) print(f\"Job finished with state: {batch_job_inline.state.name}\") # print the response for i, inline_response in enumerate(batch_job_inline.dest.inlined_responses, start=1): print(f\"\\n--- Response {i} ---\") # Check for a successful response if inline_response.response: # The .text property is a shortcut to the generated text. print(inline_response.response.text)` JavaScript`import {GoogleGenAI, Type} from '@google/genai'; const ai = new GoogleGenAI({}); const inlinedRequests = [ { contents: [{ parts: [{text: 'List a few popular cookie recipes, and include the amounts of ingredients.'}], role: 'user' }], config: { responseMimeType: 'application/json', responseSchema: { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { 'recipeName': { type: Type.STRING, description: 'Name of the recipe', nullable: false, }, 'ingredients': { type: Type.ARRAY, items: { type: Type.STRING, description: 'Ingredients of the recipe', nullable: false, }, }, }, required: ['recipeName'], }, }, } }, { contents: [{ parts: [{text: 'List a few popular gluten free cookie recipes, and include the amounts of ingredients.'}], role: 'user' }], config: { responseMimeType: 'application/json', responseSchema: { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { 'recipeName': { type: Type.STRING, description: 'Name of the recipe', nullable: false, }, 'ingredients': { type: Type.ARRAY, items: { type: Type.STRING, description: 'Ingredients of the recipe', nullable: false, }, }, }, required: ['recipeName'], }, }, } } ] const inlinedBatchJob = await ai.batches.create({ model: 'gemini-3.8-flash', src: inlinedRequests, config: { displayName: 'inlined-requests-job-1', } });` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` The following shows an example output of this job: `--- Response 1 --- [ { \"recipe_name\": \"Chocolate Chip Cookies\", \"ingredients\": [ \"1 cup (2 sticks) unsalted butter, softened\", \"3/4 cup granulated sugar\", \"3/4 cup packed light brown sugar\", \"1 large egg\", \"1 teaspoon vanilla extract\", \"2 1/4 cups all-purpose flour\", \"1 teaspoon baking soda\", \"1/2 teaspoon salt\", \"1 1/2 cups chocolate chips\" ] }, { \"recipe_name\": \"Oatmeal Raisin Cookies\", \"ingredients\": [ \"1 cup (2 sticks) unsalted butter, softened\", \"1 cup packed light brown sugar\", \"1/2 cup granulated sugar\", \"2 large eggs\", \"1 teaspoon vanilla extract\", \"1 1/2 cups all-purpose flour\", \"1 teaspoon baking soda\", \"1 teaspoon ground cinnamon\", \"1/2 teaspoon salt\", \"3 cups old-fashioned rolled oats\", \"1 cup raisins\" ] }, { \"recipe_name\": \"Sugar Cookies\", \"ingredients\": [ \"1 cup (2 sticks) unsalted butter, softened\", \"1 1/2 cups granulated sugar\", \"1 large egg\", \"1 teaspoon vanilla extract\", \"2 3/4 cups all-purpose flour\", \"1 teaspoon baking powder\", \"1/2 teaspoon salt\" ] } ] --- Response 2 --- [ { \"recipe_name\": \"Gluten-Free Chocolate Chip Cookies\", \"ingredients\": [ \"1 cup (2 sticks) unsalted butter, softened\", \"3/4 cup granulated sugar\", \"3/4 cup packed light brown sugar\", \"2 large eggs\", \"1 teaspoon vanilla extract\", \"2 1/4 cups gluten-free all-purpose flour blend (with xanthan gum)\", \"1 teaspoon baking soda\", \"1/2 teaspoon salt\", \"1 1/2 cups chocolate chips\" ] }, { \"recipe_name\": \"Gluten-Free Peanut Butter Cookies\", \"ingredients\": [ \"1 cup (250g) creamy peanut butter\", \"1/2 cup (100g) granulated sugar\", \"1/2 cup (100g) packed light brown sugar\", \"1 large egg\", \"1 teaspoon vanilla extract\", \"1/2 teaspoon baking soda\", \"1/4 teaspoon salt\" ] }, { \"recipe_name\": \"Gluten-Free Oatmeal Raisin Cookies\", \"ingredients\": [ \"1/2 cup (1 stick) unsalted butter, softened\", \"1/2 cup granulated sugar\", \"1/2 cup packed light brown sugar\", \"1 large egg\", \"1 teaspoon vanilla extract\", \"1 cup gluten-free all-purpose flour blend\", \"1/2 teaspoon baking soda\", \"1/2 teaspoon ground cinnamon\", \"1/4 teaspoon salt\", \"1 1/2 cups gluten-free rolled oats\", \"1/2 cup raisins\" ] } ]` Monitoring job status Use the operation name obtained when creating the batch job to poll its status.\nThe state field of the batch job will indicate its current status. A batch job\ncan be in one of the following states: `JOB_STATE_PENDING`: The job has been created and is waiting to be processed by the service. `JOB_STATE_RUNNING`: The job is in progress. `JOB_STATE_SUCCEEDED`: The job completed successfully. You can now retrieve the results. `JOB_STATE_FAILED`: The job failed. Check the error details for more information. `JOB_STATE_CANCELLED`: The job was cancelled by the user. `JOB_STATE_EXPIRED`: The job has expired because it was running or pending\nfor more than 48 hours. The job will not have any results to retrieve.\nYou can try submitting the job again or splitting up\nthe requests into smaller batches. You can poll the job status periodically to check for completion. Python`import time from google import genai client = genai.Client() # Use the name of the job you want to check # e.g., inline_batch_job.name from the previous step job_name = \"YOUR_BATCH_JOB_NAME\" # (e.g. 'batches/your-batch-id') batch_job = client.batches.get(name=job_name) completed_states = set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]) print(f\"Polling status for job: {job_name}\") batch_job = client.batches.get(name=job_name) # Initial get while batch_job.state.name not in completed_states: print(f\"Current state: {batch_job.state.name}\") time.sleep(30) # Wait for 30 seconds before polling again batch_job = client.batches.get(name=job_name) print(f\"Job finished with state: {batch_job.state.name}\") if batch_job.state.name == 'JOB_STATE_FAILED': print(f\"Error: {batch_job.error}\")` JavaScript`// Use the name of the job you want to check // e.g., inlinedBatchJob.name from the previous step let batchJob; const completedStates = new Set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]); try { batchJob = await ai.batches.get({name: inlinedBatchJob.name}); while (!completedStates.has(batchJob.state)) { console.log(`Current state: ${batchJob.state}`); // Wait for 30 seconds before polling again await new Promise(resolve => setTimeout(resolve, 30000)); batchJob = await client.batches.get({ name: batchJob.name }); } console.log(`Job finished with state: ${batchJob.state}`); if (batchJob.state === 'JOB_STATE_FAILED') { // The exact structure of `error` might vary depending on the SDK // This assumes `error` is an object with a `message` property. console.error(`Error: ${batchJob.state}`); } } catch (error) { console.error(`An error occurred while polling job ${batchJob.name}:`, error); }` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` Polling and webhooks **Tired of polling?** Gemini now supports\n[Webhooks](/gemini-api/docs/webhooks) for processing completions asynchronously.\nInstead of continuously calling `GET / operations`, subscribe to\n`batch.succeeded` directly to allow the Gemini API to push real-time\nnotifications to your server when asynchronous or long-running operations\ncomplete. Python`from google import genai client = genai.Client() webhook = client.webhooks.create( name=\"MyBatchWebhook\", subscribed_events=[\"batch.succeeded\", \"batch.failed\"], uri=\"https://my-api.com/gemini-callback\", ) print(f\"Created webhook: {webhook.name}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI(); async function createWebhook() { const webhook = await client.webhooks.create({ name: \"MyBatchWebhook\", subscribed_events: [\"batch.succeeded\", \"batch.failed\"], uri: \"https://my-api.com/gemini-callback\", }); console.log(`Created webhook: ${webhook.name}`); } createWebhook();` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`curl -X POST \\ \"https://generativelanguage.googleapis.com/v1/webhooks?webhook_id=my-example-webhook-123\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GOOGLE_API_KEY\" \\ -d '{ \"name\": \"My Example Webhook\", \"uri\": \"https://my-api.com/gemini-callback\", \"subscribed_events\": [\"batch.succeeded\", \"batch.failed\"] }'` Retrieving results Once the job status indicates your batch job has succeeded, the results are\navailable in the `response` field.\nBy default, batch job results are stored and available for download for 6 weeks,\nbefore they are permanently deleted. Python`import json from google import genai client = genai.Client() # Use the name of the job you want to check # e.g., inline_batch_job.name from the previous step job_name = \"YOUR_BATCH_JOB_NAME\" batch_job = client.batches.get(name=job_name) if batch_job.state.name == 'JOB_STATE_SUCCEEDED': # If batch job was created with a file if batch_job.dest and batch_job.dest.file_name: # Results are in a file result_file_name = batch_job.dest.file_name print(f\"Results are in file: {result_file_name}\") print(\"Downloading result file content...\") file_content = client.files.download(file=result_file_name) # Process file_content (bytes) as needed print(file_content.decode('utf-8')) # If batch job was created with inline request # (for embeddings, use batch_job.dest.inlined_embed_content_responses) elif batch_job.dest and batch_job.dest.inlined_responses: # Results are inline print(\"Results are inline:\") for i, inline_response in enumerate(batch_job.dest.inlined_responses): print(f\"Response {i+1}:\") if inline_response.response: # Accessing response, structure may vary. try: print(inline_response.response.text) except AttributeError: print(inline_response.response) # Fallback elif inline_response.error: print(f\"Error: {inline_response.error}\") else: print(\"No results found (neither file nor inline).\") else: print(f\"Job did not succeed. Final state: {batch_job.state.name}\") if batch_job.error: print(f\"Error: {batch_job.error}\")` JavaScript`// Use the name of the job you want to check // e.g., inlinedBatchJob.name from the previous step const jobName = \"YOUR_BATCH_JOB_NAME\"; try { const batchJob = await ai.batches.get({ name: jobName }); if (batchJob.state === 'JOB_STATE_SUCCEEDED') { console.log('Found completed batch:', batchJob.displayName); console.log(batchJob); // If batch job was created with a file destination if (batchJob.dest?.fileName) { const resultFileName = batchJob.dest.fileName; console.log(`Results are in file: ${resultFileName}`); console.log(\"Downloading result file content...\"); const fileContentBuffer = await ai.files.download({ file: resultFileName }); // Process fileContentBuffer (Buffer) as needed console.log(fileContentBuffer.toString('utf-8')); } // If batch job was created with inline responses else if (batchJob.dest?.inlinedResponses) { console.log(\"Results are inline:\"); for (let i = 0; i < batchJob.dest.inlinedResponses.length; i++) { const inlineResponse = batchJob.dest.inlinedResponses[i]; console.log(`Response ${i + 1}:`); if (inlineResponse.response) { // Accessing response, structure may vary. if (inlineResponse.response.text !== undefined) { console.log(inlineResponse.response.text); } else { console.log(inlineResponse.response); // Fallback } } else if (inlineResponse.error) { console.error(`Error: ${inlineResponse.error}`); } } } // If batch job was an embedding batch with inline responses else if (batchJob.dest?.inlinedEmbedContentResponses) { console.log(\"Embedding results found inline:\"); for (let i = 0; i < batchJob.dest.inlinedEmbedContentResponses.length; i++) { const inlineResponse = batchJob.dest.inlinedEmbedContentResponses[i]; console.log(`Response ${i + 1}:`); if (inlineResponse.response) { console.log(inlineResponse.response); } else if (inlineResponse.error) { console.error(`Error: ${inlineResponse.error}`); } } } else { console.log(\"No results found (neither file nor inline).\"); } } else { console.log(`Job did not succeed. Final state: ${batchJob.state}`); if (batchJob.error) { console.error(`Error: ${typeof batchJob.error === 'string' ? batchJob.error : batchJob.error.message || JSON.stringify(batchJob.error)}`); } } } catch (error) { console.error(`An error occurred while processing job ${jobName}:`, error); }` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`BATCH_NAME=\"batches/123456\" # Your batch job name\n\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H \"Content-Type:application/json\" 2> /dev/null > batch_status.json\n\nif jq -r '.done' batch_status.json | grep -q \"false\"; then echo \"Batch has not finished processing\" fi batch_state=$(jq -r '.metadata.state' batch_status.json) if [[ $batch_state = \"JOB_STATE_SUCCEEDED\" ]]; then if [[ $(jq '.response | has(\"inlinedResponses\")' batch_status.json) = \"true\" ]]; then jq -r '.response.inlinedResponses' batch_status.json\n exit fi responses_file_name=$(jq -r '.response.responsesFile' batch_status.json) curl https://generativelanguage.googleapis.com/download/v1beta/$responses_file_name:download?alt=media \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" 2> /dev/null\nelif [[ $batch_state = \"JOB_STATE_FAILED\" ]]; then jq '.error' batch_status.json\nelif [[ $batch_state == \"JOB_STATE_CANCELLED\" ]]; then echo \"Batch was cancelled by the user\" elif [[ $batch_state == \"JOB_STATE_EXPIRED\" ]]; then echo \"Batch expired after 48 hours\" fi` Listing batch jobs You can list your recent batch jobs. Python`batch_jobs = client.batches.list() # Optional query config: # batch_jobs = client.batches.list(config={'page_size': 5}) for batch_job in batch_jobs: print(batch_job)` JavaScript`const batchJobs = await ai.batches.list(); // Optional query config: // const batchJobs = await ai.batches.list({config: {'pageSize': 5}}); for await (const batchJob of batchJobs) { console.log(batchJob); }` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`curl https://generativelanguage.googleapis.com/v1beta/batches \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\"` Cancelling a batch job You can cancel an ongoing batch job using its name. When a job is\ncanceled, it stops processing new requests. Python`client.batches.cancel(name=batch_job_to_cancel.name)` JavaScript`await ai.batches.cancel({name: batchJobToCancel.name});` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`BATCH_NAME=\"batches/123456\" # Your batch job name # Cancel the batch\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME:cancel \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\ # Confirm that the status of the batch after cancellation is JOB_STATE_CANCELLED\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H \"Content-Type:application/json\" 2> /dev/null | jq -r '.metadata.state'` Deleting a batch job You can delete an existing batch job using its name. When a job is\ndeleted, it stops processing new requests and is removed from the list of\nbatch jobs. Python`client.batches.delete(name=batch_job_to_delete.name)` JavaScript`await ai.batches.delete({name: batchJobToDelete.name});` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`BATCH_NAME=\"batches/123456\" # Your batch job name # Delete the batch job\ncurl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\"` Generating images in batch If you're using [Gemini Nano Banana](/gemini-api/docs/image-generation) and need to generate a lot\nof images, you can use the Batch API to get higher\n[rate limits](/gemini-api/docs/rate-limits) in exchange for a turnaround of up\nto 24 hours. You can either use inline requests for small batches of requests (under 20MB) or\na JSONL input file for large batches (recommended for image generation): Inline requests for images Python`import time import base64 import json from google import genai from google.genai import types from PIL import Image client = genai.Client() # 1. Create batch job with inline requests inline_requests = [ { 'contents': [{'parts': [{'text': 'A big letter A surrounded by animals starting with the A letter'}]}], 'config': {'response_modalities': ['TEXT', 'IMAGE']} }, { 'contents': [{'parts': [{'text': 'A big letter B surrounded by animals starting with the B letter'}]}], 'config': {'response_modalities': ['TEXT', 'IMAGE']} } ] inline_batch_job = client.batches.create( model=\"gemini-3-pro-image-preview\", src=inline_requests, config={ 'display_name': \"inlined-image-requests-job-1\", }, ) print(f\"Created batch job: {inline_batch_job.name}\") # 2. Monitor job status job_name = inline_batch_job.name print(f\"Polling status for job: {job_name}\") completed_states = set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]) batch_job = client.batches.get(name=job_name) # Initial get while batch_job.state.name not in completed_states: print(f\"Current state: {batch_job.state.name}\") time.sleep(10) # Wait for 10 seconds before polling again batch_job = client.batches.get(name=job_name) print(f\"Job finished with state: {batch_job.state.name}\") # 3. Retrieve results if batch_job.state.name == 'JOB_STATE_SUCCEEDED': print(\"Results are inline:\") for i, inline_response in enumerate(batch_job.dest.inlined_responses): print(f\"Response {i+1}:\") if inline_response.response: for part in inline_response.response.candidates[0].content.parts: if part.text: print(part.text) elif part.inline_data: print(f\"Image mime type: {part.inline_data.mime_type}\") image = part.as_image() image.save(f\"image_{i+1}.png\") elif inline_response.error: print(f\"Error: {inline_response.error}\") elif batch_job.state.name == 'JOB_STATE_FAILED': print(f\"Error: {batch_job.error}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI({}); async function run() { // 1. Create batch job with inline requests const inlinedRequests = [ { contents: [{parts: [{text: 'A big letter A surrounded by animals starting with the A letter'}]}], config: {responseModalities: ['TEXT', 'IMAGE']} }, { contents: [{parts: [{text: 'A big letter B surrounded by animals starting with the B letter'}]}], config: {responseModalities: ['TEXT', 'IMAGE']} } ] const inlineBatchJob = await ai.batches.create({ model: 'gemini-3-pro-image-preview', src: inlinedRequests, config: { displayName: 'inlined-image-requests-job-1', } }); console.log(inlineBatchJob); // 2. Monitor job status let batchJob; const completedStates = new Set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]); try { batchJob = await ai.batches.get({name: inlineBatchJob.name}); while (!completedStates.has(batchJob.state)) { console.log(`Current state: ${batchJob.state}`); // Wait for 10 seconds before polling again await new Promise(resolve => setTimeout(resolve, 10000)); batchJob = await ai.batches.get({ name: batchJob.name }); } console.log(`Job finished with state: ${batchJob.state}`); } catch (error) { console.error(`An error occurred while polling job ${inlineBatchJob.name}:`, error); return; } // 3. Retrieve results if (batchJob.state === 'JOB_STATE_SUCCEEDED') { if (batchJob.dest?.inlinedResponses) { console.log(\"Results are inline:\"); for (let i = 0; i < batchJob.dest.inlinedResponses.length; i++) { const inlineResponse = batchJob.dest.inlinedResponses[i]; console.log(`Response ${i + 1}:`); if (inlineResponse.response) { for (const part of inlineResponse.response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { console.log(`Image mime type: ${part.inlineData.mimeType}`); } } } else if (inlineResponse.error) { console.error(`Error: ${inlineResponse.error}`); } } } else { console.log(\"No inline results found.\"); } } else if (batchJob.state === 'JOB_STATE_FAILED') { console.error(`Error: ${typeof batchJob.error === 'string' ? batchJob.error : batchJob.error.message || JSON.stringify(batchJob.error)}`); } } run();` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`# 1. Create batch job printf -v request_data '{ \"batch\": { \"display_name\": \"my-batch-image-requests\", \"input_config\": { \"requests\": { \"requests\": [ { \"request\": { \"contents\": [{\"parts\": [{\"text\": \"A big letter A surrounded by animals starting with the A letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]} }, \"metadata\": { \"key\": \"request-1\" } }, { \"request\": { \"contents\": [{\"parts\": [{\"text\": \"A big letter B surrounded by animals starting with the B letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]} }, \"metadata\": { \"key\": \"request-2\" } } ] } } } }'\ncurl https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:batchGenerateContent \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -X POST \\ -H \"Content-Type:application/json\" \\ -d \"$request_data\" > created_batch.json\n\nBATCH_NAME=$(jq -r '.name' created_batch.json) echo \"Created batch job: $BATCH_NAME\" # 2. Poll job status until completion by repeating the following command # Replace $BATCH_NAME with the name returned above.\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type:application/json\" > batch_status.json\n\necho \"Current status:\"\njq '.' batch_status.json\n\n# 3. If state is JOB_STATE_SUCCEEDED, retrieve results from batch_status.json batch_state=$(jq -r '.state' batch_status.json) if [[ $batch_state = \"JOB_STATE_SUCCEEDED\" ]]; then echo \"Job succeeded. Results:\" jq -r '.dest.inlinedResponses' batch_status.json\nfi` Input file for images Python`import json import time import base64 from google import genai from google.genai import types from PIL import Image client = genai.Client() # 1. Create and upload file file_name = \"my-batch-image-requests.jsonl\" with open(file_name, \"w\") as f: requests = [ {\"key\": \"request-1\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"A big letter A surrounded by animals starting with the A letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}}}, {\"key\": \"request-2\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"A big letter B surrounded by animals starting with the B letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}}} ] for req in requests: f.write(json.dumps(req) + \"\\n\") uploaded_file = client.files.upload( file=file_name, config=types.UploadFileConfig(display_name='my-batch-image-requests', mime_type='jsonl') ) print(f\"Uploaded file: {uploaded_file.name}\") # 2. Create batch job file_batch_job = client.batches.create( model=\"gemini-3-pro-image-preview\", src=uploaded_file.name, config={ 'display_name': \"file-image-upload-job-1\", }, ) print(f\"Created batch job: {file_batch_job.name}\") # 3. Monitor job status job_name = file_batch_job.name print(f\"Polling status for job: {job_name}\") completed_states = set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]) batch_job = client.batches.get(name=job_name) # Initial get while batch_job.state.name not in completed_states: print(f\"Current state: {batch_job.state.name}\") time.sleep(10) # Wait for 10 seconds before polling again batch_job = client.batches.get(name=job_name) print(f\"Job finished with state: {batch_job.state.name}\") # 4. Retrieve results if batch_job.state.name == 'JOB_STATE_SUCCEEDED': result_file_name = batch_job.dest.file_name print(f\"Results are in file: {result_file_name}\") print(\"Downloading result file content...\") file_content_bytes = client.files.download(file=result_file_name) file_content = file_content_bytes.decode('utf-8') # The result file is also a JSONL file. Parse and print each line. for line in file_content.splitlines(): if line: parsed_response = json.loads(line) if 'response' in parsed_response and parsed_response['response']: for part in parsed_response['response']['candidates'][0]['content']['parts']: if part.get('text'): print(part['text']) elif part.get('inlineData'): print(f\"Image mime type: {part['inlineData']['mimeType']}\") data = base64.b64decode(part['inlineData']['data']) elif 'error' in parsed_response: print(f\"Error: {parsed_response['error']}\") elif batch_job.state.name == 'JOB_STATE_FAILED': print(f\"Error: {batch_job.error}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; import * as fs from \"fs\"; import * as path from \"path\"; import { fileURLToPath } from 'url'; const ai = new GoogleGenAI({}); async function run() { // 1. Create and upload file const fileName = \"my-batch-image-requests.jsonl\"; const requests = [ { \"key\": \"request-1\", \"request\": { \"contents\": [{ \"parts\": [{ \"text\": \"A big letter A surrounded by animals starting with the A letter\" }] }], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]} } }, { \"key\": \"request-2\", \"request\": { \"contents\": [{ \"parts\": [{ \"text\": \"A big letter B surrounded by animals starting with the B letter\" }] }], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]} } } ]; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const filePath = path.join(__dirname, fileName); try { const writeStream = fs.createWriteStream(filePath, { flags: 'w' }); for (const req of requests) { writeStream.write(JSON.stringify(req) + '\\n'); } writeStream.end(); console.log(`Successfully wrote batch requests to ${filePath}`); } catch (error) { console.error(`An unexpected error occurred writing file:`, error); return; } const uploadedFile = await ai.files.upload({file: fileName, config: { mimeType: 'jsonl' }}); console.log(`Uploaded file: ${uploadedFile.name}`); // 2. Create batch job const fileBatchJob = await ai.batches.create({ model: 'gemini-3-pro-image-preview', src: uploadedFile.name, config: { displayName: 'file-image-upload-job-1', } }); console.log(fileBatchJob); // 3. Monitor job status let batchJob; const completedStates = new Set([ 'JOB_STATE_SUCCEEDED', 'JOB_STATE_FAILED', 'JOB_STATE_CANCELLED', 'JOB_STATE_EXPIRED', ]); try { batchJob = await ai.batches.get({name: fileBatchJob.name}); while (!completedStates.has(batchJob.state)) { console.log(`Current state: ${batchJob.state}`); // Wait for 10 seconds before polling again await new Promise(resolve => setTimeout(resolve, 10000)); batchJob = await ai.batches.get({ name: batchJob.name }); } console.log(`Job finished with state: ${batchJob.state}`); } catch (error) { console.error(`An error occurred while polling job ${fileBatchJob.name}:`, error); return; } // 4. Retrieve results if (batchJob.state === 'JOB_STATE_SUCCEEDED') { if (batchJob.dest?.fileName) { const resultFileName = batchJob.dest.fileName; console.log(`Results are in file: ${resultFileName}`); console.log(\"Downloading result file content...\"); const fileContentBuffer = await ai.files.download({ file: resultFileName }); const fileContent = fileContentBuffer.toString('utf-8'); for (const line of fileContent.split('\\n')) { if (line) { const parsedResponse = JSON.parse(line); if (parsedResponse.response) { for (const part of parsedResponse.response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { console.log(`Image mime type: ${part.inlineData.mimeType}`); } } } else if (parsedResponse.error) { console.error(`Error: ${parsedResponse.error}`); } } } } else { console.log(\"No result file found.\"); } } else if (batchJob.state === 'JOB_STATE_FAILED') { console.error(`Error: ${typeof batchJob.error === 'string' ? batchJob.error : batchJob.error.message || JSON.stringify(batchJob.error)}`); } } run();` Java`import com.google.genai.Client; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; Client client = new Client(); BatchJobSource batchJobSource = BatchJobSource.builder() .gcsUri(\"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl\") .format(\"jsonl\") .build(); BatchJob batchJob = client.batches.create(\"gemini-3.8-flash\", batchJobSource, null); System.out.println(\"Batch Job Name: \" + batchJob.name().orElse(\"\"));` REST`# 1. Create and upload file echo '{\"key\": \"request-1\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"A big letter A surrounded by animals starting with the A letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}}}' > my-batch-image-requests.jsonl\necho '{\"key\": \"request-2\", \"request\": {\"contents\": [{\"parts\": [{\"text\": \"A big letter B surrounded by animals starting with the B letter\"}]}], \"generation_config\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}}}' >> my-batch-image-requests.jsonl\n\n# Follow File API guide to upload: https://ai.google.dev/gemini-api/docs/files#upload_a_file # This example assumes you have uploaded the file and set BATCH_INPUT_FILE to its name (e.g., files/abcdef123) BATCH_INPUT_FILE=\"files/your-uploaded-file-name\" # 2. Create batch job printf -v request_data '{ \"batch\": { \"display_name\": \"my-batch-file-image-requests\", \"input_config\": { \"file_name\": \"%s\" } } }' \"$BATCH_INPUT_FILE\"\ncurl https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:batchGenerateContent \\ -X POST \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type:application/json\" \\ -d \"$request_data\" > created_batch.json\n\nBATCH_NAME=$(jq -r '.name' created_batch.json) echo \"Created batch job: $BATCH_NAME\" # 3. Poll job status until completion by repeating the following command:\ncurl https://generativelanguage.googleapis.com/v1beta/$BATCH_NAME \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type:application/json\" > batch_status.json\n\necho \"Current status:\"\njq '.' batch_status.json\n\n# 4. If state is JOB_STATE_SUCCEEDED, download results file batch_state=$(jq -r '.state' batch_status.json) if [[ $batch_state = \"JOB_STATE_SUCCEEDED\" ]]; then responses_file_name=$(jq -r '.dest.fileName' batch_status.json) echo \"Job succeeded. Downloading results from $responses_file_name...\" curl https://generativelanguage.googleapis.com/download/v1beta/$responses_file_name:download?alt=media \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" > batch_results.jsonl\n echo \"Results saved to batch_results.jsonl\" fi` Technical details **Supported models:** Batch API supports a range of Gemini models.\nRefer to the [Models page](/gemini-api/docs/models) for each model's support\nof Batch API. The supported modalities for Batch API are the same\nas what's supported on the interactive (or non-batch) API. **Pricing:** Batch API usage is priced at 50% of the standard interactive\nAPI cost for the equivalent model. See the [pricing page](/gemini-api/docs/pricing)\nfor details. Refer to the [rate limits page](/gemini-api/docs/rate-limits#batch-mode)\nfor details on rate limits for this feature. **Service level objective (SLO):** Batch jobs are designed to complete\nwithin a 24-hour turnaround time. Many jobs may complete much faster\ndepending on their size and current system load. **Caching:** [Context caching](/gemini-api/docs/caching) is supported\nfor batch requests. Reuse cached content by specifying the `cached_content`\nresource name in the configuration of individual requests within your batch.\nIf a request in your batch results in a cache hit, you pay the\n[standard context caching rates](/gemini-api/docs/pricing). Best practices **Use input files for large requests:** For a large number of requests,\nalways use the file input\nmethod for better manageability and to avoid hitting request size limits for\nthe [`BatchGenerateContent`](/api/batch-mode#google.ai.generativelanguage.v1beta.BatchService.BatchGenerateContent)\ncall itself. Note that there's a 2GB file size limit per input file. **Error handling:** Check the `batchStats` for `failedRequestCount` after a\njob completes. If using file output, parse each line to check if it's a\n`GenerateContentResponse` or a status object indicating an error for that\nspecific request. See the [troubleshooting\nguide](/gemini-api/docs/troubleshooting#error-codes) for a complete set of\nerror codes. **Submit jobs once:** The creation of a batch job is not idempotent.\nIf you send the same creation request twice, two separate batch jobs will\nbe created. **Break up very large batches:** While the target turnaround time is 24\nhours, actual processing time can vary based on system load and job size.\nFor large jobs, consider breaking them into smaller\nbatches if intermediate results are needed sooner. What's next Check out the [Batch API notebook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb)\nfor more examples. The OpenAI compatibility layer supports Batch API. Read the examples on the\n[OpenAI Compatibility](/gemini-api/docs/openai#batch) page. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 52716, "slov": 6233, "odkazu": 142, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:52:35", "sha256": "e52fbad2c109ddb5252009176e21ffb31490c5cbe0e3d27ec89cecdd70433dd4", "hloubka": 2, "zdroj_objevu": "odkaz", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://jsonlines.org/", "https://github.com/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/billing", "titulek": "Billing | Gemini API | Google AI for Developers", "h1": "Billing", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/billing", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Billing  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/billing", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Billing"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Billing", "item": "https://ai.google.dev/gemini-api/docs/billing"}]}], "drobecky": ["Gemini API", "Billing"], "osnova": [{"uroven": 1, "text": "Billing"}, {"uroven": 2, "text": "About billing and tiers"}, {"uroven": 2, "text": "Set up billing to access the Paid Tier"}, {"uroven": 3, "text": "Upgrade to the next paid tier"}, {"uroven": 2, "text": "Verify billing status"}, {"uroven": 2, "text": "Monitor usage"}, {"uroven": 2, "text": "Billing plans"}, {"uroven": 3, "text": "Prepay"}, {"uroven": 4, "text": "Add Prepay to an existing Postpay account"}, {"uroven": 4, "text": "Buy credits"}, {"uroven": 4, "text": "Auto reload"}, {"uroven": 4, "text": "Monthly auto-charge limit"}, {"uroven": 3, "text": "Postpay"}, {"uroven": 3, "text": "Migrate to prepay"}, {"uroven": 2, "text": "Spend caps"}, {"uroven": 3, "text": "Project spend caps"}, {"uroven": 3, "text": "Billing account tier spend caps"}, {"uroven": 4, "text": "Evaluate your billing account spend"}, {"uroven": 2, "text": "Processing times"}, {"uroven": 2, "text": "Refunds"}, {"uroven": 2, "text": "Cloud Billing accounts"}, {"uroven": 3, "text": "Projects and API keys"}, {"uroven": 2, "text": "Frequently asked questions"}, {"uroven": 3, "text": "What am I billed for?"}, {"uroven": 3, "text": "Where can I view my quota?"}, {"uroven": 3, "text": "How do I move to a higher rate limit tier, or request more quota?"}, {"uroven": 3, "text": "Can I use the Gemini API for free in EEA (including EU), the UK, and CH?"}, {"uroven": 3, "text": "If I set up billing with the Gemini API, will I be charged for my Google AI Studio usage?"}, {"uroven": 3, "text": "If I'm on the Free Tier, how do I upgrade to higher tiers?"}, {"uroven": 3, "text": "Can I use 1M tokens in the free tier?"}, {"uroven": 3, "text": "Can I revert back to Free Tier after I've upgraded to higher (paid) tiers?"}, {"uroven": 3, "text": "How can I calculate the number of tokens I'm using?"}, {"uroven": 3, "text": "If I sign up for my first Cloud Billing account through AI Studio, will I still get a Google Cloud Free Trial?"}, {"uroven": 3, "text": "Can I use my Google Cloud Welcome credit with the Gemini API?"}, {"uroven": 3, "text": "Does the Google Cloud Free Trial apply to Gemini API usage?"}, {"uroven": 3, "text": "How do Google Cloud credits work with Prepay?"}, {"uroven": 3, "text": "How is billing handled?"}, {"uroven": 3, "text": "Am I charged for failed requests?"}, {"uroven": 3, "text": "Is GetTokens billed?"}, {"uroven": 3, "text": "How is my Google AI Studio data handled if I have a paid API account?"}, {"uroven": 3, "text": "What is Prepaid billing and who is required to use the prepaid billing model?"}, {"uroven": 3, "text": "How do I purchase Prepay credits, and is there a minimum amount or maximum?"}, {"uroven": 3, "text": "Can I configure my Prepay account to automatically purchase more credits as needed?"}, {"uroven": 3, "text": "Can I limit the amount of automatic reload charges?"}, {"uroven": 3, "text": "Can I get a refund for my unused credits?"}, {"uroven": 3, "text": "Do my prepaid credits expire?"}, {"uroven": 3, "text": "What happens when my prepaid credit balance hits $0?"}, {"uroven": 3, "text": "Why did my usage stop even though my Prepay credit balance is greater than $0?"}, {"uroven": 3, "text": "Why is my Prepay account credit balance negative?"}, {"uroven": 3, "text": "Can I use my Prepay credits for other Google Cloud services, like Gemini Enterprise Agent Platform?"}, {"uroven": 3, "text": "Can I switch from Prepay to Postpay billing?"}, {"uroven": 3, "text": "Can I switch from Postpay to Prepay billing?"}, {"uroven": 3, "text": "What happens to my Prepaid credits if I switch to Postpay?"}, {"uroven": 3, "text": "Where can I see my current Prepay credit balance and transaction history?"}, {"uroven": 3, "text": "Why am I seeing \"The billing account type is inactive or unsupported\"?"}, {"uroven": 3, "text": "Will my Gemini API usage costs show up in the Google Cloud console?"}, {"uroven": 3, "text": "Why isn't my Gemini API Usage showing up in the Cloud Billing Console, when I can see it in AI Studio Billing, along with the consumption of my credits?"}, {"uroven": 3, "text": "If I use other Google Cloud services with costs that are subject to a Postpay charging cycle, what happens if I miss a payment?"}, {"uroven": 3, "text": "Why are my projects disrupted after I canceled a Prepay setup?"}, {"uroven": 3, "text": "Where can I get help with billing?"}], "markdown": "Billing This guide provides an overview of different Gemini API billing options,\nexplains how to enable billing and monitor usage, and provides answers to\nfrequently asked questions (FAQs) about billing. About billing and tiers Billing for the Gemini API is based on your payment history. Usage tier Qualification Billing tier cap **Free** [Active project](/gemini-api/docs/api-key#google-cloud-projects) or free trial N/A **Tier 1** Set up and link an active billing account $250 **Tier 2** Paid $100 + 3 days from first successful payment $2,000 **Tier 3** Paid $1,000 + 30 days from first successful payment $20,000 - $100,000+ New accounts begin on the Free Tier, which allows access to\n[certain models](/gemini-api/docs/pricing) in the Gemini API and AI Studio,\nup to the models' free tier [rate limits](https://aistudio.google.com/rate-limit). To deploy your applications directly from Build mode, you can use the\n**Google Cloud Starter Tier**. This tier lets you publish up to 2 full stack\napplications without setting up a Google Cloud project or billing account.\nSee [Deploying from Google AI Studio](/gemini-api/docs/aistudio-deploying) for\ndetails and refer to the [Google Cloud Starter Tier documentation](https://docs.cloud.google.com/docs/starter-tier) for more information. To access higher rate limits, use advanced models, and ensure your prompts and\nresponses are **not** used to improve Google products*, you can\nlink a billing account and Prepay to move to the\nPaid Tiers.\nThen, you'll move through higher tiers based on cumulative spend and account\nage. Tiers, rate limits, and billing account caps are all determined at the billing\naccount level. * *Enterprise-grade data privacy: For more information on data use\nfor paid services, see the [Terms of Service](/gemini-api/terms#data-use-paid).* Set up billing to access the Paid Tier You can create a project and set up billing, or import an existing project, to\nupgrade to the Paid Tier in [Google AI Studio](https://aistudio.google.com/projects).\nUpgrading from the Free Tier to the Paid Tier means linking a billing account\nand prepaying to add a minimum of $5 (or equivalent in other\ncurrencies) of credits to your account. Go to the AI Studio [API keys](https://aistudio.google.com/api-keys) page,\n[Projects](https://aistudio.google.com/projects) page, or anywhere you see\n**Set up billing** button in AI Studio.\n New users will have a [project and API key](/gemini-api/docs/api-key#google-cloud-projects) created for them by default. If you need a new key, click [**Create API key**](https://aistudio.google.com/api-keys)\nand follow the dialog to add a key-project pair to the table. Find the Free Tier project you want to upgrade to the Paid Tier, and click\n**Set up billing** under the *Billing Tier* column. If you've never set up a Google billing account before:\n You'll be asked to select your country to agree to the Terms of Service. Then, fill in or confirm your contact information and payment method to continue. If you have set up Google billing accounts in the past:\n You'll be asked to choose from your existing billing accounts. If you don't want to use any of your existing accounts, click **Add new\nbilling account** and fill in or confirm your contact information and\npayment method to continue. Next, you will either be:\n Asked to prepay a minimum of $5 to complete billing\nsetup (meaning your account is auto-assigned to the Prepay billing\nplan), Given the choice between Prepay and Postpay\nbilling plans for your account. Assigned to a Postpay billing plan for an intermediary period\nuntil the new Prepay system propagates to all users (starting March 23, 2026). After prepaying or selecting Postpay, your account setup is complete. Upgrade to the next paid tier If you're already on a paid tier and meet the criteria\nfor a plan change, you will be automatically upgraded to the next tier\n(subject to processing times). Verify billing status After you have linked a billing account to your project, you\ncan monitor its status on the\n[AI Studio Billing page](https://aistudio.google.com/billing). Unlike the free\ntier, paid tier status is dynamic; while your usage tier is determined by your\naccount history, the Gemini API will only serve requests if you have a\npositive Prepay credit balance. On the [Projects](https://aistudio.google.com/projects) page, you'll be able to\nsee your project's tier and billing plan under the *Billing Tier* column. Any\nbilling status actions you may need to take for a project display in the\n*Billing Tier* or *Status* columns: \"***Set up billing***\" if the project doesn't have a billing account attached. \"***Set up Prepay***\" if the project does have a billing account attached, but\nis required to use a Prepay billing plan that needs to be set up. \"***No credits***\" if the billing account is required to purchase\ncredits but the Prepay payments account isn't set up or the available credit\nbalance is depleted. Click any of the messages to proceed with the necessary actions. Monitor usage You can monitor your usage of the Gemini API in\n[Google AI Studio](https://aistudio.google.com/usage) in **Dashboard** >\n**Usage**. Billing plans Billing plans for the Gemini API and AI Studio fall into two categories that\ndetermine when you pay for usage: Prepay and Postpay. You can check your\nassigned billing plan and manage payment methods on the\n[AI Studio Billing](https://aistudio.google.com/billing) page. Prepay In the Prepay billing plan, you purchase credits towards your prepay balance in\nadvance of your Gemini API usage, and your API usage costs are deducted from\nyour Prepay credit balance in near real-time.\nYou can prepay by adding credits into your account, or setting\nup auto-reload. After credits are purchased, unused credits\nexpire after 12 months and are non-refundable, except after\nswitching to a Postpay account. When your Prepay credit balance on the billing account hits $0, all API keys in\nall projects linked to that billing account will stop working simultaneously.\nPrepay credits apply only to Gemini API usage costs; you can't use\nthem to pay for other Google Cloud services. New users default to the Prepay billing plan. Projects that pre-date the\nintroduction of Prepay and Postpay billing plans may need to update their\nproject's billing details before continuing to use the Gemini\nAPI. *Note that Prepay is not available for [Invoiced (or Offline)](https://docs.cloud.google.com/billing/docs/concepts#billing_account_types)\naccounts.* Add Prepay to an existing Postpay account If your existing Cloud Billing account uses a **Postpay** plan, you can add **Prepay**\ncapabilities to purchase credits in advance. These prepay credits let you use\nthe Gemini API without creating a new Cloud Billing account. During the setup to add **Prepay** to an existing account, you are\npresented with a mandatory confirmation screen explaining that your selected\nCloud Billing account will be modified. The system must modify your account state *before* you submit your prepayment.\nTherefore, canceling the process after confirming the modification but before\ncompleting the prepayment setup might result in temporary service disruptions\nfor projects already linked to that Cloud Billing account. Ensure you are ready\nto complete the prepayment process before confirming the transition. If you\nencounter issues, see [Services disrupted after canceling a **Prepay**\nsetup](https://docs.cloud.google.com/billing/docs/in-product-billing-setup#prepay-issue). If you are eligible and manually switch from a **Prepay** cycle to a **Postpay**\ncycle, any remaining prepay credit balance is automatically refunded to the\noriginal payment method used for the prepayment. However, if you close your\nCloud Billing account for any other reason, any remaining prepay\ncredits are forfeited and aren't refunded. Buy credits You can manually purchase credits in advance of your Gemini API usage to load\nthem into your Prepay account credit balance. To purchase credits, go to the [AI Studio Billing](https://aistudio.google.com/billing) page and select **Buy credits**.\nThe minimum purchase is $5. The maximum amount of credits you can prepay for is\n$5,000. Auto reload Auto-reload is an optional feature that automatically tops up your Prepay credit\nbalance when it's running low. This is useful to prevent service interruptions. You can set up auto reload and see your auto-reload status in the *Available\ncredits* card on the [AI Studio Billing](https://aistudio.google.com/billing)\npage. Click **Setup auto-reload** or\n**Manage auto-reload** to set your payment method, reload amount, and the\nminimum balance that triggers a reload payment. Monthly auto-charge limit The monthly auto-charge limit is available to Prepay users\nand helps prevent unexpected costs from frequent automatic credit reloads.\nUse this feature to set a maximum limit for automatic credit reloads within\na single billing cycle. Once the total amount of automatic reloads in a billing\ncycle reaches this limit, the system disables auto-reload until the start of the\nnext month. One-time payments you initiate manually don't count against this limit. To set the monthly auto-charge limit when auto-reload is enabled: Go to the [AI Studio Billing](https://aistudio.google.com/billing) page. Click **Manage auto-reload**. Expand the **Monthly Limit** section and enter the maximum monthly limit for auto-reloads. Click **Save**. Postpay In the Postpay billing plan, your Cloud Billing account accrues costs and you\nare automatically charged at the end of the month, or when your costs reach an\nautomatically assigned spend cap based on your account tier.\nThe payment is charged to the payment method attached to your Postpay payments\naccount, which you can manage on the [AI Studio Billing](https://aistudio.google.com/billing) page. On the **Billing** page you'll be able\nto view your balance, due dates, and past payments, as well as make payments and\nmanage payment methods. When setting up billing for a new project, if you are eligible\nfor Postpay, you will have the option to choose between Prepay and Postpay in\nthe billing setup dialogue. After you switch a Cloud Billing account to use the Postpay billing plan, all\nprojects linked to that billing account are switched to the Postpay plan. You\ncan move an eligible account to Prepay by following the steps in Migrate to prepay. You can also\nmove a project to a billing account with a different billing plan to change\nthe charging cycle for that project; visit the Cloud documentation on [managing\nbilling for projects](https://docs.cloud.google.com/billing/docs/how-to/modify-project). You can learn more about the Postpay charging cycle in the [Cloud Billing guide](https://docs.cloud.google.com/billing/docs/how-to/billing-cycle). Migrate to prepay Google AI Studio is transitioning developer accounts from Postpay to Prepay billing for Gemini API usage. This change applies only to the Gemini API; other Google Cloud services linked to your billing account remain on Postpay. Switch to Prepay and add credits before the cutover date in your account notice to avoid service interruptions. Accounts that use only Free Tier features do not need to take action. To switch an existing Postpay account to Prepay: Go to the [AI Studio Billing](https://aistudio.google.com/billing) page. Select **Switch to Prepay** for your billing account. Purchase credits (minimum $5) to load your starting balance. To prevent service interruptions after switching, configure auto-reload to top up your credit balance when it runs low. Spend caps The Gemini API supports monthly spend caps at both the billing account tier and\nproject levels. These controls are designed to protect your account from\nunexpected overages, and the ecosystem to ensure service availability. *Note that spend caps are not available for [Invoiced (or Offline)](https://docs.cloud.google.com/billing/docs/concepts#billing_account_types)\naccounts.* Project spend caps You can set your own [project-level](/gemini-api/docs/api-key#google-cloud-projects) spend caps in AI Studio.\nThis is useful if you have multiple projects under the same billing\naccount and want to ensure each has access to enough of the cumulative spending\nlimit. Accounts with the project editor, owner, or admin [roles](https://docs.cloud.google.com/iam/docs/roles-overview) can set spend caps per\nproject in AI Studio on the [Spend](https://aistudio.google.com/spend) page\nunder **Monthly spend cap** > **Edit spend cap**. For details on the specific Google Cloud IAM permissions required to view or edit spend caps and billing information in AI Studio, see the [AI Studio troubleshooting guide](/gemini-api/docs/troubleshoot-ai-studio#iam-permissions). If you [move a project to a different billing account](https://docs.cloud.google.com/billing/docs/how-to/modify-project#change_the_billing_account_for_a_project),\nany spend cap you already set for that project will persist, but any accumulated\nspend will reset to $0 for the new billing cycle. Long-running tasks like [batch mode](/gemini-api/docs/batch-api) completions and\nagent sessions may incur overages beyond your project spend cap. Billing data processing times can be delayed in AI Studio, up to around 10\nminutes. You may experience overages beyond your project cap if billing data\nhasn't processed before more charges are accrued. Billing account tier spend caps Each tier has a maximum monthly spend limit: Usage tier Spend cap **Free** N/A **Tier 1** $250 **Tier 2** $2,000 **Tier 3** $20,000 - $100,000 Monthly usage caps are enforced for the Gemini API at the billing account level. While default limits are preset, you can [request an\nincrease](https://docs.google.com/forms/d/e/1FAIpQLSdiP6BWJyNNN65lnwnlOr-5Kv0MOFp0jLQyqi_ixVCfddqWBw/viewform)\nto accommodate higher usage. Total spend is aggregated across all linked\nprojects that have the Gemini API service enabled. After the cumulative account\ntotal reaches the tier limit, service is paused for all projects linked to that\nbilling account until the start of the next billing cycle (the 1st of each\nmonth). Evaluate your billing account spend To evaluate your historical monthly spending to determine if the new Billing\nAccount tier spend caps will impact your ongoing projects,\nfollow these steps: In the Google Cloud console, view your [Cloud Billing account Reports](https://console.cloud.google.com/billing/reports) page.\n If you have more than one billing account, at the prompt, choose the Cloud\nBilling account for which you'd like to view cost reports. The report defaults to \"Group by Service\" in the \"Current month\". You will\nsee **Gemini API** in the **Service** column and total spend in the **Usage\ncost** column of the table. To see granular costs limited to Gemini API usage, set the **Group by**\nfilter to group by **SKU**, and the **Services** filter to **Gemini API**. Adjust the **Time range by usage date** filter to your desired range to\nevaluate your historical spend in a period. Processing times Billing signals and updates don't always happen in real time. **Credit usage**: Usage costs are typically drawn down from your balance\nwithin minutes. **Payment confirmation**: While most card payments are instant, some forms\nof payment (like bank transfers) may take several days to clear. Services\nonly resume or upgrade after the purchase of credits is officially confirmed. **Tier upgrades**: After a successful payment, or when you meet the\nupgrade criteria, tier upgrades usually reflect within 10\nminutes. **Total Cost breakdown graphs**: The graphs showing your total cost\nbreakdown on both the [Billing](https://aistudio.google.com/billing) page\nand the [Spend](https://aistudio.google.com/spend) page can take up to 24\nhours to update. Read the Cloud Billing guides on [charging cycle](https://docs.cloud.google.com/billing/docs/how-to/billing-cycle#delayed-billing)\nand [transaction](https://docs.cloud.google.com/billing/docs/how-to/view-history#missing-transactions)\nlatencies to learn more about potential billing delays. Refunds Refunds aren't allowed for **Prepay** billing accounts, except when switching\naccount types. **When a Prepay account switches to the Postpay account type** (after you\nmeet the criteria and manually upgrade\nyour account), the Prepay account is closed and any remaining prepaid credits\nare automatically refunded to the payment method on file. If you [close](https://docs.cloud.google.com/billing/docs/how-to/close-or-reopen-billing-account#close-a-billing-account)\nyour Prepay account for any reason other than upgrading to Postpay, any\nremaining prepaid credits are forfeited. Purchased credits expire after 1 year. After expiration, credits are forfeited\nand can't be retrieved. **Postpay** accounts follow the [Google Cloud refund policy](https://docs.cloud.google.com/billing/docs/how-to/resolve-issues#request_a_refund). Cloud Billing accounts The Gemini API uses [Cloud Billing accounts](https://cloud.google.com/billing/docs/concepts) for billing services, which you\ncan set up directly in AI Studio.\nYou can use AI Studio to track spending, understand costs, and make payments. Tiers, rate limits, and billing account caps are all determined at the billing\naccount level. Projects and API keys All [projects](/gemini-api/docs/api-key#google-cloud-projects) linked to a Cloud\nBilling account inherit the billing account's usage tier and associated rate\nlimits and account caps. If you [change a project](https://docs.cloud.google.com/billing/docs/how-to/modify-project#change_the_billing_account_for_a_project)\nfrom one billing account to another, its tier, and subsequently rate limits and\naccount caps, will switch to the tier of the new billing account. Cumulative spend (towards all Google Cloud products) and account age across all\nprojects tied to a billing account counts towards that billing account's\ntier qualifications. You can [unlink a project](https://docs.cloud.google.com/billing/docs/how-to/modify-project#disable_billing_for_a_project)\nfrom its billing account to return to the free tier. [API keys](/gemini-api/docs/api-key) are credentials generated inside a project.\nThey have no independent billing settings; they inherit the tier limits and\nbilling status of the project. The cumulative usage from all keys within a\nproject counts toward that project's spend cap and the billing account's total\nspend. Frequently asked questions The following sections provide answers to frequently asked questions. What am I billed for? Gemini API pricing is based on the following: Input token count Output token count Cached token count Cached token storage duration For pricing information, see the [Pricing page](https://ai.google.dev/pricing). Where can I view my quota? You can view your quota and system limits in\n[AI Studio](https://aistudio.google.com/usage). How do I move to a higher rate limit tier, or request more quota? You will automatically be granted more quota when your account reaches the next\n[tier requirements](/gemini-api/docs/rate-limits#usage-tiers). Can I use the Gemini API for free in EEA (including EU), the UK, and CH? Yes, we make the free tier and paid tier available in [many regions](/gemini-api/docs/available-regions). If I set up billing with the Gemini API, will I be charged for my Google AI Studio usage? AI Studio usage remains free of charge unless users link a paid API key for\naccess to paid features.\nOnce you link a paid API key as part of a paid project in AI Studio, you will be\ncharged for AI Studio usage for that key. You can switch between Paid Tier\nprojects and Free Tier projects as needed by using the respective API keys\nlinked to each type. If I'm on the Free Tier, how do I upgrade to higher tiers? To access higher tiers, you must set up billing on your project. Click **Set up\nbilling** in Google AI Studio. This will walk you through\nselecting or creating a Cloud Billing account. If you are required to be on the\nprepaid billing model, the **Set up billing** process will guide you through the\nprocess to create your Prepay account that is linked to your Cloud Billing\naccount. Can I use 1M tokens in the free tier? The free tier for Gemini API differs based on the model selected. For now, you\ncan try the 1M token context window in the following ways: In Google AI Studio With free-of-charge plans for select models With postpaid plans Can I revert back to Free Tier after I've upgraded to higher (paid) tiers? To downgrade to the Free Tier, you can [disable billing](https://docs.cloud.google.com/billing/docs/how-to/modify-project#disable_billing_for_a_project)\non each of your projects that you want to downgrade. How can I calculate the number of tokens I'm using? Use the [`GenerativeModel.count_tokens`](/api/python/google/generativeai/GenerativeModel#count_tokens)\nmethod to count the number of tokens. Refer to the [Tokens guide](/gemini-api/docs/tokens) to learn more about tokens. If I sign up for my first Cloud Billing account through AI Studio, will I still get a Google Cloud Free Trial? When you sign up for your first ever Cloud Billing account, your [Google Cloud\nFree Trial](https://docs.cloud.google.com/free/docs/free-cloud-features#free-trial) starts\nand you are granted a $300 [Welcome credit](https://docs.cloud.google.com/billing/docs/in-product-billing-setup#welcome-credits).\nHowever, those credits can't be used to pay for AI Studio usage. You can use the\nWelcome credit to pay for other eligible services within Google Cloud (note that\nonce those credits are consumed or expire (within 90 days), any additional usage\ncosts are automatically billed to your established form of payment). Can I use my Google Cloud Welcome credit with the Gemini API? No, the Google Cloud [Welcome credit](https://docs.cloud.google.com/billing/docs/in-product-billing-setup#welcome-credits)\nor free trial credit can't be used towards the Gemini API or AI Studio. If you were granted a Google Cloud welcome credit before they became\nineligible, you are allowed to spend your remaining credits on the Gemini API\nand AI Studio up until the credits expire (after 90 days). Does the Google Cloud Free Trial apply to Gemini API usage? No, starting March 2026, Gemini API usage costs are specifically excluded from\nthe [$300 Google Cloud Free Trial](https://docs.cloud.google.com/free/docs/free-cloud-features#free-trial)\nprogram. How do Google Cloud credits work with Prepay? Prepay users must first purchase Prepaid credits before any\neligible Google Cloud credits can be applied to Gemini API usage. Once you have\nan active Prepay credit balance, Google Cloud credits that are eligible for the\nGemini API are consumed before your Prepay credit balance. When your Prepay\ncredit balance on the billing account hits $0, Google Cloud credits will no\nlonger be consumed. Not all Google Cloud credits, such as the\nGoogle Cloud Welcome credit, can be used towards Gemini API\nand AI Studio. How is billing handled? Billing for the Gemini API is handled by the [Cloud billing](https://cloud.google.com/billing/docs/concepts) system. Learn about the\nin-product Cloud Billing setup in the [Cloud Billing documentation](https://docs.cloud.google.com/billing/docs/in-product-billing-setup). Am I charged for failed requests? If your request fails with a 400 or 500 error, you won't be charged for the\ntokens used. However, the request will still count against your quota. Is `GetTokens` billed? Requests to the `GetTokens` API are not billed, and they don't count against\ninference quota. How is my Google AI Studio data handled if I have a paid API account? Refer to the [Terms of service](/gemini-api/terms#paid-services) for details on\nhow data is handled when Cloud billing is enabled (see \"How Google Uses Your\nData\" under \"Paid Services\"). Note that your Google AI Studio prompts are\ntreated under the same \"Paid Services\" terms so long as at least 1 API project\nhas billing enabled, which you can validate on the\n[Gemini API key page](https://aistudio.google.com/api-keys) if you see any\nprojects marked as \"Paid\" under \"Plan\". What is Prepaid billing and who is required to use the prepaid billing model? Prepaid billing allows users of Gemini API in AI Studio to pre-purchase credits.\nStarting Mar 23, 2026, new users to AI Studio might be required to be on the\nPrepaid billing plan. During the AI Studio Set up Billing\nprocess, the UI will guide you through the billing set up flow and will indicate\nif you are required to prepay. How do I purchase Prepay credits, and is there a minimum amount or maximum? You can purchase credits on the AI Studio Billing page. During\nthe purchase process, the UI will provide the minimum pre-purchase amount that\nis required for your region and tier level, as well as a maximum amount that can\nbe in your account at one time. Can I configure my Prepay account to automatically purchase more credits as needed? Yes, we recommend that you configure auto-reload in the AI\nStudio Billing settings. You specify a \"trigger\" credit balance (e.g., \"when my\nbalance falls below $30\") and a \"reload value\" (e.g., \"add $100\"). Can I limit the amount of automatic reload charges? Yes, Prepay users can set a Monthly Auto-Charge Limit\nwithin the **Auto-Reload** widget. When the total amount of automatic reloads in a billing\ncycle reaches this limit, the system disables auto-reload until the next month. Manual credit\npurchases do not count toward this limit. Can I get a refund for my unused credits? All Prepaid API credits expire after 1 year and cannot be refunded. Read the\nrefund policy for Prepay accounts. Do my prepaid credits expire? Yes, credits expire 12 months after their purchase date. What happens when my prepaid credit balance hits $0? All Gemini API services in all projects paid for by that Cloud Billing Prepay\naccount will stop immediately to prevent incurring more charges. Your projects\naren't automatically downgraded to the Free Tier. To restore service at your current Paid Tier level, you must purchase\nadditional credits. After you've purchased credits, you should be\nable to use the Gemini API. Note that there might be a delay while our systems update to reflect your credit balance. Optionally, to downgrade to the Free Tier, you can [disable billing](https://docs.cloud.google.com/billing/docs/how-to/modify-project#disable_billing_for_a_project)\non the projects you want to downgrade. Why did my usage stop even though my Prepay credit balance is greater than $0? You may have hit the usage limit for your current tier.\nUsage limits will increase automatically as you progress to higher tiers. Your\nGemini API AI Studio usage can also be impacted due to the status of your\nCloud Billing account. Why is my Prepay account credit balance negative? Due to the complexity of our billing and processing systems, there might be\ndelays in our ability to cut off usage after you consume\nall of your credits. This excess usage might appear as a negative credit balance\nin your AI Studio billing dashboard. If this happens, your service is paused,\nand your negative balance will be deducted from your next credit purchase. To avoid a pause in your Gemini API service, we recommend setting up\nauto-reload to automatically purchase more credits when your\ncredit balance falls below a value you specify. Can I use my Prepay credits for other Google Cloud services, like Gemini Enterprise Agent Platform? No, Prepay credits are strictly locked to Gemini API usage. Any\nother Google Cloud services you use (Compute, Storage, Gemini Enterprise Agent Platform) are billed using\nthe standard [Cloud charging cycle](https://docs.cloud.google.com/billing/docs/how-to/billing-cycle). Can I switch from Prepay to Postpay billing? No, switching from a Prepay billing plan to a Postpay billing plan is not supported. Can I switch from Postpay to Prepay billing? Yes, you can transition an existing Postpay account on the [AI Studio Billing](https://aistudio.google.com/billing) page. See Migrate to prepay for instructions. What happens to my Prepaid credits if I switch to Postpay? When you upgrade to Postpay, Cloud Billing closes your Prepay\npayments account, turns off auto-reload, and automatically\nrefunds any unused Prepay credits to you (subject to standard refund processing\ntime). Where can I see my current Prepay credit balance and transaction history? All balance management and transaction history for the Gemini API must be\ndone directly within the Google AI Studio Billing tab. Why am I seeing \"The billing account type is inactive or unsupported\"? Payments interactions on the [AI Studio Billing page](https://aistudio.google.com/billing) may be blocked and replaced with the\nmessage \"The billing account type is inactive or unsupported\" if your\nselected billing account type or billing account status is not eligible for\nthe Paid Tier in AI Studio. Check the [Cloud Console](https://console.cloud.google.com/billing/) to see your\nbilling account's status. One ineligible type could be *Free trial account*, in\nwhich case you can activate billing in AI Studio to become\neligible. One inactive state could be *Closed*, in which case you can [reopen\nthe account](https://docs.cloud.google.com/billing/docs/how-to/close-or-reopen-billing-account). Will my Gemini API usage costs show up in the Google Cloud console? Yes, Gemini API costs, alongside costs associated with any other Google Cloud\nservices that are paid for by your Cloud Billing account, are viewable on the\n[Cost management pages](https://docs.cloud.google.com/billing/docs/how-to/split-charging-cycle#cost-reports)\nin the [Cloud Billing console](https://console.cloud.google.com/billing). Note\nthat you can only manage your Prepay credit balance in AI Studio. Why isn't my Gemini API Usage showing up in the Cloud Billing Console, when I can see it in AI Studio Billing, along with the consumption of my credits? Google Cloud and AI Studio report usage data to Cloud Billing at varying\nintervals. Due to the complexity of our billing and processing systems, you\nmight see a delay between your use of services, and the usage and costs being\navailable to view in Cloud Billing. Typically, your cost details are available\nwithin a day, but can sometimes take more than 24 hours.\nLearn more about delayed billing in the [Cloud Billing documentation](https://docs.cloud.google.com/billing/docs/how-to/billing-cycle#delayed-billing). If I use other Google Cloud services with costs that are subject to a Postpay charging cycle, what happens if I miss a payment? Missing a payment for other Google Cloud services can suspend your Gemini API\naccess in AI Studio, **regardless of how many Prepaid credits you have\navailable**. AI Studio usage is powered by a Google Cloud Billing account, which\ncan share both Prepay billing for AI Studio and Postpay billing for other Cloud\nservices. An issue with your Postpay balance halts all services tied to that\naccount. Your Gemini API usage will be suspended if your Cloud Billing account\nis flagged for issues such as: A delinquent or overdue balance A declined payment An invalid or expired payment method To restore service, you must [resolve the Postpay account issue](https://docs.cloud.google.com/billing/docs/how-to/resolve-issues#resolving-declined-payments)\nin the Google Cloud Billing console. Once you resolve the issue, you will regain\naccess to your Prepaid Gemini API credits and services. Why are my projects disrupted after I canceled a Prepay setup? **Issue:** You started the flow to add Prepay capabilities to an existing\nPostpay billing account, but closed the window or canceled the process before\ncompleting the prepayment setup. Other projects linked to that billing account\nlost access to the Gemini API. **Cause:** During the transition flow, the infrastructure to support Prepay is\ncreated on your billing account immediately after you accept the confirmation\ndialog. If you don't complete the prepayment steps, the configuration remains\nin an unchargeable state. Because this state applies at the billing account\nlevel, it restricts access for all projects linked to that billing account that\nrely on Prepay services. **Resolution:** Because the account state has already changed, there is no\nautomatic way to revert the state if you abandon the payment flow. To restore\nservice to your linked projects, do one of the following: **Complete the setup:** Return to Google AI Studio, restart the billing\nsetup flow, and complete the prepayment process. After the payment is\nprocessed, the Prepay billing plan becomes active and the service is restored. **Contact Support:** If you don't want to use the Prepay billing plan and\nwant to revert your billing account back to Postpay,\n[contact Cloud Billing Support](https://cloud.google.com/support/billing) to\nmanually reset your account state. Where can I get help with billing? To get help with billing, see\n[Get Cloud billing support](https://cloud.google.com/support/billing). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-03 UTC.", "znaku_textu": 33182, "slov": 5089, "odkazu": 182, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:18", "sha256": "848ea7c2c071d689bb8a18bb1317b0e447238aff0c36c006340929d0a928609c", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/rate-limit", "https://docs.cloud.google.com/docs/starter-tier", "https://aistudio.google.com/projects", "https://aistudio.google.com/api-keys", "https://aistudio.google.com/billing", "https://aistudio.google.com/usage", "https://docs.cloud.google.com/billing/docs/concepts", "https://docs.cloud.google.com/billing/docs/in-product-billing-setup", "https://docs.cloud.google.com/billing/docs/how-to/modify-project", "https://docs.cloud.google.com/billing/docs/how-to/billing-cycle", "https://docs.cloud.google.com/iam/docs/roles-overview", "https://aistudio.google.com/spend", "https://docs.google.com/forms/d/e/1FAIpQLSdiP6BWJyNNN65lnwnlOr-5Kv0MOFp0jLQyqi_ixVCfddqWBw/viewform", "https://console.cloud.google.com/billing/reports", "https://docs.cloud.google.com/billing/docs/how-to/view-history", "https://docs.cloud.google.com/billing/docs/how-to/close-or-reopen-billing-account", "https://docs.cloud.google.com/billing/docs/how-to/resolve-issues", "https://cloud.google.com/billing/docs/concepts", "https://docs.cloud.google.com/free/docs/free-cloud-features", "https://console.cloud.google.com/", "https://console.cloud.google.com/billing/", "https://docs.cloud.google.com/billing/docs/how-to/split-charging-cycle", "https://console.cloud.google.com/billing", "https://cloud.google.com/support/billing", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/caching", "titulek": "Context caching | Gemini API | Google AI for Developers", "h1": "Context caching", "popis": "Learn how to use Context Caching in the Interactions API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/caching", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Context caching  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to use Context Caching in the Interactions API", "og:url": "https://ai.google.dev/gemini-api/docs/caching", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Context caching"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Context caching", "item": "https://ai.google.dev/gemini-api/docs/caching"}]}], "drobecky": ["Gemini API", "Context caching"], "osnova": [{"uroven": 1, "text": "Context caching"}, {"uroven": 2, "text": "Implicit caching"}], "markdown": "Context caching In a typical AI workflow, you might pass the same input tokens over and over to\na model. The Gemini API offers implicit caching to optimize performance and costs. Implicit caching Implicit caching is enabled by default for all Gemini 2.5 and newer models. It is\nsupported for both [stateful](/gemini-api/docs/text-generation#multi-turn-conversations) (using `previous_interaction_id`)\nand [stateless](/gemini-api/docs/text-generation#stateless-conversations) conversation modes.\nWe automatically pass on cost savings if your request hits caches. There is nothing you need to do\nin order to enable this. The minimum input\ntoken count for context caching is listed in the following table for each model: Model Min token limit Gemini 3.8 Flash 4,096 Gemini 3.7 Flash 4,096 Gemini 3.6 Flash 4,096 Gemini 3.5 Flash 4,096 Gemini 3.1 Pro Preview 4,096 Gemini 2.5 Flash 2,048 Gemini 2.5 Pro 2,048 To increase the chance of an implicit cache hit: Try putting large and common contents at the beginning of your prompt Try to send requests with similar prefix in a short amount of time You can see the number of tokens which were cache hits in the response object's\n`usage.total_cached_tokens` (Python and JavaScript) field. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 1692, "slov": 249, "odkazu": 130, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:46", "sha256": "b4c86be6f3cf586847a1009fe2e744e0d324796e5fe571fecd0a86db1413cca2", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/changelog", "titulek": "Release notes | Gemini API | Google AI for Developers", "h1": "Release notes", "popis": "Keep track of updates to the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/changelog", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Release notes  |  Gemini API  |  Google AI for Developers", "og:description": "Keep track of updates to the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/changelog", "og:image": "https://ai.google.dev/static/site-assets/images/release-notes.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Release notes"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Release notes", "item": "https://ai.google.dev/gemini-api/docs/changelog"}]}], "drobecky": ["Gemini API", "Release notes"], "osnova": [{"uroven": 1, "text": "Release notes"}, {"uroven": 2, "text": "September 3, 2026"}, {"uroven": 2, "text": "September 2, 2026"}, {"uroven": 2, "text": "September 1, 2026"}, {"uroven": 2, "text": "August 27, 2026"}, {"uroven": 2, "text": "August 26, 2026"}, {"uroven": 2, "text": "August 13, 2026"}, {"uroven": 2, "text": "July 30, 2026"}, {"uroven": 2, "text": "July 21, 2026"}, {"uroven": 2, "text": "July 6, 2026"}, {"uroven": 2, "text": "June 30, 2026"}, {"uroven": 2, "text": "June 24, 2026"}, {"uroven": 2, "text": "June 17, 2026"}, {"uroven": 2, "text": "June 15, 2026"}, {"uroven": 2, "text": "June 1, 2026"}, {"uroven": 2, "text": "May 28, 2026"}, {"uroven": 2, "text": "May 25, 2026"}, {"uroven": 2, "text": "May 19, 2026"}, {"uroven": 2, "text": "May 7, 2026"}, {"uroven": 2, "text": "May 6, 2026"}, {"uroven": 2, "text": "May 5, 2026"}, {"uroven": 2, "text": "May 4, 2026"}, {"uroven": 2, "text": "April 30, 2026"}, {"uroven": 2, "text": "April 22, 2026"}, {"uroven": 2, "text": "April 21, 2026"}, {"uroven": 2, "text": "April 15, 2026"}, {"uroven": 2, "text": "April 14, 2026"}, {"uroven": 2, "text": "April 2, 2026"}, {"uroven": 2, "text": "April 1, 2026"}, {"uroven": 2, "text": "March 31, 2026"}, {"uroven": 2, "text": "March 26, 2026"}, {"uroven": 2, "text": "March 25, 2026"}, {"uroven": 2, "text": "March 23, 2026"}, {"uroven": 2, "text": "March 18, 2026"}, {"uroven": 2, "text": "March 16, 2026"}, {"uroven": 2, "text": "March 12, 2026"}, {"uroven": 2, "text": "March 10, 2026"}, {"uroven": 2, "text": "March 9, 2026"}, {"uroven": 2, "text": "March 3, 2026"}, {"uroven": 2, "text": "February 26, 2026"}, {"uroven": 2, "text": "February 19, 2026"}, {"uroven": 2, "text": "February 18, 2026"}, {"uroven": 2, "text": "February 17, 2026"}, {"uroven": 2, "text": "January 29, 2026"}, {"uroven": 2, "text": "January 21, 2026"}, {"uroven": 2, "text": "January 15, 2026"}, {"uroven": 2, "text": "January 14, 2026"}, {"uroven": 2, "text": "January 13, 2026"}, {"uroven": 2, "text": "January 12, 2026"}, {"uroven": 2, "text": "January 8, 2026"}, {"uroven": 2, "text": "December 19, 2025"}, {"uroven": 2, "text": "December 17, 2025"}, {"uroven": 2, "text": "December 12, 2025"}, {"uroven": 2, "text": "December 11, 2025"}, {"uroven": 2, "text": "December 10, 2025"}, {"uroven": 2, "text": "December 9, 2025"}, {"uroven": 2, "text": "December 5, 2025"}, {"uroven": 2, "text": "December 4, 2025"}, {"uroven": 2, "text": "December 3, 2025"}, {"uroven": 2, "text": "November 20, 2025"}, {"uroven": 2, "text": "November 18, 2025"}, {"uroven": 2, "text": "November 11, 2025"}, {"uroven": 2, "text": "November 10, 2025"}, {"uroven": 2, "text": "November 6, 2025"}, {"uroven": 2, "text": "November 4, 2025"}, {"uroven": 2, "text": "October 29, 2025"}, {"uroven": 2, "text": "October 20, 2025"}, {"uroven": 2, "text": "October 17, 2025"}, {"uroven": 2, "text": "October 15, 2025"}, {"uroven": 2, "text": "October 7, 2025"}, {"uroven": 2, "text": "October 2, 2025"}, {"uroven": 2, "text": "September 29, 2025"}, {"uroven": 2, "text": "September 25, 2025"}, {"uroven": 2, "text": "September 23, 2025"}, {"uroven": 2, "text": "September 16, 2025"}, {"uroven": 2, "text": "September 10, 2025"}, {"uroven": 2, "text": "September 9, 2025"}, {"uroven": 2, "text": "August 26, 2025"}, {"uroven": 2, "text": "August 18, 2025"}, {"uroven": 2, "text": "August 14, 2025"}, {"uroven": 2, "text": "August 7, 2025"}, {"uroven": 2, "text": "July 31, 2025"}, {"uroven": 2, "text": "July 22, 2025"}, {"uroven": 2, "text": "July 17, 2025"}, {"uroven": 2, "text": "July 14, 2025"}, {"uroven": 2, "text": "July 7, 2025"}, {"uroven": 2, "text": "June 26, 2025"}, {"uroven": 2, "text": "June 24, 2025"}, {"uroven": 2, "text": "June 17, 2025"}, {"uroven": 2, "text": "June 05, 2025"}, {"uroven": 2, "text": "May 27, 2025"}, {"uroven": 2, "text": "May 20, 2025"}, {"uroven": 2, "text": "May 7, 2025"}, {"uroven": 2, "text": "May 6, 2025"}, {"uroven": 2, "text": "April 17, 2025"}, {"uroven": 2, "text": "April 16, 2025"}, {"uroven": 2, "text": "April 9, 2025"}, {"uroven": 2, "text": "April 4, 2025"}, {"uroven": 2, "text": "March 25, 2025"}, {"uroven": 2, "text": "March 12, 2025"}, {"uroven": 2, "text": "March 11, 2025"}, {"uroven": 2, "text": "March 7, 2025"}, {"uroven": 2, "text": "February 28, 2025"}, {"uroven": 2, "text": "February 25, 2025"}, {"uroven": 2, "text": "February 19, 2025"}, {"uroven": 2, "text": "February 18, 2025"}, {"uroven": 2, "text": "February 11, 2025"}, {"uroven": 2, "text": "February 6, 2025"}, {"uroven": 2, "text": "February 5, 2025"}, {"uroven": 2, "text": "January 21, 2025"}, {"uroven": 2, "text": "December 19, 2024"}, {"uroven": 2, "text": "December 11, 2024"}, {"uroven": 2, "text": "November 21, 2024"}, {"uroven": 2, "text": "November 14, 2024"}, {"uroven": 2, "text": "November 8, 2024"}, {"uroven": 2, "text": "October 31, 2024"}, {"uroven": 2, "text": "October 3, 2024"}, {"uroven": 2, "text": "September 24, 2024"}, {"uroven": 2, "text": "September 19, 2024"}, {"uroven": 2, "text": "September 17, 2024"}, {"uroven": 2, "text": "September 13, 2024"}, {"uroven": 2, "text": "August 30, 2024"}, {"uroven": 2, "text": "August 27, 2024"}, {"uroven": 2, "text": "August 9, 2024"}, {"uroven": 2, "text": "August 5, 2024"}, {"uroven": 2, "text": "August 1, 2024"}, {"uroven": 2, "text": "July 12, 2024"}, {"uroven": 2, "text": "June 27, 2024"}, {"uroven": 2, "text": "June 18, 2024"}, {"uroven": 2, "text": "June 12, 2024"}, {"uroven": 2, "text": "May 23, 2024"}, {"uroven": 2, "text": "May 14, 2024"}, {"uroven": 2, "text": "May 10, 2024"}, {"uroven": 2, "text": "April 9, 2024"}, {"uroven": 2, "text": "March 19, 2024"}, {"uroven": 2, "text": "December 13 2023"}], "markdown": "Release notes This page documents updates to the Gemini API. September 3, 2026 **Lyria 3.5 in public preview**: Released the next generation of Google's music\ngeneration model: [`lyria-3.5`](/gemini-api/docs/models/lyria-3.5):\nFull-length song generation with improved musical coherence, natural vocals,\nand fine-grained duration and structural control. The model supports text and image inputs and generates high-fidelity 44.1 kHz\nstereo audio. See the [Music generation](/gemini-api/docs/music-generation)\nguide for details and code samples. September 2, 2026 **Gemini 3.8 Flash generally available (GA)**: Released\n`gemini-3.8-flash`, our most intelligent Flash model, engineered for\nlong-horizon software engineering, autonomous agents, and complex enterprise\nworkflows. To get started, see the\n[Gemini 3.8 Flash](/gemini-api/docs/models/gemini-3.8-flash) model page and\nthe [Latest model guide](/gemini-api/docs/latest-model). September 1, 2026 **Agentic video understanding**: Released agentic video understanding for\nGemini 3.7 Flash, 3.6 Flash, and 3.5 Flash-Lite across the Interactions and\nGenerateContent APIs. The model dynamically navigates video timelines,\nrequesting transcripts, frames, or audio tracks on demand. This approach uses\nup to 88% fewer tokens for long-form content compared to static processing. To get started, see the\n[Agentic video understanding](/gemini-api/docs/video-understanding#agentic-video-understanding) guide. August 27, 2026 **Gemini Omni Flash generally available (GA)**: Released\n`gemini-omni-1.1-flash`, the GA version of our fast, conversational video\ngeneration and editing model. This release includes significant new\ncapabilities: **Video extension**: Seamlessly extend existing videos by generating\ncontinuations at the end of a clip using the `extend` task or directly\nwith a prompt. **Interpolation (first + last frame)**: Generate a video transitioning\nbetween two images using the `image_to_video` task with up to 2 images. **Resolution control**: New `resolution` parameter in `video_config`\nsupports `360p`, `720p` (default), `1080p`, and `4k` outputs.\n1080p and 4K outputs are generated using upscaling. The existing `gemini-omni-flash-preview` endpoint will be deprecated on\nSeptember 30, 2026. To get started, see the\n[Gemini Omni Flash](/gemini-api/docs/models/gemini-omni-flash) model page\nand the [omni guide](/gemini-api/docs/omni). August 26, 2026 **Gemini 3.5 Transcribe generally available (GA)**: Released two dedicated\nspeech-to-text models based on Gemini's audio understanding: **Gemini 3.5 Transcribe** (`gemini-3.5-transcribe`): High-accuracy,\nlow-latency non-streaming speech-to-text with utterance-based language\ndetection across 85+ languages, speaker diarization, word-level\ntimestamps, and custom vocabulary biasing (up to 1,000 terms). **Gemini 3.5 Transcribe Live** (`gemini-3.5-transcribe-live`):\nLow-latency, bidirectional streaming speech-to-text over WebSockets using\nthe Live API, supporting interim and finalized transcription events,\nSmart transcription mode, and multiple Voice Activity Detection (VAD)\nstrategies. To get started, see the\n[Audio transcription guide](/gemini-api/docs/transcribe), the\n[Live transcription guide](/gemini-api/docs/live-api/live-transcribe), and the\n[Gemini 3.5 Transcribe model page](/gemini-api/docs/models/gemini-3.5-transcribe). August 13, 2026 **Gemini 3.7 Flash generally available (GA)**: Released our most\nintelligent workhorse model yet for coding and agents: **Gemini 3.7 Flash** (`gemini-3.7-flash`): Substantial improvements\nacross software engineering, web development, and agentic workflows,\navailable at an introductory price through December 31, 2026. To get started, see the\n[Gemini 3.7 Flash](/gemini-api/docs/models/gemini-3.7-flash) model page\nand the [Latest model guide](/gemini-api/docs/latest-model). July 30, 2026 **Gemini Robotics ER 2 in public preview**: Released two new embodied\nreasoning model endpoints for robotics: `gemini-robotics-er-2-preview`: Advanced spatial reasoning, agentic\ncode execution, multi-step tool orchestration, video moment finding,\nprogress classification, and multi-robot coordination. `gemini-robotics-er-2-streaming-preview`: Optimized for real-time\ntext streaming using the Live API, enabling low-latency robot agents with\nbidirectional audio and video input. Both model endpoints accept text, image, video, and audio inputs and support\nfunction calling with blocking behavior for physical robot actions.\nTo get started, see the\n[Gemini Robotics ER overview](/gemini-api/docs/robotics-overview). For\nreal-time streaming use cases, see\n[Robotics with streaming](/gemini-api/docs/robotics-streaming). **Deprecation announcement**: The `gemini-robotics-er-1.6-preview` model\nwill be [shut down](/gemini-api/docs/deprecations) on August 31, 2026. July 21, 2026 **Gemini 3.6 Flash and Gemini 3.5 Flash-Lite generally available (GA)**:\nReleased stable, production-ready versions of our latest 3.x Flash models: **Gemini 3.6 Flash** (`gemini-3.6-flash`): Features improved token\nefficiency and code/agentic planning capabilities at a lower price point\nthan 3.5 Flash, resolving developer feedback around output verbosity. **Gemini 3.5 Flash-Lite** (`gemini-3.5-flash-lite`): Offers a\nlow-latency, highly cost-effective subagent option designed for\nhigh-volume automation. To learn more, see the [Latest Gemini model](/gemini-api/docs/latest-model)\nguide. **Deprecated parameters**: The sampling parameters `temperature`, `top_p`\nand `top_k` are now deprecated. See the\n[Latest Gemini Model](/gemini-api/docs/latest-model#sampling-parameter-deprecation)\nfor details. July 6, 2026 [Developer logs](/gemini-api/docs/logs-datasets) support for the\nInteractions API: logs for supported Interactions API calls are now viewable\nin the [AI Studio dashboard](https://aistudio.google.com/logs). June 30, 2026 **Gemini Omni Flash in public preview**: Released `gemini-omni-flash-preview`,\na high-performance multimodal model designed for high-speed video generation\nand conversational video editing. Using the [Interactions API](/gemini-api/docs/interactions-overview),\nyou can generate 3–10 second videos at 720p from text descriptions or animate still images,\nand then conversationally edit and refine the outputs. To get started, see the\n[Gemini Omni Flash](/gemini-api/docs/omni) guide and the\n[Gemini Omni Flash](/gemini-api/docs/models/gemini-omni-flash) model card. Released `gemini-3.1-flash-lite-image` (Nano Banana 2 Lite) to general\navailability (GA), our built-in multimodal model optimized for ultra-low\nlatency and cost-effective image generation and editing. See the [Gemini 3.1\nFlash Lite Image](/gemini-api/docs/models/gemini-3.1-flash-lite-image) model\ncard and the [Image generation](/gemini-api/docs/image-generation) guide. June 24, 2026 **Computer Use**: Launched public preview support for the\n[Computer Use](/gemini-api/docs/computer-use) tool in Gemini 3.5 Flash. This\nrelease includes simplified actions with intents, built-in support for\nbrowser, mobile, and desktop environments, configurable safety policies, and\nadvanced prompt injection detection. June 17, 2026 **Streaming support for speech generation**: Streaming via `streamGenerateContent`\n(and `stream: true` in the Interactions API) is now supported for the\n`gemini-3.1-flash-tts-preview` model. To learn more, see the\n[Text-to-Speech](/gemini-api/docs/speech-generation#streaming) guide. June 15, 2026 **Deprecation announcement**: The following image generation models are\nbeing deprecated and will be [shut down](/gemini-api/docs/deprecations) on **August 17, 2026**: **Imagen 4 and Gemini 3 Image models**:\n `imagen-4.0-generate-001` `imagen-4.0-ultra-generate-001` `imagen-4.0-fast-generate-001` To migrate your code to newer stable or preview endpoints, refer to the\n[Gemini deprecations](/gemini-api/docs/deprecations#imagen-models) page. **Deprecation announcement**: The following video generation models are\nbeing deprecated and will be [shut down](/gemini-api/docs/deprecations) on **June 30, 2026**: **Veo models**:\n `veo-2.0-generate-001` `veo-3.0-generate-001` `veo-3.0-fast-generate-001` Update your integration to either use the Veo 3.1 preview model IDs\n(`veo-3.1-generate-preview`, `veo-3.1-fast-generate-preview`) or the\n3.1 GA models available through the\n[Gemini Enterprise Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/veo/3-1-generate)\nto avoid service interruptions. **Deprecation announcement**: The experimental GMP Contextual View tool (a fixed interface for Grounding with Google Maps outputs) will [shut down](/gemini-api/docs/deprecations) on **June 15, 2026**: June 1, 2026 The following Gemini 2.0 models are now [shut down](/gemini-api/docs/deprecations): `gemini-2.0-flash` `gemini-2.0-flash-001` `gemini-2.0-flash-lite` `gemini-2.0-flash-lite-001` Use [`gemini-3.5-flash`](/gemini-api/docs/models/gemini-3.5-flash) or\n[`gemini-3.1-flash-lite`](/gemini-api/docs/models/gemini-3.1-flash-lite)\ninstead. May 28, 2026 Released `gemini-3.1-flash-image` (Nano Banana 2) and `gemini-3-pro-image`\n(Nano Banana Pro), the generally available (GA) versions of our native\nvisual models, [Gemini 3.1 Flash Image](/gemini-api/docs/models/gemini-3.1-flash-image)\nand [Gemini 3 Pro Image](/gemini-api/docs/models/gemini-3-pro-image). **Video-to-image generation support**: You can now pass a video file (via\ndirect upload or as a public YouTube URL) as multimodal context alongside a\ntext prompt to generate high-quality thumbnails, cinematic movie posters, or\nsummary infographics. This feature is supported exclusively on the\n`gemini-3.1-flash-image` model. To learn more, see the\n[Video-to-image generation](/gemini-api/docs/image-generation#video-to-image)\nguide. Deprecation announcement: The `gemini-3.1-flash-image-preview` and\n`gemini-3-pro-image-preview` models are deprecated\nand will be [shut down](/gemini-api/docs/deprecations) on June 25, 2026. May 25, 2026 The `gemini-3.1-flash-lite-preview` model has been\n[shut down](/gemini-api/docs/deprecations). Use\n[`gemini-3.1-flash-lite`](/gemini-api/docs/models/gemini-3.1-flash-lite) instead. May 19, 2026 Released `gemini-3.5-flash`, the generally available (GA) version of\n[Gemini 3.5 Flash](/gemini-api/docs/models/gemini-3.5-flash),\nour most intelligent model for sustained frontier performance on\nagentic and coding tasks. This is now the model behind `gemini-flash-latest`. Launched the **Managed Agents in the Gemini API** in public preview. This enables\ndevelopers to build and deploy autonomous, stateful agents that run in\nsecure, isolated Google-hosted Linux sandbox environments. To learn more,\nsee the [Agents overview](/gemini-api/docs/agents) page and the\n[Quickstart](/gemini-api/docs/managed-agents-quickstart). Released the general-purpose **Antigravity Agent** managed agent,\n[`antigravity-preview-05-2026`](/gemini-api/docs/models/antigravity-preview-05-2026), in public preview.\nThe Antigravity agent can autonomously plan, reason, write and execute code,\nmanage files, and browse the web inside its sandbox container. See the\n[Antigravity Agent](/gemini-api/docs/antigravity-agent) guide for code\nsamples and specifications. May 7, 2026 Released `gemini-3.1-flash-lite`, the generally available (GA) version of\n[Gemini 3.1 Flash-Lite](/gemini-api/docs/models/gemini-3.1-flash-lite),\noptimized for speed, scale, and cost efficiency. Deprecation announcement: The `gemini-3.1-flash-lite-preview` model is\ndeprecating on 5/11/26 and will be\n[shut down](/gemini-api/docs/deprecations) on May 25, 2026. May 6, 2026 **Upcoming breaking change**: The [Interactions API](/gemini-api/docs/interactions-overview)\nrequest and response schema (`outputs` → `steps`) and output format\nconfiguration (`response_format`) are changing. The new schema becomes the\ndefault on **May 26** and the legacy schema will be removed on **June 8**.\nSee the\n[migration guide](/gemini-api/docs/interactions-breaking-changes-may-2026)\nfor details. May 5, 2026 Updated **File Search** to support multimodal search. You can now natively\nembed and search through images using the `gemini-embedding-2` model.\nGrounding metadata now includes `media_id` for visual citations and\n`page_numbers` that indicate where information is found. To learn\nmore, see the [File Search](/gemini-api/docs/file-search) guide. May 4, 2026 Launched event-driven [Webhooks](/gemini-api/docs/webhooks) support in the\nGemini API to replace polling workflows for the Batch API and long-running\noperations. April 30, 2026 The `gemini-robotics-er-1.5-preview` model has been\n[shut down](/gemini-api/docs/deprecations). Use\n[`gemini-robotics-er-1.6-preview`](/gemini-api/docs/models/gemini-robotics-er-1.6-preview) instead. April 22, 2026 Released `gemini-embedding-2` as generally available\n(GA). To learn more, see the [Embeddings](/gemini-api/docs/embeddings) page. April 21, 2026 Released new versions of the [Deep Research](/gemini-api/docs/deep-research)\nagent with collaborative planning, visualization support, MCP server\nintegration, and File Search: [`deep-research-preview-04-2026`](/gemini-api/docs/models/deep-research-preview-04-2026): Designed for\nspeed and efficiency, ideal to be streamed back to a client UI. [`deep-research-max-preview-04-2026`](/gemini-api/docs/models/deep-research-max-preview-04-2026): Maximum\ncomprehensiveness for automated context gathering and synthesis. April 15, 2026 Launched [Gemini 3.1 Flash TTS Preview](/gemini-api/docs/models/gemini-3.1-flash-tts-preview), our cost-efficient,\nexpressive, and steerable text to speech model. Read the\n[Text-to-Speech](/gemini-api/docs/speech-generation) docs to learn more. April 14, 2026 Released `gemini-robotics-er-1.6-preview`, our updated robotics model.\nIt now has new capabilities like instrument reading, improved spatial and\nphysical reasoning capabilities. To learn more, see\n[Gemini Robotics ER](/gemini-api/docs/robotics-overview) page and the\n[blog](https://deepmind.google/blog/gemini-robotics-er-1-6). Deprecation announcement: The `gemini-robotics-er-1.5-preview` model\nwill be [shut down](/gemini-api/docs/deprecations) on April 30, 2026 at 9AM\nPST. April 2, 2026 Released `gemma-4-26b-a4b-it` and `gemma-4-31b-it`, available on\n[AI Studio](https://aistudio.google.com) and through the Gemini API,\nas part of the [Gemma 4](https://ai.google.dev/gemma/docs/core) launch. April 1, 2026 Introduced the new [Flex](/gemini-api/docs/flex-inference) and [Priority](/gemini-api/docs/priority-inference) inference tiers, offering more options\nfor optimizing cost or latency. March 31, 2026 Launched Veo 3.1 Lite Preview, [`veo-3.1-lite-generate-preview`](/gemini-api/docs/models/veo-3.1-lite-generate-preview), our most\ncost-efficient [video generation](/gemini-api/docs/video) model, designed\nfor rapid iteration and building high-volume applications. The `gemini-2.5-flash-lite-preview-09-2025` model has been shut down. Use\n[`gemini-3.1-flash-lite-preview`](/gemini-api/docs/models/gemini-3.1-flash-lite-preview) instead. March 26, 2026 Released [`gemini-3.1-flash-live-preview`](/gemini-api/docs/models/gemini-3.1-flash-live-preview), the latest\naudio-to-audio (A2A) model designed for real-time dialogue and voice-first\nAI applications. Read the [Live API](/gemini-api/docs/live-api) docs to get\nstarted. March 25, 2026 Launched [Lyria 3](/gemini-api/docs/music-generation) music generation\nmodels: [`lyria-3-clip-preview`](/gemini-api/docs/models/lyria-3-clip-preview)\n(30-second clips) and [`lyria-3-pro-preview`](/gemini-api/docs/models/lyria-3-pro-preview)\n(full-length songs). Both models accept text and image inputs and generate\nhigh-quality, 48kHz stereo audio. See the\n[Music generation](/gemini-api/docs/music-generation) guide for details and\ncode samples. March 23, 2026 Rolled out [Prepay and Postpay billing plans](/gemini-api/docs/billing) in\nAI Studio. Existing accounts may be affected; read the [Billing](/gemini-api/docs/billing) documentation for more information. March 18, 2026 Released the new [Built-in Tools and Function Calling Combination](/gemini-api/docs/tool-combination) feature, making it possible\nto use Gemini's built-in tools alongside custom function calling\ntools in a single API call. [Grounding with Google Maps](/gemini-api/docs/maps-grounding#supported_models)\nis now supported for Gemini 3 models going forward. March 16, 2026 Introduced revamped [Usage Tiers](/gemini-api/docs/billing#about-billing)\nand [Billing Account spend caps](/gemini-api/docs/billing#tier-spend-caps)\nfor a better user billing experience. March 12, 2026 Introduced [project-level spend caps](/gemini-api/docs/billing#project-spend-caps) to billing in AI Studio. March 10, 2026 Released `gemini-embedding-2-preview`, our first multimodal embedding model.\nIt supports text, image, video, audio, and PDF inputs,\nmapping all modalities into a unified embedding space. To learn more, see\n[Embeddings](/gemini-api/docs/embeddings). Deprecation announcement: The `gemini-2.5-flash-lite-preview-09-2025` model\nwill be [shut down](/gemini-api/docs/deprecations) on March 31, 2026. March 9, 2026 The Gemini 3 Pro Preview model has been [shut down](/gemini-api/docs/deprecations). The `gemini-3-pro-preview` now points to\n[`gemini-3.1-pro-preview`](/gemini-api/docs/models/gemini-3.1-pro-preview). March 3, 2026 Launched Gemini 3.1 Flash-Lite Preview, the first Flash-Lite model in the\nGemini 3 series. Read the [model page](/gemini-api/docs/models/gemini-3.1-flash-lite-preview) for specs, specific\nupdates, and developer guidance. February 26, 2026 Launched Nano Banana 2, [Gemini 3.1 Flash Image Preview](/gemini-api/docs/models/gemini-3.1-flash-image-preview), a high-efficiency\nmodel optimized for speed and high-volume use cases. Deprecation announcement: Gemini 3 Pro Preview (`gemini-3-pro-preview`)\nwill be [shut down](/gemini-api/docs/deprecations) March 9, 2026. February 19, 2026 Released [Gemini 3.1 Pro Preview](/gemini-api/docs/models/gemini-3.1-pro-preview), our latest iteration in\nthe new Gemini 3 series family. Launched a separate endpoint `gemini-3.1-pro-preview-customtools`, which is\nbetter at prioritizing custom tools, for users building with a mix of bash\nand tools. February 18, 2026 Deprecation announcement: The following models will be\n[shut down](/gemini-api/docs/deprecations) June 1, 2026: `gemini-2.0-flash` `gemini-2.0-flash-001` `gemini-2.0-flash-lite` `gemini-2.0-flash-lite-001` February 17, 2026 The following models are [shut down](/gemini-api/docs/deprecations): `gemini-2.5-flash-preview-09-25` `imagen-4.0-generate-preview-06-06` `imagen-4.0-ultra-generate-preview-06-06` January 29, 2026 Launched support for the Computer Use tool in `gemini-3-pro-preview` and\n`gemini-3-flash-preview`. January 21, 2026 Changed the `latest` aliases: `gemini-pro-latest` switched to `gemini-3-pro-preview` `gemini-flash-latest` switched to `gemini-3-flash-preview` January 15, 2026 Deprecation announcement: The following models will be\n[shut down](/gemini-api/docs/deprecations) February 17, 2026: `gemini-2.5-flash-preview-09-25` `imagen-4.0-generate-preview-06-06` `imagen-4.0-ultra-generate-preview-06-06` The `gemini-2.5-flash-image-preview` model has been shut down. January 14, 2026 The `text-embedding-004` model has been [shut down](/gemini-api/docs/deprecations). January 13, 2026 Added 4k output resolutions for [Veo](/gemini-api/docs/video) and more\nsupport for portrait videos in all resolutions. January 12, 2026 Launched model lifecycle feature. Some models will now specify the lifecycle\nstage and deprecation timeline. See the following documentation for more\ninformation: [Model stages](https://ai.google.dev/api/generate-content#ModelStatus) January 8, 2026 Launched support for Cloud Storage buckets and any public and private DB\npre-signed URL as data input source for the Gemini API. The file size limit\nhas also increased from 20MB to 100MB. For details, see [File input methods\nguide](/gemini-api/docs/file-input-methods). December 19, 2025 Introduced a breaking change to the Interactions API in\nv1beta. The `total_reasoning_tokens` field has been renamed to\n`total_thought_tokens` to better align with the concept of \"thoughts\" in\nthinking models. December 17, 2025 Launched Gemini 3 Flash Preview, `gemini-3-flash-preview`, delivering fast\nfrontier-class performance that rivals larger models at a fraction of the\ncost. With upgraded visual and spatial reasoning, and agentic coding\ncapabilities. Read the documentation on some new features, including: [Multimodal function responses](/gemini-api/docs/function-calling#multimodal) [Code execution with images](/gemini-api/docs/code-execution#images) December 12, 2025 Released `gemini-2.5-flash-native-audio-preview-12-2025`,\na new native audio model for the Live API. This update improves the model's\nability to handle complex workflows. To learn more, see the\n[Live API guide](/gemini-api/docs/live-guide) and\n[Gemini 2.5 Flash Native Audio](/gemini-api/docs/models/gemini-2.5-flash-live). December 11, 2025 Launched the Interactions API. This API provides a unified interface\nfor interacting with Gemini models and agents. To learn more, see the\n[Interactions API](/gemini-api/docs/interactions-overview) guide. Launched the Gemini Deep Research agent in preview. It can\nautonomously plan, execute, and synthesize results for multi-step research\ntasks. See the [Deep Research](/gemini-api/docs/deep-research) guide for\ndetails. December 10, 2025 Launched enhancements to our [text-to-speech models](/gemini-api/docs/speech-generation), Gemini 2.5 Flash TTS preview\n(optimized for low latency) and Gemini 2.5 Pro TTS preview (optimized for\nquality), including enhanced expressivity, precision pacing, and seamless\ndialogue. December 9, 2025 The following Gemini Live API models are now shut down:\n `gemini-2.0-flash-live-001` `gemini-live-2.5-flash-preview` December 5, 2025 Gemini 3 billing for [Grounding with Google Search](/gemini-api/docs/google-search) will begin on January 5, 2026. December 4, 2025 Deprecation announcement: The `gemini-2.5-flash-image-preview` model will be\nshut down January 15, 2026. December 3, 2025 Deprecation announcement: The `text-embedding-004` model will be shut down\nJanuary 14, 2026. November 20, 2025 Released Gemini 3 Pro Image Preview, `gemini-3-pro-image-preview`, the\nnext iteration to the Nano Banana model. Read the [Image generation](/gemini-api/docs/image-generation) page for more details. November 18, 2025 Launched the first Gemini 3 series model, `gemini-3-pro-preview`, our\nstate-of-the-art reasoning and multimodal understanding model with powerful\nagentic and coding capabilities. In addition to improvements in intelligence and performance,\nGemini 3 Pro Preview introduces new behavior around: [Media resolution](/gemini-api/docs/media-resolution) [Thought signatures](/gemini-api/docs/thought-signatures) [Thinking levels](/gemini-api/docs/thinking#thinking-levels) Read the [Gemini 3 Developer Guide](/gemini-api/docs/gemini-3) for\nmigration, new features, and specs. November 11, 2025 Deprecation announcement: The following models will be shut down: November 12: `veo-3.0-fast-generate-preview` `veo-3.0-generate-preview` November 14: `gemini-2.0-flash-exp-image-generation` `gemini-2.0-flash-preview-image-generation` November 10, 2025 The following model is shut down: `imagen-3.0-generate-002` Use [Imagen 4](/gemini-api/docs/imagen#imagen-4) instead. Refer to the\n[Gemini deprecations table](/gemini-api/docs/deprecations) for more details. November 6, 2025 Launched the File Search API to public preview, enabling developers to\nground responses in their own data. Read the new [File Search](/gemini-api/docs/file-search) page for more info. November 4, 2025 For [Gemini 2.5 Flash Image](/gemini-api/docs/image-generation), the input\ntoken count for images has been reduced from 1290 to 258, lowering the cost\nof image editing. Deprecation announcement: The following models will be shut down: November 18th: `gemini-2.5-flash-lite-preview-06-17` `gemini-2.5-flash-preview-05-20` December 2nd: `gemini-2.0-flash-thinking-exp` `gemini-2.0-flash-thinking-exp-01-21` `gemini-2.0-flash-thinking-exp-1219` `gemini-2.5-pro-preview-03-25` `gemini-2.5-pro-preview-05-06` `gemini-2.5-pro-preview-06-05` December 9th: `gemini-2.0-flash-lite-preview` `gemini-2.0-flash-lite-preview-02-05` `gemini-2.0-flash-exp` `gemini-2.0-pro-exp` `gemini-2.0-pro-exp-02-05` October 29, 2025 Launched the new [logging and datasets](/gemini-api/docs/logs-datasets) tool\nfor the Gemini API. October 20, 2025 The following Gemini Live API models are now shut down: `gemini-2.5-flash-preview-native-audio-dialog` `gemini-2.5-flash-exp-native-audio-thinking-dialog` You can use `gemini-2.5-flash-native-audio-preview-09-2025` instead. Deprecation announcement: Shut down for `gemini-2.0-flash-live-001` and\n`gemini-live-2.5-flash-preview` coming December 09, 2025. October 17, 2025 **Grounding with Google Maps** is now\ngenerally available. For more information, see\n[Grounding with Google Maps](/gemini-api/docs/maps-grounding) documentation. October 15, 2025 Released [Veo 3.1 and 3.1 Fast](/gemini-api/docs/video#veo-3.1) models in\npublic preview, with new features including: Extending Veo-created videos. Referencing up to three images to generate a video. Providing first and last frame images to generate videos from. This launch also added more options for Veo 3 output video durations: 4, 6,\nand 8 seconds. Deprecation announcement: Shut down for `veo-3.0-generate-preview` and\n`veo-3.0-fast-generate-preview` coming November 12, 2025. October 7, 2025 Launched [Gemini 2.5 Computer Use Preview](/gemini-api/docs/computer-use) October 2, 2025 Launched Gemini 2.5 Flash Image GA: [Image Generation with Gemini](/gemini-api/docs/image-generation) September 29, 2025 The following Gemini 1.5 models are now shut down:\n `gemini-1.5-pro` `gemini-1.5-flash-8b` `gemini-1.5-flash` September 25, 2025 Released Gemini Robotics ER 1.5 model in preview. See the\n[Robotics overview](/gemini-api/docs/robotics-overview)\nto learn about how to use the model for your robotics application. Launched following preview models: `gemini-2.5-flash-preview-09-2025` `gemini-2.5-flash-lite-preview-09-2025` See the [Models](/gemini-api/docs/models) page for details. September 23, 2025 Released `gemini-2.5-flash-native-audio-preview-09-2025`,\na new native audio model for the Live API with improved function calling\nand speech cut off handling. To learn more, see the\n[Live API guide](/gemini-api/docs/live-guide) and\n[Gemini 2.5 Flash Native Audio](/gemini-api/docs/models#gemini-2.5-flash-native-audio). September 16, 2025 Deprecation announcement: The following models will be shut down in October 2025: `embedding-001` `embedding-gecko-001` `gemini-embedding-exp-03-07` (`gemini-embedding-exp`) See the [Embeddings](/gemini-api/docs/embeddings) page for details on the latest embeddings\nmodel. September 10, 2025 Released support for the\n[Embeddings model in Batch API](/gemini-api/docs/batch-api#batch-embedding),\nand added Batch API to the\n[OpenAI compatibility library](/gemini-api/docs/openai#batch) for even\neasier ways to get started with batch queries. September 9, 2025 Launched Veo 3 and Veo 3 Fast GA, with lower pricing and new options for\naspect ratios, resolution, and seeding. Read the\n[Veo documentation](/gemini-api/docs/video#model-features) for more\ninformation. August 26, 2025 Launched [Gemini 2.5 Image Preview](/gemini-api/docs/models#gemini-2.5-flash-image-preview),\nour latest native image generation model. August 18, 2025 Released [URL context tool](/gemini-api/docs/url-context) to general\navailability (GA), a tool for providing URLs as additional context to\nprompts. Support for using URL context with the `gemini-2.0-flash` model\n(available during experimental release) will be discontinued in one week. August 14, 2025 Released Imagen 4 Ultra, Standard and Fast models as generally available\n(GA). To learn more, see the [Imagen](/gemini-api/docs/imagen) page. August 7, 2025 `allow_adult` setting in Image to Video generation are now available in\nrestricted regions. See the\n[Veo](/gemini-api/docs/video?example=dialogue#veo-model-parameters)\npage for details. July 31, 2025 Launched image-to-video generation for the Veo 3 Preview model. Released Veo 3 Fast Preview model. To learn more about Veo 3, visit the [Veo](/gemini-api/docs/video) page. July 22, 2025 Released `gemini-2.5-flash-lite`, our fast, low-cost, high-performance Gemini\n2.5 model. To learn more, see [Gemini 2.5\nFlash-Lite](/gemini-api/docs/models#gemini-2.5-flash-lite). July 17, 2025 Launched `veo-3.0-generate-preview`, the latest update to Veo introducing\nvideo with audio generation. To learn more about Veo 3, visit the [Veo](/gemini-api/docs/video) page. Increased rate limits for Imagen 4 Standard and Ultra. Visit the\n[Rate limits](/gemini-api/docs/rate-limits) page for more details. July 14, 2025 Released `gemini-embedding-001`, the stable version of our\ntext embedding model. To learn more, see\n[embeddings](/gemini-api/docs/embeddings). The `gemini-embedding-exp-03-07`\nmodel will be deprecated on August 14, 2025. July 7, 2025 Launched Gemini API Batch Mode. Batch up requests and send them to process\nasynchronously. To learn more, see [Batch Mode](/gemini-api/docs/batch-mode). June 26, 2025 The preview models `gemini-2.5-pro-preview-05-06` and\n`gemini-2.5-pro-preview-03-25` are now redirecting to\nthe latest stable version `gemini-2.5-pro`. `gemini-2.5-pro-exp-03-25` is shut down. June 24, 2025 Released Imagen 4 Ultra and Standard Preview models. To learn more, see the\n[Image generation](/gemini-api/docs/image-generation) page. June 17, 2025 Released `gemini-2.5-pro`, the stable version of our most powerful\nmodel, now with adaptive thinking. To learn more, see\n[Gemini 2.5 Pro](/gemini-api/docs/models#gemini-2.5-pro)\nand [Thinking](/gemini-api/docs/thinking). `gemini-2.5-pro-preview-05-06`\nwill be redirected to `gemini-2.5-pro` on June 26, 2025. Released `gemini-2.5-flash`, our first stable 2.5 Flash model. To learn\nmore, see [Gemini 2.5 Flash](/gemini-api/docs/models#gemini-2.5-flash).\n`gemini-2.5-flash-preview-04-17` will be deprecated on July 15, 2025. Released `gemini-2.5-flash-lite-preview-06-17`, a low-cost, high-performance\nGemini 2.5 model. To learn more, see [Gemini 2.5 Flash-Lite\nPreview](/gemini-api/docs/models#gemini-2.5-flash-lite). June 05, 2025 Released `gemini-2.5-pro-preview-06-05`, a new version of our most powerful\nmodel, now with adaptive thinking. To learn more, see\n[Gemini 2.5 Pro Preview](/gemini-api/docs/models#gemini-2.5-pro-preview-06-05)\nand [Thinking](/gemini-api/docs/thinking).\n`gemini-2.5-pro-preview-05-06` will be redirected to `gemini-2.5-pro` on\nJune 26, 2025. May 27, 2025 The last available tuning model, Gemini 1.5 Flash 001, has been shut down.\nTuning is no longer supported on any models.\nSee [Fine tuning with the Gemini API](/gemini-api/docs/model-tuning). May 20, 2025 **API updates:** Launched support for\n[custom video preprocessing](/gemini-api/docs/video-understanding#customize-video-processing)\nusing clipping intervals and configurable frame rate sampling. Launched multi-tool use, which supports configuring\n[code execution](/gemini-api/docs/code-execution) and\n[Grounding with Google Search](/gemini-api/docs/grounding) on the same\n`generateContent` request. Launched support for\n[asynchronous function calls](/gemini-api/docs/live-tools#async-function-calling)\nin the Live API. Launched an experimental\n[URL context tool](/gemini-api/docs/url-context)\nfor providing URLs as additional context to prompts. **Model updates:** Released `gemini-2.5-flash-preview-05-20`, a Gemini\n[preview](/gemini-api/docs/models#model-versions) model optimized for\nprice-performance and adaptive thinking. To learn more, see\n[Gemini 2.5 Flash Preview](/gemini-api/docs/models#gemini-2.5-flash-preview)\nand [Thinking](/gemini-api/docs/thinking). Released the\n[`gemini-2.5-pro-preview-tts`](/gemini-api/docs/models#gemini-2.5-pro-preview-tts)\nand\n[`gemini-2.5-flash-preview-tts`](/gemini-api/docs/models#gemini-2.5-flash-preview-tts)\nmodels, which are capable of\n[generating speech](/gemini-api/docs/speech-generation) with one or two\nspeakers. Released the `lyria-realtime-exp` model, which\n[generates music](/gemini-api/docs/music-generation) in real time. Released `gemini-2.5-flash-preview-native-audio-dialog` and\n`gemini-2.5-flash-exp-native-audio-thinking-dialog`,\nnew Gemini models for the Live API with native audio output capabilities. To\nlearn more, see the\n[Live API guide](/gemini-api/docs/live-guide#native-audio-output) and\n[Gemini 2.5 Flash Native Audio](/gemini-api/docs/models#gemini-2.5-flash-native-audio). Released `gemma-3n-e4b-it` preview, available on\n[AI Studio](https://aistudio.google.com) and through the Gemini API,\nas part of the [Gemma 3n](https://ai.google.dev/gemma/docs/3n) launch. May 7, 2025 Released `gemini-2.0-flash-preview-image-generation`, a preview model for\ngenerating and editing images. To learn more, see [Image\ngeneration](https://ai.google.dev/gemini-api/docs/image-generation) and\n[Gemini 2.0 Flash Preview Image\nGeneration](https://ai.google.dev/gemini-api/docs/models#gemini-2.0-flash-preview-image-generation). May 6, 2025 Released `gemini-2.5-pro-preview-05-06`, a new version of our most powerful\nmodel, with improvements on code and function calling. `gemini-2.5-pro-preview-03-25`\nwill automatically point to the new version of the model. April 17, 2025 Released `gemini-2.5-flash-preview-04-17`, a Gemini\n[preview](/gemini-api/docs/models#model-versions) model optimized for\nprice-performance and adaptive thinking. To learn more, see\n[Gemini 2.5 Flash Preview](/gemini-api/docs/models#gemini-2.5-flash-preview)\nand [Thinking](/gemini-api/docs/thinking). April 16, 2025 Launched context caching for\n[Gemini 2.0 Flash](/gemini-api/docs/models#gemini-2.0-flash). April 9, 2025 **Model updates:** Released `veo-2.0-generate-001`, a generally available (GA) text- and\nimage-to-video model, capable of generating detailed and artistically\nnuanced videos. To learn more, see the [Veo docs](/gemini-api/docs/video). Released `gemini-2.0-flash-live-001`, a public preview version of the\n[Live API](/gemini-api/docs/live) model with billing enabled. **Enhanced Session Management and Reliability** **Session Resumption:** Keep sessions alive across temporary network\ndisruptions. The API now supports server-side session state storage (for\nup to 24 hours) and provides handles (session_resumption) to reconnect\nand resume where you left off. **Longer Sessions via Context Compression:** Enable extended\ninteractions beyond previous time limits. Configure context window\ncompression with a sliding window mechanism to automatically manage\ncontext length, preventing abrupt terminations due to context limits. **Graceful Disconnect Notification:** Receive a `GoAway` server\nmessage indicating when a connection is about to close, allowing for\ngraceful handling before termination. **More Control over Interaction Dynamics** **Configurable Voice Activity Detection (VAD):** Choose sensitivity\nlevels or disable automatic VAD entirely and use new client events\n(`activityStart`, `activityEnd`) for manual turn control. **Configurable Interruption Handling:** Decide whether user input\nshould interrupt the model's response. **Configurable Turn Coverage:** Choose whether the API processes all\naudio and video input continuously or only captures it when the end-user\nis detected speaking. **Configurable Media Resolution:** Optimize for quality or token usage\nby selecting the resolution for input media. **Richer Output and Features** **Expanded Voice & Language Options:** Choose from two new voices and\n30 new languages for audio output. The output language is now\nconfigurable within `speechConfig`. **Text Streaming:** Receive text responses incrementally as they are\ngenerated, enabling faster display to the user. **Token Usage Reporting:** Gain insights into usage with detailed\ntoken counts provided in the `usageMetadata` field of server messages,\nbroken down by modality and prompt or response phases. April 4, 2025 Released `gemini-2.5-pro-preview-03-25`, a public preview Gemini 2.5 Pro version\nwith billing enabled. You can continue to use `gemini-2.5-pro-exp-03-25` on\nthe free tier. March 25, 2025 Released `gemini-2.5-pro-exp-03-25`, a public experimental Gemini model\nwith thinking mode always on by default.\nTo learn more, see\n[Gemini 2.5 Pro Experimental](/gemini-api/docs/models#gemini-2.5-pro-preview-03-25). March 12, 2025 **Model updates:** Launched an experimental [Gemini 2.0 Flash](/gemini-api/docs/image-generation#gemini)\nmodel capable of image generation and editing. Released `gemma-3-27b-it`, available on\n[AI Studio](https://aistudio.google.com) and through the Gemini API,\nas part of the [Gemma 3](https://ai.google.dev/gemma/docs/core) launch. **API updates:** Added support for\n[YouTube URLs](/gemini-api/docs/vision#youtube) as a media source. Added support for including an\n[inline video](/gemini-api/docs/vision#inline-video) of less than 20MB. March 11, 2025 **SDK updates:** Released the\n[Google Gen AI SDK for TypeScript and JavaScript](https://googleapis.github.io/js-genai)\nto public preview. March 7, 2025 **Model updates:** Released `gemini-embedding-exp-03-07`, an\n[experimental](/gemini-api/docs/models/experimental-models)\nGemini-based embeddings model in public preview. February 28, 2025 **API updates:** Support for [Search as a tool](/gemini-api/docs/grounding)\nadded to `gemini-2.0-pro-exp-02-05`, an experimental model based on\nGemini 2.0 Pro. February 25, 2025 **Model updates:** Released `gemini-2.0-flash-lite`, a generally available (GA) version of\n[Gemini 2.0 Flash-Lite](/gemini-api/docs/models/gemini#gemini-2.0-flash-lite),\nwhich is optimized for speed, scale, and cost efficiency. February 19, 2025 **AI Studio updates:** Support for\n[additional regions](https://ai.google.dev/gemini-api/docs/available-regions)\n(Kosovo, Greenland and Faroe Islands). **API updates:** Support for\n[additional regions](https://ai.google.dev/gemini-api/docs/available-regions)\n(Kosovo, Greenland and Faroe Islands). February 18, 2025 **Model updates:** Gemini 1.0 Pro is no longer supported. For the list of supported models, see\n[Gemini models](/gemini-api/docs/models/gemini). February 11, 2025 **API updates:** Updates on the\n[OpenAI libraries compatibility](https://ai.google.dev/gemini-api/docs/openai). February 6, 2025 **Model updates:** Released `imagen-3.0-generate-002`, a generally available (GA) version of\n[Imagen 3 in the Gemini API](/gemini-api/docs/imagen). **SDK updates:** Released the [Google Gen AI SDK for Java](https://github.com/googleapis/java-genai)\nfor public preview. February 5, 2025 **Model updates:** Released `gemini-2.0-flash-001`, a generally available (GA) version of\n[Gemini 2.0 Flash](/gemini-api/docs/models/gemini#gemini-2.0-flash) that\nsupports text-only output. Released `gemini-2.0-pro-exp-02-05`,\nan [experimental](/gemini-api/docs/models/experimental-models) public\npreview version of Gemini 2.0 Pro. Released `gemini-2.0-flash-lite-preview-02-05`, an experimental public\npreview [model](/gemini-api/docs/models/gemini#gemini-2.0-flash-lite)\noptimized for cost efficiency. **API updates:** Added\n[file input and graph output](/gemini-api/docs/code-execution#input-output)\nsupport to code execution. **SDK updates:** Released the\n[Google Gen AI SDK for Python](https://googleapis.github.io/python-genai/)\nto general availability (GA). January 21, 2025 **Model updates:** Released `gemini-2.0-flash-thinking-exp-01-21`, the latest preview version of\nthe model behind the\n[Gemini 2.0 Flash Thinking Model](/gemini-api/docs/thinking). December 19, 2024 **Model updates:** Released Gemini 2.0 Flash Thinking Mode for public preview. Thinking Mode is\na test-time compute model that lets you see the model's thought process\nwhile it generates a response, and produces responses with stronger\nreasoning capabilities. Read more about Gemini 2.0 Flash Thinking Mode in our [overview\npage](/gemini-api/docs/thinking-mode). December 11, 2024 **Model updates:** Released [Gemini 2.0 Flash Experimental](/gemini-api/docs/models/gemini#gemini-2.0-flash)\nfor public preview. Gemini 2.0 Flash Experimental's partial list of features includes:\n Twice as fast as Gemini 1.5 Pro Bidirectional streaming with our Live API Multimodal response generation in the form of text, images, and speech Built-in tool use with multi-turn reasoning to use features like code\nexecution, Search, function calling, and more Read more about Gemini 2.0 Flash in our [overview\npage](/gemini-api/docs/models/gemini-v2). November 21, 2024 **Model updates:** Released `gemini-exp-1121`, an even more powerful experimental Gemini API model. **Model updates:** Updated the `gemini-1.5-flash-latest` and `gemini-1.5-flash` model aliases\nto use `gemini-1.5-flash-002`.\n Change to `top_k` parameter: The `gemini-1.5-flash-002`\nmodel supports `top_k` values between 1 and 41 (exclusive).\nValues greater than 40 will be changed to 40. November 14, 2024 **Model updates:** Released `gemini-exp-1114`, a powerful experimental Gemini API model. November 8, 2024 **API updates:** Added [support for Gemini](/gemini-api/docs/openai) in the OpenAI libraries / REST API. October 31, 2024 **API updates:** Added [support for Grounding with Google Search](/gemini-api/docs/grounding). October 3, 2024 **Model updates:** Released `gemini-1.5-flash-8b-001`, a stable version of our smallest Gemini\nAPI model. September 24, 2024 **Model updates:** Released `gemini-1.5-pro-002` and `gemini-1.5-flash-002`, two new stable\nversions of Gemini 1.5 Pro and 1.5 Flash, for general availability. Updated the `gemini-1.5-pro-latest` model code to use `gemini-1.5-pro-002`\nand the `gemini-1.5-flash-latest` model code to use `gemini-1.5-flash-002`. Released `gemini-1.5-flash-8b-exp-0924` to replace `gemini-1.5-flash-8b-exp-0827`. Released the [civic integrity safety filter](/gemini-api/docs/safety-settings#safety-filters)\nfor the Gemini API and AI Studio. Released support for two new parameters for Gemini 1.5 Pro and 1.5 Flash in\nPython and NodeJS:\n[`frequencyPenalty`](/api/generate-content#FIELDS.frequency_penalty) and\n[`presencePenalty`](/api/generate-content#FIELDS.presence_penalty). September 19, 2024 **AI Studio updates:** Added thumb-up and thumb-down buttons to model responses, to enable users to\nprovide feedback on the quality of a response. **API updates:** Added support for Google Cloud credits, which can now be used towards\nGemini API usage. September 17, 2024 **AI Studio updates:** Added an **Open in Colab** button that exports a prompt – and the\ncode to run it – to a Colab notebook. The feature doesn't yet support\nprompting with tools (JSON mode, function calling, or code execution). September 13, 2024 **AI Studio updates:** Added support for compare mode, which lets you compare responses across\n models and prompts to find the best fit for your use case. August 30, 2024 **Model updates:** Gemini 1.5 Flash supports\n[supplying JSON schema through model configuration](/gemini-api/docs/json-mode#supply-schema-in-config). August 27, 2024 **Model updates:** Released the following\n[experimental models](/gemini-api/docs/models/experimental-models):\n `gemini-1.5-pro-exp-0827` `gemini-1.5-flash-exp-0827` `gemini-1.5-flash-8b-exp-0827` August 9, 2024 **API updates:** Added support for [PDF processing](/gemini-api/docs/document-processing). August 5, 2024 **Model updates:** Fine-tuning support released for Gemini 1.5 Flash. August 1, 2024 **Model updates:** Released `gemini-1.5-pro-exp-0801`, a new experimental version of\n[Gemini 1.5 Pro](/gemini-api/docs/models/gemini#gemini-1.5-pro). July 12, 2024 **Model updates:** Support for Gemini 1.0 Pro Vision removed from Google AI services and tools. June 27, 2024 **Model updates:** General availability release for Gemini 1.5 Pro's 2M context window. **API updates:** Added support for [code execution](/gemini-api/docs/code-execution). June 18, 2024 **API updates:** Added support for [context caching](/gemini-api/docs/caching). June 12, 2024 **Model updates:** Gemini 1.0 Pro Vision deprecated. May 23, 2024 **Model updates:** [Gemini 1.5 Pro](/gemini-api/docs/models/gemini#gemini-1.5-pro)\n(`gemini-1.5-pro-001`) is generally available (GA). [Gemini 1.5 Flash](/gemini-api/docs/models/gemini#gemini-1.5-flash)\n(`gemini-1.5-flash-001`) is generally available (GA). May 14, 2024 **API updates:** Introduced a 2M context window for Gemini 1.5 Pro (waitlist). Introduced pay-as-you-go [billing](/gemini-api/docs/billing) for Gemini 1.0\nPro, with Gemini 1.5 Pro and Gemini 1.5 Flash billing coming soon. Introduced increased rate limits for the upcoming paid tier of Gemini 1.5\nPro. Added built-in video support to the [File API](/api/rest/v1beta/files). Added plain text support to the [File API](/api/rest/v1beta/files). Added support for parallel function calling, which returns more than one\ncall at a time. May 10, 2024 **Model updates:** Released [Gemini 1.5 Flash](/gemini-api/docs/models/gemini#gemini-1.5-flash)\n(`gemini-1.5-flash-latest`) in preview. April 9, 2024 **Model updates:** Released [Gemini 1.5 Pro](/gemini-api/docs/models/gemini#gemini-1.5-pro)\n(`gemini-1.5-pro-latest`) in preview. Released a new text embedding model, `text-embeddings-004`, which supports\n[elastic embedding](/gemini-api/docs/embeddings#elastic-embedding)\nsizes under 768. **API updates:** Released the [File API](/api/rest/v1beta/files) for temporarily storing\nmedia files for use in prompting. Added support for prompting with text, image, and audio data, also\nknown as *multimodal* prompting. To learn more, see\n[Prompting with media](/gemini-api/docs/prompting_with_media). Released [System instructions](/gemini-api/docs/system-instructions) in\nbeta. Added\n[Function calling mode](/gemini-api/docs/function-calling#function_calling_mode),\nwhich defines the execution behavior for function calling. Added support for the `response_mime_type` configuration option, which lets\nyou request responses in\n[JSON format](/gemini-api/docs/api-overview#json). March 19, 2024 **Model updates:** Added support for\n[tuning Gemini 1.0 Pro](https://developers.googleblog.com/en/tune-gemini-pro-in-google-ai-studio-or-with-the-gemini-api/)\nin Google AI Studio or with the Gemini API. December 13 2023 **Model updates:** gemini-pro: New text model for a wide variety of tasks. Balances capability\nand efficiency. gemini-pro-vision: New multimodal model for a wide variety of tasks.\nBalances capability and efficiency. embedding-001: New embeddings model. aqa: A new specially tuned model that is trained to answer questions\n using text passages for grounding generated answers. See [Gemini models](/gemini-api/docs/models/gemini) for more details. **API version updates:** v1: The stable API channel. v1beta: Beta channel. This channel has features that may be under\ndevelopment. See [the API versions topic](/gemini-api/docs/api-versions) for more details. **API updates:** `GenerateContent` is a single unified endpoint for chat and text. Streaming available through the `StreamGenerateContent` method. Multimodal capability: Image is a new supported modality New beta features:\n [Function Calling](/gemini-api/docs/function-calling) Attributed Question Answering (AQA) Updated candidate count: Gemini models only return 1 candidate. Different Safety Settings and SafetyRating categories. See\n[safety settings](/gemini-api/docs/safety-settings) for more details. Tuning models is not yet supported for Gemini models (Work in progress). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 47473, "slov": 6814, "odkazu": 227, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:47", "sha256": "5ba3ba8eeaab8288c68f12864a590988196fd31a37803159daeec46e48d31e6a", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/logs", "https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/veo/3-1-generate", "https://deepmind.google/blog/gemini-robotics-er-1-6", "https://aistudio.google.com/", "https://googleapis.github.io/js-genai", "https://github.com/googleapis/java-genai", "https://googleapis.github.io/python-genai/", "https://developers.googleblog.com/en/tune-gemini-pro-in-google-ai-studio-or-with-the-gemini-api/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/code-execution", "titulek": "Code execution | Gemini API | Google AI for Developers", "h1": "Code execution", "popis": "Learn how to use the Gemini API code execution feature.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/code-execution", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Code execution  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to use the Gemini API code execution feature.", "og:url": "https://ai.google.dev/gemini-api/docs/code-execution", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Code execution"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Code execution", "item": "https://ai.google.dev/gemini-api/docs/code-execution"}]}], "drobecky": ["Gemini API", "Code execution"], "osnova": [{"uroven": 1, "text": "Code execution"}, {"uroven": 2, "text": "Enable code execution"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Code Execution with images (Gemini 3)"}, {"uroven": 2, "text": "Enable Code Execution with images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Use code execution in multi-turn interactions"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Input/output (I/O)"}, {"uroven": 3, "text": "I/O pricing"}, {"uroven": 3, "text": "I/O details"}, {"uroven": 2, "text": "Billing"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "Supported tools combinations"}, {"uroven": 2, "text": "Supported libraries"}, {"uroven": 2, "text": "What's next"}], "markdown": "Code execution The Gemini API provides a code execution tool that enables the model to\ngenerate and run Python code. The model can then learn iteratively from the\ncode execution results until it arrives at a final output. You can use code\nexecution to build applications that benefit from code-based reasoning. For\nexample, you can use code execution to solve equations or process text. You can\nalso use the libraries included in the code execution\nenvironment to perform more specialized tasks. Gemini is only able to execute code in Python. You can still ask Gemini to\ngenerate code in another language, but the model can't use the code execution\ntool to run it. Enable code execution To enable code execution, configure the code execution tool on the model. This\nallows the model to generate and run code. Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What is the sum of the first 50 prime numbers? \" \"Generate and run code for the calculation, and make sure you get all 50.\", tools=[{\"type\": \"code_execution\"}] ) for step in interaction.steps: if step.type == \"model_output\": for content_block in step.content: if content_block.type == \"text\": print(content_block.text) elif step.type == \"code_execution_call\": print(step.arguments.code) elif step.type == \"code_execution_result\": print(step.result)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: \"What is the sum of the first 50 prime numbers? \" + \"Generate and run code for the calculation, and make sure you get all 50.\", tools: [{ type: \"code_execution\" }] }); for (const step of interaction.steps) { if (step.type === \"model_output\") { for (const contentBlock of step.content) { if (contentBlock.type === \"text\") { console.log(contentBlock.text); } } } else if (step.type === \"code_execution_call\") { console.log(step.arguments.code); } else if (step.type === \"code_execution_result\") { console.log(step.result); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CodeExecution; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Calculate the 100th Fibonacci number using Python.\")) .tools(Arrays.asList(new CodeExecution())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.\", \"tools\": [{\"type\": \"code_execution\"}] }'` The output might look something like the following, which has been formatted for\nreadability: `Okay, I need to calculate the sum of the first 50 prime numbers. Here's how I'll\napproach this:\n\n1. **Generate Prime Numbers:** I'll use an iterative method to find prime\n numbers. I'll start with 2 and check if each subsequent number is divisible\n by any number between 2 and its square root. If not, it's a prime.\n2. **Store Primes:** I'll store the prime numbers in a list until I have 50 of\n them.\n3. **Calculate the Sum:** Finally, I'll sum the prime numbers in the list.\n\nHere's the Python code to do this:\n\ndef is_prime(n):\n \"\"\"Efficiently checks if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n\nprimes = []\nnum = 2\nwhile len(primes) < 50:\n if is_prime(num):\n primes.append(num)\n num += 1\n\nsum_of_primes = sum(primes)\nprint(f'{primes=}')\nprint(f'{sum_of_primes=}')\n\nprimes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,\n71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229]\nsum_of_primes=5117\n\nThe sum of the first 50 prime numbers is 5117.` This output combines several content parts that the model returns when using\ncode execution: `text`: Inline text generated by the model `code_execution_call`: Code generated by the model that is meant to be executed `code_execution_result`: Result of the executable code Code Execution with images (Gemini 3) The Gemini 3 Flash model can now write and execute Python code to actively\nmanipulate and inspect images. **Use cases** **Zoom and inspect**: The model implicitly detects when details are too small\n(e.g., reading a distant gauge) and writes code to crop and re-examine the area\nat higher resolution. **Visual math**: The model can run multi-step calculations using code (e.g.,\nsumming line items on a receipt). **Image annotation**: The model can annotate images to answer questions, such\nas drawing arrows to show relationships. Enable Code Execution with images Code Execution with images is officially supported in Gemini 3 Flash. You can\nactivate this behavior by enabling both Code Execution as a tool and Thinking. Python`from google import genai import requests import base64 from PIL import Image import io image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"image\", \"data\": base64.b64encode(image_bytes).decode('utf-8'), \"mime_type\": \"image/jpeg\"}, {\"type\": \"text\", \"text\": \"Zoom into the expression pedals and tell me how many pedals are there?\"} ], tools=[{\"type\": \"code_execution\"}] ) for step in interaction.steps: if step.type == \"model_output\": for content_block in step.content: if content_block.type == \"text\": print(content_block.text) elif content_block.type == \"image\": img = Image.open(io.BytesIO(base64.b64decode(content_block.data))) img.show() # or: img.save(\"output_image.jpg\") elif step.type == \"code_execution_call\": print(step.arguments.code) elif step.type == \"code_execution_result\": print(step.result)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; async function main() { const client = new GoogleGenAI({}); 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 interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"image\", data: base64ImageData, mime_type: \"image/jpeg\" }, { type: \"text\", text: \"Zoom into the expression pedals and tell me how many pedals are there?\" } ], tools: [{ type: \"code_execution\" }] }); for (const step of interaction.steps) { if (step.type === \"model_output\") { for (const contentBlock of step.content) { if (contentBlock.type === \"text\") { console.log(\"Text:\", contentBlock.text); } } } else if (step.type === \"code_execution_call\") { console.log(`\\nGenerated Code:\\n`, step.arguments.code); } else if (step.type === \"code_execution_result\") { console.log(`\\nExecution Output:\\n`, step.result); } } } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CodeExecution; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Calculate the 100th Fibonacci number using Python.\")) .tools(Arrays.asList(new CodeExecution())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`IMG_URL=\"https://goo.gle/instrument-img\" MODEL=\"gemini-3.8-flash\" MIME_TYPE=$(curl -sIL \"$IMG_URL\" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\\r$//' | head -n 1) if [[ -z \"$MIME_TYPE\" || ! \"$MIME_TYPE\" == image/* ]]; then MIME_TYPE=\"image/jpeg\" fi if [[ \"$(uname)\" == \"Darwin\" ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -b 0) elif [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64) else IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -w0) fi # Use jq to create the JSON payload to avoid \"Argument list too long\" error with large base64 strings echo -n \"$IMAGE_B64\" > image_b64.txt\njq -n \\ --rawfile b64 image_b64.txt \\ --arg mime \"$MIME_TYPE\" \\ '{ model: \"gemini-3.8-flash\", input: [ {type: \"image\", data: $b64, mime_type: $mime}, {type: \"text\", text: \"Zoom into the expression pedals and tell me how many pedals are there?\"} ], tools: [{type: \"code_execution\"}] }' > payload.json\n\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d @payload.json` Use code execution in multi-turn interactions You can also use code execution as part of a multi-turn conversation using\n`previous_interaction_id`. Python`from google import genai client = genai.Client() interaction1 = client.interactions.create( model=\"gemini-3.8-flash\", input=\"I have a math question for you.\", tools=[{\"type\": \"code_execution\"}] ) print(interaction1.output_text) interaction2 = client.interactions.create( model=\"gemini-3.8-flash\", previous_interaction_id=interaction1.id, input=\"What is the sum of the first 50 prime numbers? \" \"Generate and run code for the calculation, and make sure you get all 50.\", tools=[{\"type\": \"code_execution\"}] ) for step in interaction2.steps: if step.type == \"model_output\": for content_block in step.content: if content_block.type == \"text\": print(content_block.text) elif step.type == \"code_execution_call\": print(step.arguments.code) elif step.type == \"code_execution_result\": print(step.result)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction1 = await client.interactions.create({ model: \"gemini-3.8-flash\", input: \"I have a math question for you.\", tools: [{ type: \"code_execution\" }] }); console.log(interaction1.output_text); const interaction2 = await client.interactions.create({ model: \"gemini-3.8-flash\", previous_interaction_id: interaction1.id, input: \"What is the sum of the first 50 prime numbers? \" + \"Generate and run code for the calculation, and make sure you get all 50.\", tools: [{ type: \"code_execution\" }] }); for (const step of interaction2.steps) { if (step.type === \"model_output\") { for (const contentBlock of step.content) { if (contentBlock.type === \"text\") { console.log(contentBlock.text); } } } else if (step.type === \"code_execution_call\") { console.log(step.arguments.code); } else if (step.type === \"code_execution_result\") { console.log(step.result); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CodeExecution; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Calculate the 100th Fibonacci number using Python.\")) .tools(Arrays.asList(new CodeExecution())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# First turn RESPONSE1=$(curl -s -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"I have a math question for you.\", \"tools\": [{\"type\": \"code_execution\"}] }') INTERACTION_ID=$(echo $RESPONSE1 | jq -r '.id') # Second turn with previous_interaction_id\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"previous_interaction_id\": \"'\"$INTERACTION_ID\"'\", \"input\": \"What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.\", \"tools\": [{\"type\": \"code_execution\"}] }'` Input/output (I/O) In current Gemini models such as\n[Gemini 3.5 Flash](/gemini-api/docs/models/gemini#gemini-3.5-flash), code\nexecution supports file input and graph output. Using these input and output\ncapabilities, you can upload CSV and text files, ask questions about the\nfiles, and have [Matplotlib](https://matplotlib.org/) graphs generated as part\nof the response. The output files are returned as inline images in the response. I/O pricing When using code execution I/O, you're charged for input tokens and output\ntokens: **Input tokens:** User prompt **Output tokens:** Code generated by the model Code execution output in the code environment Thinking tokens Summary generated by the model I/O details When you're working with code execution I/O, be aware of the following technical\ndetails: The maximum runtime of the code environment is 30 seconds. If the code environment generates an error, the model may decide to\nregenerate the code output. This can happen up to 5 times. The maximum file input size is limited by the model token window. If you upload a file that exceeds the model's maximum context window, the API will return an error. Code execution works best with text and CSV files. The input file can be passed as inline data or uploaded using the\n[Files API](/gemini-api/docs/files),\nand the output file is always returned as inline data. Billing There's no additional charge for enabling code execution from the Gemini API.\nYou'll be billed at the current rate of input and output tokens based on the\nGemini model you're using. Here are a few other things to know about billing for code execution: You're only billed once for the input tokens you pass to the model, and you're\nbilled for the final output tokens returned to you by the model. Tokens representing generated code are counted as output tokens. Generated\ncode can include text and multimodal output like images. Code execution results are also counted as output tokens. The billing model is shown in the following diagram: You're billed at the current rate of input and output tokens based on the\nGemini model you're using. If Gemini uses code execution when generating your response, the original\nprompt, the generated code, and the result of the executed code are labeled\n*intermediate tokens* and are billed as *input tokens*. Gemini then generates a summary and returns the generated code, the result of\nthe executed code, and the final summary. These are billed as *output tokens*. The Gemini API includes an intermediate token count in the API response, so\nyou know why you're getting additional input tokens beyond your initial\nprompt. Limitations The model can only generate and execute code. It can't return other artifacts\nlike media files. In some cases, enabling code execution can lead to regressions in other areas\nof model output (for example, writing a story). There is some variation in the ability of the different models to use code\nexecution successfully. Supported tools combinations Code execution tool can be combined with\n[Grounding with Google Search](/gemini-api/docs/google-search) to\npower more complex use cases. Gemini 3 models support combining built-in tools (like Code Execution) with\ncustom tools (function calling). Supported libraries The code execution environment includes the following libraries: attrs chess contourpy fpdf geopandas imageio jinja2 joblib jsonschema jsonschema-specifications lxml matplotlib mpmath numpy opencv-python openpyxl packaging pandas pillow protobuf pylatex pyparsing PyPDF2 python-dateutil python-docx python-pptx reportlab scikit-learn scipy seaborn six striprtf sympy tabulate tensorflow toolz xlrd You can't install your own libraries. What's next Try the [Interactions API Quickstart](/gemini-api/docs/quickstart). Learn about other Gemini API tools:\n [Function calling](/gemini-api/docs/function-calling) [Grounding with Google Search](/gemini-api/docs/google-search) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 17679, "slov": 2288, "odkazu": 131, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:57", "sha256": "5c0d192a2c497792420f3d8891a5f62813b520c7329188106d3d55e485512227", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://matplotlib.org/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/coding-agents", "titulek": "Set up your coding assistant with Gemini MCP and Skills | Gemini API | Google AI for Developers", "h1": "Set up your coding assistant with Gemini MCP and Skills", "popis": "Install Gemini API skills to give your AI coding assistant access to the latest documentation and best practices.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/coding-agents", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Set up your coding assistant with Gemini MCP and Skills  |  Gemini API  |  Google AI for Developers", "og:description": "Install Gemini API skills to give your AI coding assistant access to the latest documentation and best practices.", "og:url": "https://ai.google.dev/gemini-api/docs/coding-agents", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Set up your coding assistant with Gemini MCP and Skills"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Set up your coding assistant with Gemini MCP and Skills", "item": "https://ai.google.dev/gemini-api/docs/coding-agents"}]}], "drobecky": ["Gemini API", "Set up your coding assistant with Gemini MCP and Skills"], "osnova": [{"uroven": 1, "text": "Set up your coding assistant with Gemini MCP and Skills"}, {"uroven": 2, "text": "Connect the Gemini Docs MCP"}, {"uroven": 2, "text": "Add API Development Skills"}, {"uroven": 3, "text": "gemini-api-dev"}, {"uroven": 4, "text": "Install with skills.sh"}, {"uroven": 4, "text": "Install with Context7"}, {"uroven": 3, "text": "gemini-live-api-dev"}, {"uroven": 4, "text": "Install with skills.sh"}, {"uroven": 4, "text": "Install with Context7"}, {"uroven": 2, "text": "Verify installation"}, {"uroven": 3, "text": "1. Verify agent behavior"}, {"uroven": 3, "text": "2. Verify manifestations & tools"}, {"uroven": 2, "text": "Troubleshooting"}, {"uroven": 3, "text": "Agent didn't discover the skill"}, {"uroven": 3, "text": "Global vs. local conflict"}, {"uroven": 2, "text": "Resources"}], "markdown": "Set up your coding assistant with Gemini MCP and Skills AI coding assistants are powerful but have limitations—training data cuts off\nat a specific date, missing new API features and changes. Without access to\nGemini-specific documentation, agents may suggest generic patterns instead of\noptimized approaches. To keep your coding assistant current with the evolving Gemini API and its\nrecommended usage, we recommend setting up the **Gemini Docs MCP**\nand enhancing your environment with **Gemini API Skills**. While these tools are usable independently, they are designed to work\ntogether to provide complete coverage. Connect the Gemini Docs MCP Gemini hosts a public Model Context Protocol (MCP) server at\n`https://gemini-api-docs-mcp.dev`. Connecting your coding agent to this server ensures that\nall queries have access to the latest APIs, code updates, and optimal configuration examples. Run the following command in your agent's terminal or project root to install\nthe server: `npx add-mcp \"https://gemini-api-docs-mcp.dev\"` This server adds a `search_documentation` function that your agent can use to\nretrieve real-time API definitions and integration patterns from the official\nGemini documentation files. Add API Development Skills The skills provide **baked-in rules and best practices** (such as enforcing the correct SDK and current model versions) directly in your assistant's context. The skill works together with the Gemini Docs MCP service: If you have both\ninstalled, the skill uses the MCP service for documentation, but even without\nthe MCP installed, it will fetch `llms.txt` from `ai.google.dev` as a fallback. To install these skills, you can use one of the following supported tools. Installation instructions for both are provided below each skill module: **[skills.sh](https://skills.sh)**: Recommended. The open standard for portable agent behaviors. **[Context7](https://context7.com)**: Supported for users already utilizing the Context7 ecosystem. gemini-api-dev Skill for building apps with the\n[Gemini API](/gemini-api/docs/interactions-overview) (Interactions API). The\nInteractions API is our simplest and best way to build with Gemini models and\nagents. This skill covers: Text generation, multi-turn chat, and streaming Function calling, structured output, and image generation Background execution and Deep Research agents Server-side conversation state management Prompt routing to current models and avoiding deprecated models Python and TypeScript SDK patterns Install with skills.sh `npx skills add google-gemini/gemini-skills --skill gemini-api-dev --global` Install with Context7 `npx ctx7 skills install /google-gemini/gemini-skills gemini-api-dev` gemini-live-api-dev Skill for building real-time conversational AI applications with Gemini Live\nAPI. This skill provides documentation and best practices for: WebSocket connections for low-latency streaming Streaming audio, video, and text Voice activity detection and barge-in support Install with skills.sh `npx skills add google-gemini/gemini-skills --skill gemini-live-api-dev --global` Install with Context7 `npx ctx7 skills install /google-gemini/gemini-skills gemini-live-api-dev` Verify installation After installing, confirm that your coding assistant can connect to the Gemini Docs MCP server and use your installed skills. 1. Verify agent behavior The most reliable way to verify is to ask your agent a technical question about Gemini API. **Prompt:** \"How do I use context caching with the Gemini API?\" A successful setup will: **Provide accurate code**: Reference specific Gemini methods like `cacheContent` or `cachedContents.create` from the latest endpoints. **Use the MCP Tool**: Show that it is connected to the **Gemini Docs MCP Server** or utilizing the `search_documentation` tool to fetch data. **Invoke loaded skills**: Show an indicator that it is \"Using skill: gemini-api-dev\" (if relying on a secondary wrapper). 2. Verify manifestations & tools If the agent gives a general or generic answer, use the specific Discovery or Status commands for your environment to verify that the Docs MCP or skill is loaded into memory. Environment MCP Verification Skills Verification **Claude Code** Type `/mcp` in the terminal to view active servers and `search_documentation` tools. Type `/skills` in the terminal to list all active manifests. **Cursor** Navigate to **Settings > Features > MCP**. Ensure server is \"Connected\". Open **Settings > Rules**. Verify the skill appears under \"Agent Decides.\" **Antigravity** Check the **Customizations > Connections** sidebar for MCP status. Type `/skills list` or check the **Customizations > Rules** sidebar. **Gemini CLI** Run `gemini mcp list` or use `/mcp list`. Run `gemini skills list` or use the `/skills` slash command in-session. **Copilot** Type `@gemini /mcp` to list active data connectors. Type `@gemini /skills` (or `/skills`) to view active extensions. Troubleshooting If your agent provides only general information or fails to recognize\nGemini-specific methods, check the following: Agent didn't discover the skill Most agents index skills only on startup. **Fix:** Completely restart your IDE (Cursor/VS Code) or exit and re-open your\nterminal-based agent (Claude Code). Global vs. local conflict If you installed with the `--global` flag, your agent might be ignoring it in\nfavor of project-specific rules. **Fix:** Try installing the skill directly into your project root without the\nglobal flag: `npx skills add google-gemini/gemini-skills --skill gemini-api-dev` Resources [Gemini API skills on GitHub](https://github.com/google-gemini/gemini-skills) [Interactions API](/gemini-api/docs/interactions-overview) [Get started](/gemini-api/docs/get-started) [Libraries](/gemini-api/docs/libraries) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-01 UTC.", "znaku_textu": 6095, "slov": 898, "odkazu": 130, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:33", "sha256": "7c419d4702a3cab171f83990dbd670219aa701600b45b8155b55e979f7943d13", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://skills.sh/", "https://context7.com/", "https://github.com/google-gemini/gemini-skills", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/computer-use", "titulek": "Computer use | Gemini API | Google AI for Developers", "h1": "Computer use", "popis": "Learn how to use the Gemini API computer use feature.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/computer-use", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Computer use  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to use the Gemini API computer use feature.", "og:url": "https://ai.google.dev/gemini-api/docs/computer-use", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Computer use"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Computer use", "item": "https://ai.google.dev/gemini-api/docs/computer-use"}]}], "drobecky": ["Gemini API", "Computer use"], "osnova": [{"uroven": 1, "text": "Computer use"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "How Computer Use works"}, {"uroven": 2, "text": "How to implement Computer Use"}, {"uroven": 3, "text": "0. Set up Playwright"}, {"uroven": 3, "text": "1. Send a request to the model"}, {"uroven": 3, "text": "Gemini 3.x"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Gemini 2.5 (Legacy)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "2. Receive the model response"}, {"uroven": 3, "text": "Gemini 3.x"}, {"uroven": 3, "text": "Gemini 2.5 (Legacy)"}, {"uroven": 3, "text": "3. Execute the received actions"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "4. Capture the new environment state"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Build an agent loop"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Supported environments (Gemini 3.x)"}, {"uroven": 3, "text": "Browser environment (ENVIRONMENT_BROWSER)"}, {"uroven": 3, "text": "Mobile environment (ENVIRONMENT_MOBILE)"}, {"uroven": 3, "text": "Desktop environment (ENVIRONMENT_DESKTOP)"}, {"uroven": 2, "text": "Legacy Supported UI actions (Gemini 2.5)"}, {"uroven": 2, "text": "Custom user-defined functions"}, {"uroven": 4, "text": "Gemini 3.x Custom Tooling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 4, "text": "Gemini 2.5 (Legacy) Custom Tooling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Managing thinking levels (Gemini 3.x)"}, {"uroven": 2, "text": "Safety and security"}, {"uroven": 3, "text": "Configuring safety policies (Gemini 3.x)"}, {"uroven": 4, "text": "Safety overrides"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Prompt injection detection (Gemini 3.x)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "cURL"}, {"uroven": 3, "text": "Acknowledge safety decision"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Safety best practices"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Model versions"}, {"uroven": 2, "text": "What's next"}], "markdown": "Computer use The Computer Use tool lets you build browser, mobile, and desktop control agents\nthat interact with and automate tasks. Using screenshots, the model can \"see\" a\ncomputer screen, and \"act\" by generating specific UI actions like mouse clicks\nand keyboard inputs. Similar to function calling, you will need to implement the\nclient-side execution environment to receive and execute the Computer Use\nactions. For the list of supported models, see Model versions. The Gemini 3.x models support several advanced capabilities: **Multi-environment support:** build agents for browser, mobile, and desktop environments. **Streamlined actions with intents:** actions include an `intent` field that explains the model's reasoning behind each step. **Configurable safety policies:** fine-tune safety behavior with built-in policy categories and overrides. **Prompt injection detection:** opt-in screenshot scanning to detect hidden adversarial instructions. With Computer Use, you can build agents that: Automate repetitive data entry or form filling on websites. Perform automated testing of web applications and user flows Conduct research across various websites (e.g., gathering product\ninformation, prices, and reviews from ecommerce sites to inform a purchase) Here's a minimal example of initializing the client and sending a prompt to the model with the `computer_use` tool enabled for a browser environment: Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Search for 'Gemini API' on Google.\", tools=[{\"type\": \"computer_use\", \"environment\": \"browser\"}] ) print(interaction)` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const interaction = await ai.interactions.create({ model: 'gemini-3.8-flash', input: \"Search for 'Gemini API' on Google.\", tools: [{ type: \"computer_use\", environment: \"browser\" }] }); console.log(interaction);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` \n How Computer Use works To build an agent with the Computer Use model, you need to set up a\ncontinuous loop between your application and the API. Here is what your code\nwill do at each step: **Send a request to the model** Your application sends an API request containing the Computer Use tool,\nyour configuration settings (like the target environment), the user's\nprompt, and a screenshot of the current screen. **Receive the model response** The model analyzes the screen and the prompt, returning a response\nwhich includes a suggested `function_call` representing a UI action (such\nas a click, scroll, or keystroke). For **Gemini 3.x models**, the response also includes a reasoning `intent`\nexplaining why the model chose that action. The response may also include a `safety_decision` from an internal safety\nsystem that classifies the action as regular/allowed,\n`require_confirmation` (requiring user approval), or blocked. **Execute the received action** If the action is allowed (or the user confirms it), your client-side\ncode parses the `function_call`, scales the normalized coordinates to match\nyour viewport, and executes the action in your target environment using\nautomation tools (such as Playwright). If the action is blocked, your\nclient should halt the execution or handle the interruption. **Capture the new environment state** After the action finishes executing, your application captures a new\nscreenshot and sends it back to the model in a `function_result` to\nrequest the next step. This process then repeats from step 2, continually soliciting the next action\nfrom the model until the task is completed or terminated. How to implement Computer Use Before building with the Computer Use tool you will need to set up: **Secure execution environment:** Run your agent in a sandboxed VM or\ncontainer to isolate it from your host system and limit its potential impact.\nThe [reference implementation](https://github.com/google/computer-use-preview/)\nincludes a ready-to-use Docker-based sandbox you can use as a starting point. **Client-side action handler:** Implement client-side logic to execute coordinates, type text, and take screenshots. The examples below use a web browser as the execution environment and\n[Playwright](https://playwright.dev/) as the client-side handler. 0. Set up Playwright First, install the required packages: `pip install google-genai playwright\nplaywright install chromium` Then, initialize a Playwright browser instance to use for execution: `from playwright.sync_api import sync_playwright # 1. Configure screen dimensions for the target environment SCREEN_WIDTH = 1440 SCREEN_HEIGHT = 900 # 2. Start the Playwright browser # In production, utilize a sandboxed environment. playwright = sync_playwright().start() # Set headless=False to see the actions performed on your screen browser = playwright.chromium.launch(headless=False) # 3. Create a context and page with the specified dimensions context = browser.new_context( viewport={\"width\": SCREEN_WIDTH, \"height\": SCREEN_HEIGHT} ) page = context.new_page() # 4. Navigate to an initial page to start the task page.goto(\"https://www.google.com\") # The 'page', 'SCREEN_WIDTH', and 'SCREEN_HEIGHT' variables # will be used in the steps below.` 1. Send a request to the model Initialize the client library and configure the Computer Use tool. Note that there is no need to specify the display size when issuing a request; the model predicts pixel coordinates scaled to the height and width of the screen. Gemini 3.x PythonUse the `google-genai` Python SDK (version `2.7.0` or higher) to configure a request targeting the browser environment: `from google import genai client = genai.Client() interaction = client.interactions.create( model='gemini-3.8-flash', input=\"Find a flight from SF to Hawaii on Jun 30th, coming back on Jul 6th\", tools=[ { \"type\": \"computer_use\", \"environment\": \"browser\", \"enable_prompt_injection_detection\": True } ] ) print(interaction)` JavaScriptUse the `@google/genai` Node.js SDK to configure a request targeting the browser environment: `import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const interaction = await ai.interactions.create({ model: 'gemini-3.8-flash', input: \"Find a flight from SF to Hawaii on Jun 30th, coming back on Jul 6th\", tools: [ { type: \"computer_use\", environment: \"browser\", enable_prompt_injection_detection: true } ] }); console.log(interaction);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` RESTUse curl to send a request: `curl -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Find me a flight from SF to Hawaii on Jun 30th, coming back on Jul 6th. Start by navigating directly to flights.google.com\", \"tools\": [ { \"type\": \"computer_use\", \"environment\": \"browser\", \"enable_prompt_injection_detection\": true } ] }'` Gemini 2.5 (Legacy) Python`from google import genai client = genai.Client() # Specify predefined functions to exclude (optional) excluded_functions = [\"drag_and_drop\"] interaction = client.interactions.create( model='gemini-2.5-computer-use-preview-10-2025', input=\"Search for highly rated smart fridges on Google Shopping.\", tools=[ { \"type\": \"computer_use\", \"environment\": \"browser\", \"excluded_predefined_functions\": excluded_functions } ] ) print(interaction)` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); // Specify predefined functions to exclude (optional) const excludedFunctions = [\"drag_and_drop\"]; const interaction = await ai.interactions.create({ model: 'gemini-2.5-computer-use-preview-10-2025', input: \"Search for highly rated smart fridges on Google Shopping.\", tools: [ { type: \"computer_use\", environment: \"browser\", excluded_predefined_functions: excludedFunctions } ] }); console.log(interaction);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` 2. Receive the model response The response model suggests a function call. For **Gemini 3.x models**, the\nresponse contains a tailored reasoning intent alongside coordinates. The\nfollowing shows examples of both responses: Gemini 3.x`{ \"steps\": [ { \"type\": \"function_call\", \"name\": \"click\", \"arguments\": { \"x\": 450, \"y\": 120, \"intent\": \"Click the search box to type the destination.\" } } ] }` Gemini 2.5 (Legacy)`{ \"steps\": [ { \"type\": \"model_output\", \"content\": [ { \"type\": \"text\", \"text\": \"I will type the search query into the search bar.\" } ] }, { \"type\": \"function_call\", \"name\": \"type_text_at\", \"arguments\": { \"x\": 371, \"y\": 470, \"text\": \"highly rated smart fridges\", \"press_enter\": true } } ] }` 3. Execute the received actions Your application must parse the response coordinates, execute the action, and scale them from the normalized 1000x1000 coordinates. The code below handles both legacy tool commands (`click_at`, `type_text_at`) and modern streamlined commands (`click`, `type`). Python`from typing import Any, List, Tuple import time def denormalize_x(x: int, screen_width: int) -> int: \"\"\"Convert normalized x coordinate (0-1000) to actual pixel coordinate.\"\"\" return int(x / 1000 * screen_width) def denormalize_y(y: int, screen_height: int) -> int: \"\"\"Convert normalized y coordinate (0-1000) to actual pixel coordinate.\"\"\" return int(y / 1000 * screen_height) def execute_function_calls(interaction, page, screen_width, screen_height): results = [] function_calls = [ step for step in interaction.steps if step.type == \"function_call\" ] for function_call in function_calls: action_result = {} fname = function_call.name args = function_call.arguments print(f\" -> Executing: {fname} (Intent: {args.get('intent', 'N/A')})\") try: if fname in (\"open_web_browser\", \"open_app\"): pass # Handled / already open elif fname in (\"click\", \"click_at\", \"double_click\", \"triple_click\", \"middle_click\", \"right_click\", \"move\", \"long_press\"): actual_x = denormalize_x(args[\"x\"], screen_width) actual_y = denormalize_y(args[\"y\"], screen_height) if fname in (\"click\", \"click_at\"): page.mouse.click(actual_x, actual_y) elif fname == \"double_click\": page.mouse.dblclick(actual_x, actual_y) elif fname == \"right_click\": page.mouse.click(actual_x, actual_y, button=\"right\") elif fname == \"middle_click\": page.mouse.click(actual_x, actual_y, button=\"middle\") elif fname == \"move\": page.mouse.move(actual_x, actual_y) elif fname in (\"type\", \"type_text_at\"): actual_x = denormalize_x(args[\"x\"], screen_width) if \"x\" in args else None actual_y = denormalize_y(args[\"y\"], screen_height) if \"y\" in args else None text = args[\"text\"] press_enter = args.get(\"press_enter\", False) if actual_x is not None and actual_y is not None: page.mouse.click(actual_x, actual_y) # Clear field first page.keyboard.press(\"Meta+A\") page.keyboard.press(\"Backspace\") page.keyboard.type(text) if press_enter: page.keyboard.press(\"Enter\") elif fname == \"navigate\": page.goto(args[\"url\"]) elif fname == \"go_back\": page.go_back() elif fname == \"go_forward\": page.go_forward() elif fname == \"wait\": time.sleep(args.get(\"seconds\", 1)) else: print(f\"Warning: Custom or unhandled function {fname}\") page.wait_for_load_state(timeout=5000) time.sleep(1) except Exception as e: print(f\"Error executing {fname}: {e}\") action_result = {\"error\": str(e)} results.append((fname, function_call.id, action_result)) return results` JavaScript`function denormalizeX(x, screenWidth) { // Convert normalized x coordinate (0-1000) to actual pixel coordinate. return Math.floor((x / 1000) * screenWidth); } function denormalizeY(y, screenHeight) { // Convert normalized y coordinate (0-1000) to actual pixel coordinate. return Math.floor((y / 1000) * screenHeight); } async function executeFunctionCalls(interaction, page, screenWidth, screenHeight) { const results = []; const functionCalls = interaction.steps.filter(step => step.type === \"function_call\"); for (const functionCall of functionCalls) { const actionResult = {}; const fname = functionCall.name; const args = functionCall.arguments; console.log(` -> Executing: ${fname} (Intent: ${args.intent || 'N/A'})`); try { if (fname === \"open_web_browser\" || fname === \"open_app\") { // Handled / already open } else if ([\"click\", \"click_at\", \"double_click\", \"triple_click\", \"middle_click\", \"right_click\", \"move\", \"long_press\"].includes(fname)) { const actualX = denormalizeX(args.x, screenWidth); const actualY = denormalizeY(args.y, screenHeight); if (fname === \"click\" || fname === \"click_at\") { await page.mouse.click(actualX, actualY); } else if (fname === \"double_click\") { await page.mouse.dblclick(actualX, actualY); } else if (fname === \"right_click\") { await page.mouse.click(actualX, actualY, { button: \"right\" }); } else if (fname === \"middle_click\") { await page.mouse.click(actualX, actualY, { button: \"middle\" }); } else if (fname === \"move\") { await page.mouse.move(actualX, actualY); } } else if (fname === \"type\" || fname === \"type_text_at\") { const actualX = args.x !== undefined ? denormalizeX(args.x, screenWidth) : null; const actualY = args.y !== undefined ? denormalizeY(args.y, screenHeight) : null; const text = args.text; const pressEnter = args.press_enter || false; if (actualX !== null && actualY !== null) { await page.mouse.click(actualX, actualY); } // Clear field first await page.keyboard.press(\"Meta+A\"); await page.keyboard.press(\"Backspace\"); await page.keyboard.type(text); if (pressEnter) { await page.keyboard.press(\"Enter\"); } } else if (fname === \"navigate\") { await page.goto(args.url); } else if (fname === \"go_back\") { await page.goBack(); } else if (fname === \"go_forward\") { await page.goForward(); } else if (fname === \"wait\") { await new Promise(resolve => setTimeout(resolve, (args.seconds || 1) * 1000)); } else { console.log(`Warning: Custom or unhandled function ${fname}`); } await page.waitForLoadState('load', { timeout: 5000 }).catch(() => {}); await new Promise(resolve => setTimeout(resolve, 1000)); } catch (e) { console.log(`Error executing ${fname}: ${e}`); actionResult.error = e.message; } results.push([fname, functionCall.id, actionResult]); } return results; }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` 4. Capture the new environment state After executing the actions, send the result of the function execution back to\nthe model so it can use this information to generate the next action. If\nmultiple actions (parallel calls) were executed, you must send a\n`function_result` for each one in the subsequent user turn. Python`import json import base64 def get_function_responses(page, results): screenshot_bytes = page.screenshot(type=\"png\") current_url = page.url function_responses = [] for name, call_id, result in results: function_responses.append({ \"type\": \"function_result\", \"name\": name, \"call_id\": call_id, \"result\": [ { \"type\": \"text\", \"text\": json.dumps({\"url\": current_url, **result}) }, { \"type\": \"image\", \"data\": base64.b64encode(screenshot_bytes).decode(\"utf-8\"), \"mime_type\": \"image/png\" } ] }) return function_responses` JavaScript`async function getFunctionResponses(page, results) { const screenshotBuffer = await page.screenshot({ type: 'png' }); const screenshotBase64 = screenshotBuffer.toString('base64'); const currentUrl = page.url(); const functionResponses = []; for (const [name, callId, result] of results) { functionResponses.push({ type: \"function_result\", name: name, call_id: callId, result: [ { type: \"text\", text: JSON.stringify({ url: currentUrl, ...result }) }, { type: \"image\", data: screenshotBase64, mime_type: \"image/png\" } ] }); } return functionResponses; }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Once you have defined how to capture and format the environment state, you can\ncombine all these steps into a continuous execution loop. Build an agent loop To enable multi-step interactions, combine the four steps from the How to\nimplement Computer Use section into a single loop.\nThis loop continues requesting actions and feeding the results back to the model\nuntil the task is complete. Remember to manage the conversation history correctly by appending both the\nmodel responses and your function responses to the history at each step. Python`import time from typing import Any, List, Tuple from playwright.sync_api import sync_playwright from google import genai client = genai.Client() # Constants for screen dimensions SCREEN_WIDTH = 1440 SCREEN_HEIGHT = 900 # Setup Playwright print(\"Initializing browser...\") playwright = sync_playwright().start() browser = playwright.chromium.launch(headless=False) context = browser.new_context(viewport={\"width\": SCREEN_WIDTH, \"height\": SCREEN_HEIGHT}) page = context.new_page() # Define helper functions. Copy/paste from steps 3 and 4 # def denormalize_x(...) # def denormalize_y(...) # def execute_function_calls(...) # def get_function_responses(...) try: # Go to initial page page.goto(\"https://ai.google.dev/gemini-api/docs\") # Take initial screenshot initial_screenshot = page.screenshot(type=\"png\") USER_PROMPT = \"Go to ai.google.dev/gemini-api/docs and search for pricing.\" print(f\"Goal: {USER_PROMPT}\") # First interaction interaction = client.interactions.create( model='gemini-3.8-flash', input=[ {\"type\": \"text\", \"text\": USER_PROMPT}, {\"type\": \"image\", \"data\": base64.b64encode(initial_screenshot).decode(\"utf-8\"), \"mime_type\": \"image/png\"} ], tools=[{ \"type\": \"computer_use\", \"environment\": \"browser\", \"enable_prompt_injection_detection\": True }] ) # Agent Loop turn_limit = 5 for i in range(turn_limit): print(f\"\\n--- Turn {i+1} ---\") has_function_calls = any( step.type == \"function_call\" for step in interaction.steps ) if not has_function_calls: text_response = \" \".join([ content_block.text for step in interaction.steps if step.type == \"model_output\" for content_block in step.content if content_block.type == \"text\" ]) print(\"Agent finished:\", text_response) break print(\"Executing actions...\") results = execute_function_calls(interaction, page, SCREEN_WIDTH, SCREEN_HEIGHT) print(\"Capturing state...\") function_responses = get_function_responses(page, results) # Continue conversation with function responses interaction = client.interactions.create( model='gemini-3.8-flash', previous_interaction_id=interaction.id, input=function_responses, tools=[{ \"type\": \"computer_use\", \"environment\": \"browser\", \"enable_prompt_injection_detection\": True }] ) finally: # Cleanup print(\"\\nClosing browser...\") browser.close() playwright.stop()` JavaScript`import { chromium } from 'playwright'; import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); // Constants for screen dimensions const SCREEN_WIDTH = 1440; const SCREEN_HEIGHT = 900; console.log(\"Initializing browser...\"); const browser = await chromium.launch({ headless: false }); const context = await browser.newContext({ viewport: { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } }); const page = await context.newPage(); // Define helper functions. Copy/paste from steps 3 and 4: // function denormalizeX(...) // function denormalizeY(...) // async function executeFunctionCalls(...) // async function getFunctionResponses(...) try { // Go to initial page await page.goto(\"https://ai.google.dev/gemini-api/docs\"); // Take initial screenshot const initialScreenshotBuffer = await page.screenshot({ type: 'png' }); const initialScreenshotBase64 = initialScreenshotBuffer.toString('base64'); const USER_PROMPT = \"Go to ai.google.dev/gemini-api/docs and search for pricing.\"; console.log(`Goal: ${USER_PROMPT}`); // First interaction let interaction = await ai.interactions.create({ model: 'gemini-3.8-flash', input: [ { type: 'text', text: USER_PROMPT }, { type: 'image', data: initialScreenshotBase64, mime_type: 'image/png' } ], tools: [{ type: 'computer_use', environment: 'browser', enable_prompt_injection_detection: true }] }); // Agent Loop const turnLimit = 5; for (let i = 0; i < turnLimit; i++) { console.log(`\\n--- Turn ${i + 1} ---`); const hasFunctionCalls = interaction.steps.some(step => step.type === \"function_call\"); if (!hasFunctionCalls) { const textResponses = []; for (const step of interaction.steps) { if (step.type === \"model_output\") { for (const contentBlock of step.content || []) { if (contentBlock.type === \"text\") { textResponses.push(contentBlock.text); } } } } console.log(\"Agent finished:\", textResponses.join(\" \")); break; } console.log(\"Executing actions...\"); const results = await executeFunctionCalls(interaction, page, SCREEN_WIDTH, SCREEN_HEIGHT); console.log(\"Capturing state...\"); const functionResponses = await getFunctionResponses(page, results); // Continue conversation with function responses interaction = await ai.interactions.create({ model: 'gemini-3.8-flash', previous_interaction_id: interaction.id, input: functionResponses, tools: [{ type: 'computer_use', environment: 'browser', enable_prompt_injection_detection: true }] }); } } finally { // Cleanup console.log(\"\\nClosing browser...\"); await browser.close(); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Supported environments (Gemini 3.x) Gemini 3.x models support three environments specified in the `computer_use`\nconfigurations: Browser environment (`ENVIRONMENT_BROWSER`) Available actions under browser tool: Command name Description Arguments (in function call) **click** Left clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **double_click** Double clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **triple_click** Triple clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **middle_click** Middle clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **right_click** Right clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **mouse_down** Presses and holds the mouse button at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **mouse_up** Releases the mouse button at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **move** Moves the cursor to the specified position. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **type** Types text. `text`: str\n`press_enter`: bool (Optional, default `false`)\n`intent`: str **drag_and_drop** Drags an item from the start coordinate to the end coordinate. `start_y`: int (0-999)\n`start_x`: int (0-999)\n`end_y`: int (0-999)\n`end_x`: int (0-999)\n`intent`: str **wait** Pauses execution for a specified number of seconds. `seconds`: int (Optional, default `1`)\n`intent`: str **press_key** Presses the specified key and releases it. `key`: str\n`intent`: str **key_down** Presses and holds the specified key. `key`: str\n`intent`: str **key_up** Releases the specified key. `key`: str\n`intent`: str **hotkey** Presses the specified key combination. `keys`: `List[str]`\n`intent`: `str` **take_screenshot** Returns a screenshot of the current screen. `intent`: str **scroll** Scrolls up, down, left, or right at a coordinate by a pixel distance. `y`: int (0-999)\n`x`: int (0-999)\n`direction`: str (`\"up\"`, `\"down\"`, `\"left\"`, `\"right\"`)\n`magnitude_in_pixels`: int (0-999, Optional, default `300`)\n`intent`: str **go_back** Navigates back to the previous webpage in the browser history. `intent`: str **navigate** Navigates directly to a specified URL. `url`: str\n`intent`: str **go_forward** Navigates forward to the next webpage in the browser history. `intent`: str Mobile environment (`ENVIRONMENT_MOBILE`) Android-optimized environment actions: Command name Description Arguments (in function call) **open_app** Opens an application by its name. `app_name`: str\n`intent`: str **click** Left clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **list_apps** Lists available applications on the device, returning their names and package names. `intent`: str **wait** Pauses execution for a specified number of seconds. `seconds`: int (Optional, default `1`)\n`intent`: str **go_back** Navigates back to the previous screen or webpage. `intent`: str **type** Types text. `text`: str\n`press_enter`: bool (Optional, default `false`)\n`intent`: str **drag_and_drop** Drags an item from the start coordinate to the end coordinate. `start_y`: int (0-999)\n`start_x`: int (0-999)\n`end_y`: int (0-999)\n`end_x`: int (0-999)\n`intent`: str **long_press** Performs a long press at a coordinate on the screen. `y`: int (0-999)\n`x`: int (0-999)\n`seconds`: int (Optional, default `2`)\n`intent`: str **press_key** Presses the specified key and releases it. `key`: str\n`intent`: str **take_screenshot** Returns a screenshot of the current screen. `intent`: str Desktop environment (`ENVIRONMENT_DESKTOP`) Desktop environments OS-level cursor commands: Command name Description Arguments (in function call) **click** Left clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **double_click** Double clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **triple_click** Triple clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **middle_click** Middle clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **right_click** Right clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **mouse_down** Presses and holds the mouse button at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **mouse_up** Releases the mouse button at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **move** Moves the cursor to the specified position. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **type** Types text. `text`: str\n`press_enter`: bool (Optional, default `false`)\n`intent`: str **drag_and_drop** Drags an item from the start coordinate to the end coordinate. `start_y`: int (0-999)\n`start_x`: int (0-999)\n`end_y`: int (0-999)\n`end_x`: int (0-999)\n`intent`: str **wait** Pauses execution for a specified number of seconds. `seconds`: int (Optional, default `1`)\n`intent`: str **press_key** Presses the specified key and releases it. `key`: str\n`intent`: str **key_down** Presses and holds the specified key. `key`: str\n`intent`: str **key_up** Releases the specified key. `key`: str\n`intent`: str **hotkey** Presses the specified key combination. `keys`: `List[str]`\n`intent`: `str` **take_screenshot** Returns a screenshot of the current screen. `intent`: str **scroll** Scrolls up, down, left, or right at a coordinate by a pixel distance. `y`: int (0-999)\n`x`: int (0-999)\n`direction`: str (`\"up\"`, `\"down\"`, `\"left\"`, `\"right\"`)\n`magnitude_in_pixels`: int (0-999, Optional, default `300`)\n`intent`: str Legacy Supported UI actions (Gemini 2.5) For legacy models (`gemini-2.5-computer-use-preview-10-2025`), the following actions are supported: Command name Description Arguments (in function call) Example function call **open_web_browser** Opens the web browser. None `{\"name\": \"open_web_browser\", \"arguments\": {}}` **wait_5_seconds** Pauses execution for 5 seconds. None `{\"name\": \"wait_5_seconds\", \"arguments\": {}}` **go_back** Navigates to the previous page in history. None `{\"name\": \"go_back\", \"arguments\": {}}` **go_forward** Navigates to the next page in history. None `{\"name\": \"go_forward\", \"arguments\": {}}` **search** Navigates to default search engine. None `{\"name\": \"search\", \"arguments\": {}}` **navigate** Navigates the browser directly to the specified URL. `url`: str `{\"name\": \"navigate\", \"arguments\": {\"url\": \"https://www.wikipedia.org\"}}` **click_at** Clicks at a specific coordinate. `y`: int (0-999), `x`: int (0-999) `{\"name\": \"click_at\", \"arguments\": {\"y\": 300, \"x\": 500}}` **hover_at** Hovers mouse at a specific coordinate. `y`: int (0-999), `x`: int (0-999) `{\"name\": \"hover_at\", \"arguments\": {\"y\": 150, \"x\": 250}}` **type_text_at** Types text at a coordinate. `y`: int (0-999), `x`: int (0-999), `text`: str, `press_enter`: bool (Optional, default True), `clear_before_typing`: bool (Optional, default True) `{\"name\": \"type_text_at\", \"arguments\": {\"y\": 250, \"x\": 400, \"text\": \"search\", \"press_enter\": false}}` **key_combination** Press keys or combinations. `keys`: str `{\"name\": \"key_combination\", \"arguments\": {\"keys\": \"Control+A\"}}` **scroll_document** Scrolls the entire webpage. `direction`: str `{\"name\": \"scroll_document\", \"arguments\": {\"direction\": \"down\"}}` **scroll_at** Scrolls at coordinate (x,y). `y`: int, `x`: int, `direction`: str, `magnitude`: int (Optional, default 800) `{\"name\": \"scroll_at\", \"arguments\": {\"y\": 500, \"x\": 500, \"direction\": \"down\"}}` **drag_and_drop** Drags between two coordinates. `y`: int, `x`: int, `destination_y`: int, `destination_x`: int `{\"name\": \"drag_and_drop\", \"arguments\": {\"y\": 100, \"destination_y\": 500, \"destination_x\": 500, \"x\": 100}}` Custom user-defined functions You can extend the functionality of the model by including custom user-defined functions. For example, in human-in-the-loop (HITL) scenarios you can exclude default predefined actions and register custom actions. Gemini 3.x Custom Tooling PythonExclude standard predefined browser actions (such as `click`) and register a custom `yield_to_user` tool: `from google import genai client = genai.Client() yield_to_user_tool = { \"type\": \"function\", \"name\": \"yield_to_user\", \"description\": \"Yields control back to the user for assistance or verification when an automated action is unsafe or ambiguous.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"reason\": { \"type\": \"string\", \"description\": \"The reason why the agent is yielding control to the human.\" } }, \"required\": [\"reason\"] } } interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Click the submit button. If you need a second factor authentication code, ask me.\", tools=[ { \"type\": \"computer_use\", \"environment\": \"mobile\", \"excluded_predefined_functions\": [\"click\"] }, yield_to_user_tool ] )` JavaScriptExclude standard predefined browser actions (such as `click`) and register a custom `yield_to_user` tool: `import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const yieldToUserTool = { type: \"function\", name: \"yield_to_user\", description: \"Yields control back to the user for assistance or verification when an automated action is unsafe or ambiguous.\", parameters: { type: \"object\", properties: { reason: { type: \"string\", description: \"The reason why the agent is yielding control to the human.\" } }, required: [\"reason\"] } }; const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Click the submit button. If you need a second factor authentication code, ask me.\", tools: [ { type: \"computer_use\", environment: \"mobile\", excluded_predefined_functions: [\"click\"] }, yieldToUserTool ] });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Gemini 2.5 (Legacy) Custom Tooling Python`from google import genai client = genai.Client() # Define custom tools here custom_functions = [...] # Describe parameters as function declarations excluded_functions = [ \"open_web_browser\", \"wait_5_seconds\", \"go_back\", \"go_forward\", \"search\", \"navigate\", \"hover_at\", \"scroll_document\", \"key_combination\", \"drag_and_drop\", ] interaction = client.interactions.create( model='gemini-2.5-computer-use-preview-10-2025', input=\"Open Chrome, then long-press at 200,400.\", tools=[ { \"type\": \"computer_use\", \"environment\": \"browser\", \"excluded_predefined_functions\": excluded_functions }, *custom_functions ] ) print(interaction)` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); // Define custom tools here const customFunctions = [...]; // Describe parameters as function declarations const excludedFunctions = [ \"open_web_browser\", \"wait_5_seconds\", \"go_back\", \"go_forward\", \"search\", \"navigate\", \"hover_at\", \"scroll_document\", \"key_combination\", \"drag_and_drop\", ]; const interaction = await ai.interactions.create({ model: 'gemini-2.5-computer-use-preview-10-2025', input: \"Open Chrome, then long-press at 200,400.\", tools: [ { type: \"computer_use\", environment: \"browser\", excluded_predefined_functions: excludedFunctions }, ...customFunctions ] }); console.log(interaction);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Managing thinking levels (Gemini 3.x) For computer use agents, you can configure different thinking levels to balance action quality and execution speed. Lower thinking levels generally achieve a good balance for standard automation tasks. Safety and security Configuring safety policies (Gemini 3.x) Gemini 3.x models include built-in safety service categories that automatically determine if user confirmation is required. Safety policy category Description `FINANCIAL_TRANSACTIONS` Blocks or triggers confirmation for actions involving payments, retail checkout, or regulated goods. `SENSITIVE_DATA_MODIFICATION` Protects health, financial, or government records from unauthorized modification. `COMMUNICATION_TOOL` Restricts the agent from autonomously sending emails, chat messages, or drafts. `ACCOUNT_CREATION` Restricts the agent from autonomously registering new accounts on websites. `DATA_MODIFICATION` Regulates overall file system modifications, data sharing, and storage deletion. `USER_CONSENT_MANAGEMENT` Requires user takeover for cookie consent banners and privacy prompts. `LEGAL_TERMS_AND_AGREEMENTS` Prevents the model from autonomously accepting Terms of Service or legally binding contracts. Safety overrides You can override select policies by passing overrides: Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Clean up the local folder by archiving old logs.\", tools=[ { \"type\": \"computer_use\", \"environment\": \"desktop\", \"disabled_safety_policies\": [ \"data_modification\" ] } ] )` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Clean up the local folder by archiving old logs.\", tools: [ { type: \"computer_use\", environment: \"desktop\", disabled_safety_policies: [ \"data_modification\" ] } ] });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Prompt injection detection (Gemini 3.x) Computer Use for Gemini 3.5 Flash or later supports an advanced safety\nmechanism to detect prompt injection attacks. When enabled, this feature\nchecks whether an included screenshot contains hidden adversarial\ninstructions (for example, \"Ignore previous commands\") and blocks\nexecution when detected. Prompt injection detection is an opt-in feature. The default is `false`. The following examples demonstrate how to enable prompt injection detection\nin your Computer Use tool configuration: Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.5-flash\", input=\"Search for flight deals and summarize top results.\", tools=[ { \"type\": \"computer_use\", \"environment\": \"desktop\", \"enable_prompt_injection_detection\": True, } ], )` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const interaction = await ai.interactions.create({ model: \"gemini-3.5-flash\", input: \"Search for flight deals and summarize top results.\", tools: [ { type: \"computer_use\", environment: \"desktop\", enablePromptInjectionDetection: true, } ] });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.ComputerUse; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Click the Submit button on the screen.\")) .tools(Arrays.asList(new ComputerUse())) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` cURL`curl \"https://generativelanguage.googleapis.com/v1beta/interactions?key=${GEMINI_API_KEY}\" \\\n-H 'Content-Type: application/json' \\\n-d '{ \"model\": \"gemini-3.5-flash\", \"input\": \"Search for flight deals and summarize top results.\", \"tools\": [ { \"type\": \"computer_use\", \"environment\": \"desktop\", \"enable_prompt_injection_detection\": true } ] }'` Acknowledge safety decision The response may include a `safety_decision` parameter in the function call arguments: `{ \"steps\": [ { \"type\": \"function_call\", \"name\": \"click_at\", \"arguments\": { \"x\": 60, \"y\": 100, \"safety_decision\": { \"explanation\": \"Must check check-box\", \"decision\": \"require_confirmation\" } } } ] }` If the `safety_decision` is `require_confirmation`, prompt the end user. If the user confirms, set `safety_acknowledgement` in `function_result`. Python`def get_safety_confirmation(safety_decision): # Prompt user for confirmation print(f\"Safety confirmation required: {safety_decision.get('explanation', '')}\") return \"CONTINUE\" # Or TERMINATE # Inside execute_function_calls, check for safety_decision: if 'safety_decision' in function_call.arguments: decision = get_safety_confirmation(function_call.arguments['safety_decision']) if decision == \"TERMINATE\": break # Include safety_acknowledgement inside the action result action_result[\"safety_acknowledgement\"] = True` Safety best practices Computer Use presents unique security and operational risks, as a model acting\non a user's behalf might encounter untrusted content on screens or make errors\nin executing actions. Implement the following best practices to protect user\ndata and systems: **Human-in-the-Loop (HITL):** **Enforce user confirmation:** When the safety response indicates\n`require_confirmation` (or legacy safety decision requires it), prompt the user for approval. **Provide custom safety instructions:** Implement a custom system instruction to define and enforce your own safety boundaries. For example: Python`from google import genai client = genai.Client() system_instruction = \"\"\" ## **RULE 1: Seek User Confirmation (USER_CONFIRMATION)** This is your first and most important check. If the next required action falls into any of the following categories, you MUST stop immediately, and seek the user's explicit permission. **Procedure for Seeking Confirmation:** * **For Consequential Actions:** Perform all preparatory steps (e.g., navigating, filling out forms, typing a message). You will ask for confirmation **AFTER** all necessary information is entered on the screen, but **BEFORE** you perform the final, irreversible action (e.g., before clicking \"Send\", \"Submit\", \"Confirm Purchase\", \"Share\"). * **For Prohibited Actions:** If the action is strictly forbidden (e.g., accepting legal terms, solving a CAPTCHA), you must first inform the user about the required action and ask for their confirmation to proceed. **USER_CONFIRMATION Categories:** * **Consent and Agreements:** You are FORBIDDEN from accepting, selecting, or agreeing to any of the following on the user's behalf. You must ask the user to confirm before performing these actions. * Terms of Service * Privacy Policies * Cookie consent banners * End User License Agreements (EULAs) * Any other legally significant contracts or agreements. * **Robot Detection:** You MUST NEVER attempt to solve or bypass the following. You must ask the user to confirm before performing these actions. * CAPTCHAs (of any kind) * Any other anti-robot or human-verification mechanisms, even if you are capable. * **Financial Transactions:** * Completing any purchase. * Managing or moving money (e.g., transfers, payments). * Purchasing regulated goods or participating in gambling. * **Sending Communications:** * Sending emails. * Sending messages on any platform (e.g., social media, chat apps). * Posting content on social media or forums. * **Accessing or Modifying Sensitive Information:** * Health, financial, or government records (e.g., medical history, tax forms, passport status). * Revealing or modifying sensitive personal identifiers (e.g., SSN, bank account number, credit card number). * **User Data Management:** * Accessing, downloading, or saving files from the web. * Sharing or sending files/data to any third party. * Transferring user data between systems. * **Browser Data Usage:** * Accessing or managing Chrome browsing history, bookmarks, autofill data, or saved passwords. * **Security and Identity:** * Logging into any user account. * Any action that involves misrepresentation or impersonation (e.g., creating a fan account, posting as someone else). * **Insurmountable Obstacles:** If you are technically unable to interact with a user interface element or are stuck in a loop you cannot resolve, ask the user to take over. --- ## **RULE 2: Default Behavior (ACTUATE)** If an action does **NOT** fall under the conditions for `USER_CONFIRMATION`, your default behavior is to **Actuate**. **Actuation Means:** You MUST proactively perform all necessary steps to move the user's request forward. Continue to actuate until you either complete the non-consequential task or encounter a condition defined in Rule 1. * **Example 1:** If asked to send money, you will navigate to the payment portal, enter the recipient's details, and enter the amount. You will then **STOP** as per Rule 1 and ask for confirmation before clicking the final \"Send\" button. * **Example 2:** If asked to post a message, you will navigate to the site, open the post composition window, and write the full message. You will then **STOP** as per Rule 1 and ask for confirmation before clicking the final \"Post\" button. After the user has confirmed, remember to get the user's latest screen before continuing to perform actions. # Final Response Guidelines: Write final response to the user in the following cases: - User confirmation - When the task is complete or you have enough information to respond to the user \"\"\" interaction = client.interactions.create( model=\"gemini-3.8-flash\", system_instruction=system_instruction, input=\"Prepare a draft but do not send.\", tools=[{ \"type\": \"computer_use\", \"environment\": \"browser\" }] )` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const systemInstruction = ` ## **RULE 1: Seek User Confirmation (USER_CONFIRMATION)** This is your first and most important check. If the next required action falls into any of the following categories, you MUST stop immediately, and seek the user's explicit permission. **Procedure for Seeking Confirmation:** * **For Consequential Actions:** Perform all preparatory steps (e.g., navigating, filling out forms, typing a message). You will ask for confirmation **AFTER** all necessary information is entered on the screen, but **BEFORE** you perform the final, irreversible action (e.g., before clicking \"Send\", \"Submit\", \"Confirm Purchase\", \"Share\"). * **For Prohibited Actions:** If the action is strictly forbidden (e.g., accepting legal terms, solving a CAPTCHA), you must first inform the user about the required action and ask for their confirmation to proceed. **USER_CONFIRMATION Categories:** * **Consent and Agreements:** You are FORBIDDEN from accepting, selecting, or agreeing to any of the following on the user's behalf. You must ask the user to confirm before performing these actions. * Terms of Service * Privacy Policies * Cookie consent banners * End User License Agreements (EULAs) * Any other legally significant contracts or agreements. * **Robot Detection:** You MUST NEVER attempt to solve or bypass the following. You must ask the user to confirm before performing these actions. * CAPTCHAs (of any kind) * Any other anti-robot or human-verification mechanisms, even if you are capable. * **Financial Transactions:** * Completing any purchase. * Managing or moving money (e.g., transfers, payments). * Purchasing regulated goods or participating in gambling. * **Sending Communications:** * Sending emails. * Sending messages on any platform (e.g., social media, chat apps). * Posting content on social media or forums. * **Accessing or Modifying Sensitive Information:** * Health, financial, or government records (e.g., medical history, tax forms, passport status). * Revealing or modifying sensitive personal identifiers (e.g., SSN, bank account number, credit card number). * **User Data Management:** * Accessing, downloading, or saving files from the web. * Sharing or sending files/data to any third party. * Transferring user data between systems. * **Browser Data Usage:** * Accessing or managing Chrome browsing history, bookmarks, autofill data, or saved passwords. * **Security and Identity:** * Logging into any user account. * Any action that involves misrepresentation or impersonation (e.g., creating a fan account, posting as someone else). * **Insurmountable Obstacles:** If you are technically unable to interact with a user interface element or are stuck in a loop you cannot resolve, ask the user to take over. --- ## **RULE 2: Default Behavior (ACTUATE)** If an action does **NOT** fall under the conditions for \\`USER_CONFIRMATION\\`, your default behavior is to **Actuate**. **Actuation Means:** You MUST proactively perform all necessary steps to move the user's request forward. Continue to actuate until you either complete the non-consequential task or encounter a condition defined in Rule 1. * **Example 1:** If asked to send money, you will navigate to the payment portal, enter the recipient's details, and enter the amount. You will then **STOP** as per Rule 1 and ask for confirmation before clicking the final \"Send\" button. * **Example 2:** If asked to post a message, you will navigate to the site, open the post composition window, and write the full message. You will then **STOP** as per Rule 1 and ask for confirmation before clicking the final \"Post\" button. After the user has confirmed, remember to get the user's latest screen before continuing to perform actions. # Final Response Guidelines: Write final response to the user in the following cases: - User confirmation - When the task is complete or you have enough information to respond to the user `; const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", system_instruction: systemInstruction, input: \"Prepare a draft but do not send.\", tools: [{ type: \"computer_use\", environment: \"browser\" }] });` Java`java\nimport com.google.genai.Client;\nimport com.google.genai.gaos.models.interactions.ComputerUse;\nimport com.google.genai.gaos.models.interactions.CreateModelInteraction;\nimport com.google.genai.gaos.models.interactions.Interaction;\nimport com.google.genai.gaos.models.interactions.InteractionsInput;\nimport com.google.genai.gaos.models.interactions.Model;\nimport com.google.genai.gaos.models.operations.CreateInteractionRequestBody;\nimport java.util.Arrays;\n\nClient client = new Client();\n\nCreateModelInteraction params =\n CreateModelInteraction.builder()\n .model(Model.of(\"gemini-3.8-flash\"))\n .input(InteractionsInput.of(\"Click the Submit button on the screen.\"))\n .tools(Arrays.asList(new ComputerUse()))\n .build();\n\nInteraction interaction =\n client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();\n\nSystem.out.println(interaction.outputText().orElse(\"\"));` **Secure execution environment:** Run your agent in a secure, sandboxed\nenvironment to limit its potential impact. This can be a sandboxed virtual\nmachine (VM), a container (e.g., Docker), or a dedicated browser profile\nwith limited permissions. See the\n[GitHub reference implementation](https://github.com/google/computer-use-preview/)\nfor sandbox setup guidance using Docker. **Input sanitization:** Sanitize all user-generated text in prompts to\nmitigate the risk of unintended instructions or prompt injection. This is a\nhelpful layer of security, but not a replacement for a secure execution\nenvironment. **Content guardrails:** Use guardrails and content safety APIs to evaluate\nuser inputs, tool inputs and outputs, and the agent's responses for appropriateness,\nprompt injection, and jailbreak detection. **Allowlists and blocklists:** Implement filtering mechanisms to control\nwhere the model can navigate and what it can do. A blocklist of prohibited\nwebsites is a good starting point, while a more restrictive allowlist is\neven more secure. **Observability and logging:** Maintain detailed logs for debugging,\nauditing, and incident response. Your client should log prompts,\nscreenshots, model-suggested actions (`function_call`), safety responses, and\nall actions ultimately executed by the client. **Environment management:** Ensure the GUI environment is consistent.\nUnexpected pop-ups, notifications, or changes in layout can confuse the\nmodel. Start from a known, clean state for each new task if possible. Model versions You can use Computer Use with the following models: [**Gemini 3.8 Flash**](/gemini-api/docs/models/gemini-3.8-flash) (`gemini-3.8-flash`): The recommended model for\ncomputer use, featuring high-accuracy UI interaction and reliable tool calling. [**Gemini 3.7 Flash**](/gemini-api/docs/models/gemini-3.7-flash) (`gemini-3.7-flash`): Previous stable model for\ncomputer use, featuring streamlined actions with intents, support for\nbrowser, mobile, and desktop environments, configurable safety policies, and\nprompt injection detection. [**Gemini 3.5 Flash-Lite**](/gemini-api/docs/models/gemini-3.5-flash-lite) (`gemini-3.5-flash-lite`): A low-latency, cost-effective model supporting\ncomputer use. [**Gemini 3.5 Flash**](/gemini-api/docs/models/gemini-3.5-flash) (`gemini-3.5-flash`): Previous stable model supporting\ncomputer use. [**Gemini 3 Flash Preview**](/gemini-api/docs/models/gemini-3-flash-preview) (`gemini-3-flash-preview`): Preview model\nsupporting computer use. [**Gemini 2.5 (Legacy Preview)**](/gemini-api/docs/models/gemini-2.5-computer-use-preview-10-2025) (`gemini-2.5-computer-use-preview-10-2025`): Legacy preview model optimized for browser-based computer use. What's next Experiment with Computer Use in the [Browserbase demo environment](http://gemini.browserbase.com). Check out the [Reference implementation](https://github.com/google/computer-use-preview) for example code. Learn about other Gemini API tools:\n [Function calling](/gemini-api/docs/function-calling) [Grounding with Google Search](/gemini-api/docs/google-search) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 57338, "slov": 7044, "odkazu": 149, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:58", "sha256": "6444560a078596300f2673892f16bee1ee07b81b4aadc63af33289818cad1602", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://policies.google.com/terms/generative-ai/use-policy", "https://github.com/google/computer-use-preview/", "https://playwright.dev/", "http://gemini.browserbase.com/", "https://github.com/google/computer-use-preview", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/crewai-example", "titulek": "Customer support analysis with Gemini and CrewAI | Gemini API | Google AI for Developers", "h1": "Customer support analysis with Gemini and CrewAI", "popis": "Building CrewAI Agents with Gemini", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/crewai-example", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Customer support analysis with Gemini and CrewAI  |  Gemini API  |  Google AI for Developers", "og:description": "Building CrewAI Agents with Gemini", "og:url": "https://ai.google.dev/gemini-api/docs/crewai-example", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Customer support analysis with Gemini and CrewAI"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Customer support analysis with Gemini and CrewAI", "item": "https://ai.google.dev/gemini-api/docs/crewai-example"}]}], "drobecky": ["Gemini API", "Customer support analysis with Gemini and CrewAI"], "osnova": [{"uroven": 1, "text": "Customer support analysis with Gemini and CrewAI"}, {"uroven": 2, "text": "Define components"}, {"uroven": 3, "text": "Tools"}, {"uroven": 3, "text": "Agents"}, {"uroven": 3, "text": "Tasks"}, {"uroven": 3, "text": "Crew"}, {"uroven": 2, "text": "Run the crew"}], "markdown": "Customer support analysis with Gemini and CrewAI [CrewAI](https://docs.crewai.com/introduction) is a framework for orchestrating\nautonomous AI agents that collaborate to achieve complex goals. It lets you\ndefine agents by specifying roles, goals, and backstories, and then define tasks\nfor them. This example demonstrates how to build a multi-agent system for analyzing\ncustomer support data to identify issues and propose process improvements using\nGemini 3 Flash, generating a report intended to be read by a Chief Operating\nOfficer (COO). The guide will show you how to create a \"crew\" of AI agents that can do the\nfollowing tasks: Fetch and analyze customer support data (simulated in this example). Identify recurring problems and process bottlenecks. Suggest actionable improvements. Compile the findings into a concise report suitable for a COO. You need a Gemini API key. If you don't already have one, you can [get one in\nGoogle AI Studio](https://aistudio.google.com/apikey). `pip install \"crewai[tools]\"` Set your Gemini API key as an environment variable named `GEMINI_API_KEY`, then\nconfigure CrewAI to use the Gemini model. `import os from crewai import LLM gemini_api_key = os.getenv(\"GEMINI_API_KEY\") gemini_llm = LLM( model='gemini/gemini-3.8-flash', api_key=gemini_api_key, temperature=1.0 # Use the Gemini 3 recommended temperature )` Define components Build CrewAI applications using **Tools**, **Agents**, **Tasks**, and the\n**Crew** itself. The following sections explain each of these components. Tools Tools are capabilities that agents can use to interact with the outside world or\nperform specific actions. Here, you define a placeholder tool to simulate\nfetching customer support data. In a real application, you would connect to a\ndatabase, API or file system. For more information on tools, see the [CrewAI\ntools guide](https://docs.crewai.com/concepts/tools). `from crewai.tools import BaseTool # Placeholder tool for fetching customer support data class CustomerSupportDataTool(BaseTool): name: str = \"Customer Support Data Fetcher\" description: str = ( \"Fetches recent customer support interactions, tickets, and feedback. \" \"Returns a summary string.\") def _run(self, argument: str) -> str: # In a real scenario, this would query a database or API. # For this example, return simulated data. print(f\"--- Fetching data for query: {argument} ---\") return ( \"\"\"Recent Support Data Summary: - 50 tickets related to 'login issues'. High resolution time (avg 48h). - 30 tickets about 'billing discrepancies'. Mostly resolved within 12h. - 20 tickets on 'feature requests'. Often closed without resolution. - Frequent feedback mentions 'confusing user interface' for password reset. - High volume of calls related to 'account verification process'. - Sentiment analysis shows growing frustration with 'login issues' resolution time. - Support agent notes indicate difficulty reproducing 'login issues'.\"\"\" ) support_data_tool = CustomerSupportDataTool()` Agents Agents are the individual AI workers in your crew. Each agent has a specific\n`role`, `goal`, `backstory`, assigned `llm`, and optional `tools`. For more\ninformation on agents, see the [CrewAI agents\nguide](https://docs.crewai.com/concepts/agents). `from crewai import Agent # Agent 1: Data analyst data_analyst = Agent( role='Customer Support Data Analyst', goal='Analyze customer support data to identify trends, recurring issues, and key pain points.', backstory=( \"\"\"You are an expert data analyst specializing in customer support operations. Your strength lies in identifying patterns and quantifying problems from raw support data.\"\"\" ), verbose=True, allow_delegation=False, # This agent focuses on its specific task tools=[support_data_tool], # Assign the data fetching tool llm=gemini_llm # Use the configured Gemini LLM ) # Agent 2: Process optimizer process_optimizer = Agent( role='Process Optimization Specialist', goal='Identify bottlenecks and inefficiencies in current support processes based on the data analysis. Propose actionable improvements.', backstory=( \"\"\"You are a specialist in optimizing business processes, particularly in customer support. You excel at pinpointing root causes of delays and inefficiencies and suggesting concrete solutions.\"\"\" ), verbose=True, allow_delegation=False, # No tools needed, this agent relies on the context provided by data_analyst. llm=gemini_llm ) # Agent 3: Report writer report_writer = Agent( role='Executive Report Writer', goal='Compile the analysis and improvement suggestions into a concise, clear, and actionable report for the COO.', backstory=( \"\"\"You are a skilled writer adept at creating executive summaries and reports. You focus on clarity, conciseness, and highlighting the most critical information and recommendations for senior leadership.\"\"\" ), verbose=True, allow_delegation=False, llm=gemini_llm )` Tasks Tasks define the specific assignments for the agents. Each task has a\n`description`, `expected_output`, and is assigned to an `agent`. Tasks are run\nsequentially by default and include the context of the previous task. For more\ninformation on tasks, see the [CrewAI tasks\nguide](https://docs.crewai.com/concepts/tasks). `from crewai import Task # Task 1: Analyze data analysis_task = Task( description=( \"\"\"Fetch and analyze the latest customer support interaction data (tickets, feedback, call logs) focusing on the last quarter. Identify the top 3-5 recurring issues, quantify their frequency and impact (e.g., resolution time, customer sentiment). Use the Customer Support Data Fetcher tool.\"\"\" ), expected_output=( \"\"\"A summary report detailing the key findings from the customer support data analysis, including: - Top 3-5 recurring issues with frequency. - Average resolution times for these issues. - Key customer pain points mentioned in feedback. - Any notable trends in sentiment or support agent observations.\"\"\" ), agent=data_analyst # Assign task to the data_analyst agent ) # Task 2: Identify bottlenecks and suggest improvements optimization_task = Task( description=( \"\"\"Based on the data analysis report provided by the Data Analyst, identify the primary bottlenecks in the support processes contributing to the identified issues (especially the top recurring ones). Propose 2-3 concrete, actionable process improvements to address these bottlenecks. Consider potential impact and ease of implementation.\"\"\" ), expected_output=( \"\"\"A concise list identifying the main process bottlenecks (e.g., lack of documentation for agents, complex escalation path, UI issues) linked to the key problems. A list of 2-3 specific, actionable recommendations for process improvement (e.g., update agent knowledge base, simplify password reset UI, implement proactive monitoring).\"\"\" ), agent=process_optimizer # Assign task to the process_optimizer agent # This task implicitly uses the output of analysis_task as context ) # Task 3: Compile COO report report_task = Task( description=( \"\"\"Compile the findings from the Data Analyst and the recommendations from the Process Optimization Specialist into a single, concise executive report for the COO. The report should clearly state: 1. The most critical customer support issues identified (with brief data points). 2. The key process bottlenecks causing these issues. 3. The recommended process improvements. Ensure the report is easy to understand, focuses on actionable insights, and is formatted professionally.\"\"\" ), expected_output=( \"\"\"A well-structured executive report (max 1 page) summarizing the critical support issues, underlying process bottlenecks, and clear, actionable recommendations for the COO. Use clear headings and bullet points.\"\"\" ), agent=report_writer # Assign task to the report_writer agent )` Crew The `Crew` brings the agents and tasks together, defining the workflow process\n(such as \"sequential\"). `from crewai import Crew, Process support_analysis_crew = Crew( agents=[data_analyst, process_optimizer, report_writer], tasks=[analysis_task, optimization_task, report_task], process=Process.sequential, # Tasks will run sequentially in the order defined verbose=True )` Run the crew Finally, kick off the crew execution with any necessary inputs. `# Start the crew's work print(\"--- Starting Customer Support Analysis Crew ---\") # The 'inputs' dictionary provides initial context if needed by the first task. # In this case, the tool simulates data fetching regardless of the input. result = support_analysis_crew.kickoff(inputs={'data_query': 'last quarter support data'}) print(\"--- Crew Execution Finished ---\") print(\"--- Final Report for COO ---\") print(result)` The script will now execute. The `Data Analyst` will use the tool, the `Process\nOptimizer` will analyze the findings, and the `Report Writer` will compile the\nfinal report, which is then printed to the console. The `verbose=True` setting\nwill show the detailed thought process and actions of each agent. To learn more about CrewAI, check out the [CrewAI\nintroduction](https://docs.crewai.com/introduction). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 9363, "slov": 1278, "odkazu": 131, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:26", "sha256": "ee98fc265477a1f75410be8fa7a6aac753b831ed63ca0590a971d2161ce3e0fe", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://docs.crewai.com/introduction", "https://docs.crewai.com/concepts/tools", "https://docs.crewai.com/concepts/agents", "https://docs.crewai.com/concepts/tasks", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/custom-agents", "titulek": "Building managed agents | Gemini API | Google AI for Developers", "h1": "Building managed agents", "popis": "How to create and use custom agents with managed agents in the Gemini API.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/custom-agents", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Building managed agents  |  Gemini API  |  Google AI for Developers", "og:description": "How to create and use custom agents with managed agents in the Gemini API.", "og:url": "https://ai.google.dev/gemini-api/docs/custom-agents", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Building managed agents"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Building managed agents", "item": "https://ai.google.dev/gemini-api/docs/custom-agents"}]}], "drobecky": ["Gemini API", "Building managed agents"], "osnova": [{"uroven": 1, "text": "Building managed agents"}, {"uroven": 2, "text": "Customize the Antigravity agent"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Tools and system instructions"}, {"uroven": 3, "text": "File-based customization"}, {"uroven": 4, "text": "Agent directory structure"}, {"uroven": 4, "text": "AGENTS.md"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 4, "text": "Skills: SKILL.md"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Create a managed agent"}, {"uroven": 3, "text": "From sources"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "From an existing environment (fork)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "With network rules"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Invoke the agent"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Overriding configuration at invocation"}, {"uroven": 3, "text": "Override system instruction and tools"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Override network configuration (refresh credentials)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Manage agents"}, {"uroven": 3, "text": "List agents"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Get an agent"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Delete an agent"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Agent definition reference"}, {"uroven": 3, "text": "Agent ID restrictions"}, {"uroven": 2, "text": "Iteration workflow"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Building managed agents Managed agents on the Gemini API let you extend the Antigravity agent with your own instructions, skills, and data. You can customize the agent inline at interaction time, or save the configuration as a managed agent you invoke by ID. Customize the Antigravity agent The fastest way to build a custom agent is to pass your configuration inline while creating a new interaction with no registration step required. You can extend the agent in several key ways: **[Model selection](/gemini-api/docs/antigravity-agent#model-selection)**: Choose the underlying Gemini model via `agent_config` (defaults to **Gemini 3.8 Flash**). **System instructions**: Pass inline text via `system_instruction` to shape behavior. **Tools**: Override default tools (Code Execution, Search, URL Context), register remote MCP servers, or define custom functions (Function Calling). **Files and skills**: Mount files like `AGENTS.md` and `SKILL.md` into the environment. Here is an example of passing all three inline: Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Analyze the Q1 revenue data and create a slide deck.\", system_instruction=\"You are a data analyst. Always include visualizations and export results as PDF.\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/AGENTS.md\", \"content\": \"Always use matplotlib for charts. Include a summary table in every report.\", }, { \"type\": \"inline\", \"target\": \".agents/skills/slide-maker/SKILL.md\", \"content\": \"---\\nname: slide-maker\\n---\\n# Slide Maker\\nCreate HTML slide decks from data analysis results.\", }, ], }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Analyze the Q1 revenue data and create a slide deck.\", system_instruction: \"You are a data analyst. Always include visualizations and export results as PDF.\", environment: { type: \"remote\", sources: [ { type: \"inline\", target: \".agents/AGENTS.md\", content: \"Always use matplotlib for charts. Include a summary table in every report.\", }, { type: \"inline\", target: \".agents/skills/slide-maker/SKILL.md\", content: \"---\\nname: slide-maker\\n---\\n# Slide Maker\\nCreate HTML slide decks from data analysis results.\", }, ], }, }, { timeout: 300000 }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Analyze the Q1 revenue data and create a slide deck.\", \"system_instruction\": \"You are a data analyst. Always include visualizations and export results as PDF.\", \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/AGENTS.md\", \"content\": \"Always use matplotlib for charts. Include a summary table in every report.\" }, { \"type\": \"inline\", \"target\": \".agents/skills/slide-maker/SKILL.md\", \"content\": \"---\\nname: slide-maker\\n---\\n# Slide Maker\\nCreate HTML slide decks from data analysis results.\" } ] } }'` Everything is defined at interaction time. No need to register anything first. The Antigravity agent harness provides the runtime (code execution, file management, web access) and your configuration layers on top. Tools and system instructions You can customize the agent's behavior and capabilities for a specific interaction using the `system_instruction` and `tools` parameters. **System instructions**: Use the `system_instruction` parameter to pass inline text that shapes the agent's behavior. This is ideal for quick tweaks you want to change per call. The `system_instruction` and `AGENTS.md` are additive; both apply when present. **Tools**: By default, the Antigravity agent has access to `code_execution`, `google_search`, and `url_context`. You can override this list by passing the `tools` parameter at interaction time. You can also register [remote MCP servers](/gemini-api/docs/antigravity-agent#mcp-servers) or define [custom functions (function calling)](/gemini-api/docs/antigravity-agent#function-calling) to connect the agent to your own APIs and databases. For full details on available tools, see [Antigravity Agent: Supported tools](/gemini-api/docs/antigravity-agent#supported-tools). File-based customization Agent directory structure While you can pass configuration inline, we recommend organizing your agent's files in a structured directory. This makes it easier to manage, version control, and mount into the agent's environment. A typical agent project directory looks like this: `my-agent/\n├── AGENTS.md # Instructions on how the agent should operate\n├── skills/ # Custom skills (subfolders and SKILL.md files)\n│ └── slide-maker/\n│ └── SKILL.md\n└── workspace/ # Initial data files and knowledge` The Antigravity runtime scans `.agents/` (and the root of the environment) for these files. AGENTS.md The agent automatically loads `.agents/AGENTS.md` (or `/.agents/AGENTS.md`) from the environment as system instructions on startup. Use `AGENTS.md` for long-form persona definitions, detailed guidelines, and instructions you want to version control alongside your code. Mount an `AGENTS.md` using an inline source: Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Analyze the Q1 revenue data and create a report.\", system_instruction=\"You are a data analyst. Always include visualizations and export results as PDF.\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/AGENTS.md\", \"content\": \"Always use matplotlib for charts. Include a summary table in every report.\", }, ], }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Analyze the Q1 revenue data and create a report.\", system_instruction: \"You are a data analyst. Always include visualizations and export results as PDF.\", environment: { type: \"remote\", sources: [ { type: \"inline\", target: \".agents/AGENTS.md\", content: \"Always use matplotlib for charts. Include a summary table in every report.\", }, ], }, }, { timeout: 300000 }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Analyze the Q1 revenue data and create a report.\", \"system_instruction\": \"You are a data analyst. Always include visualizations and export results as PDF.\", \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/AGENTS.md\", \"content\": \"Always use matplotlib for charts. Include a summary table in every report.\" } ] } }'` Skills: SKILL.md Skills are files that extend the agent's capabilities. Place them under `.agents/skills//SKILL.md` and the harness auto-discovers and registers them. `.agents/\n├── AGENTS.md\n└── skills/\n └── slide-maker/\n └── SKILL.md` Mount a skill using an inline source: Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Create a presentation about our Q1 results.\", system_instruction=\"You create presentations from data.\", environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/skills/slide-maker/SKILL.md\", \"content\": \"---\\nname: slide-maker\\ndescription: Create HTML slide decks\\n---\\n# Slide Maker\\n\\nWhen asked to create a presentation:\\n1. Analyze the input data\\n2. Create an HTML slide deck with reveal.js\\n3. Save to /workspace/output/slides.html\", }, ], }, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Create a presentation about our Q1 results.\", system_instruction: \"You create presentations from data.\", environment: { type: \"remote\", sources: [ { type: \"inline\", target: \".agents/skills/slide-maker/SKILL.md\", content: \"---\\nname: slide-maker\\ndescription: Create HTML slide decks\\n---\\n# Slide Maker\\n\\nWhen asked to create a presentation:\\n1. Analyze the input data\\n2. Create an HTML slide deck with reveal.js\\n3. Save to /workspace/output/slides.html\", }, ], }, }, { timeout: 300000 }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Create a presentation about our Q1 results.\", \"system_instruction\": \"You create presentations from data.\", \"environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/skills/slide-maker/SKILL.md\", \"content\": \"---\\nname: slide-maker\\ndescription: Create HTML slide decks\\n---\\n# Slide Maker\\n\\nWhen asked to create a presentation:\\n1. Analyze the input data\\n2. Create an HTML slide deck with reveal.js\\n3. Save to /workspace/output/slides.html\" } ] } }'` Skills loaded from `.agents/skills/` and `/.agents/skills/` are both discovered automatically. Create a managed agent Once you've iterated on your configuration, you can create it as a managed agent with `agents.create`. This lets you invoke the agent by ID without repeating the configuration each time. The `id` you specify when creating a managed agent must be unique to your project and must not start with reserved prefixes (e.g., `google-`, `gemini-`). See Agent ID restrictions for the full list of restricted prefixes. From sources Specify `base_agent`, `id`, `agent_config`, `system_instruction` and `base_environment` with sources. The platform provisions a fresh sandbox with your files on every invocation. See [Environments](/gemini-api/docs/agent-environment) for available source types (Git, GCS, inline). Python`from google import genai client = genai.Client() agent = client.agents.create( id=\"data-analyst\", base_agent=\"antigravity-preview-05-2026\", agent_config={ \"type\": \"antigravity\", \"model\": \"gemini-3.8-flash\", }, system_instruction=\"You are a data analyst. Always include visualizations and export results as PDF.\", base_environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/AGENTS.md\", \"content\": \"Always use matplotlib for charts. Include a summary table in every report.\", }, { \"type\": \"inline\", \"target\": \".agents/skills/slide-maker/SKILL.md\", \"content\": \"---\\nname: slide-maker\\n---\\n# Slide Maker\\nCreate HTML slide decks from data analysis results.\", }, { \"type\": \"repository\", \"source\": \"https://github.com/my-org/analysis-templates\", \"target\": \"/workspace/templates\", }, ], }, ) print(f\"Created agent: {agent.id}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const agent = await client.agents.create({ id: \"data-analyst\", base_agent: \"antigravity-preview-05-2026\", agent_config: { type: \"antigravity\", model: \"gemini-3.8-flash\", }, system_instruction: \"You are a data analyst. Always include visualizations and export results as PDF.\", base_environment: { type: \"remote\", sources: [ { type: \"inline\", target: \".agents/AGENTS.md\", content: \"Always use matplotlib for charts. Include a summary table in every report.\", }, { type: \"inline\", target: \".agents/skills/slide-maker/SKILL.md\", content: \"---\\nname: slide-maker\\n---\\n# Slide Maker\\nCreate HTML slide decks from data analysis results.\", }, { type: \"repository\", source: \"https://github.com/my-org/analysis-templates\", target: \"/workspace/templates\", }, ], }, }); console.log(`Created agent: ${agent.id}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/agents\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"id\": \"data-analyst\", \"base_agent\": \"antigravity-preview-05-2026\", \"agent_config\": { \"type\": \"antigravity\", \"model\": \"gemini-3.8-flash\" }, \"system_instruction\": \"You are a data analyst. Always include visualizations and export results as PDF.\", \"base_environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"inline\", \"target\": \".agents/AGENTS.md\", \"content\": \"Always use matplotlib for charts. Include a summary table in every report.\" }, { \"type\": \"inline\", \"target\": \".agents/skills/slide-maker/SKILL.md\", \"content\": \"---\\nname: slide-maker\\n---\\n# Slide Maker\\nCreate HTML slide decks from data analysis results.\" }, { \"type\": \"repository\", \"source\": \"https://github.com/my-org/analysis-templates\", \"target\": \"/workspace/templates\" } ] } }'` From an existing environment (fork) Iterate with the base Antigravity agent until the environment is right (packages installed, files in place), then fork it into a managed agent. Python`from google import genai client = genai.Client() # Step 1: set up the environment interactively interaction = client.interactions.create( agent=\"antigravity-preview-05-2026\", input=\"Install pandas, matplotlib, and seaborn. Create an analysis template at /workspace/template.py.\", environment=\"remote\", ) # Step 2: fork that environment into a managed agent agent = client.agents.create( id=\"my-data-analyst\", base_agent=\"antigravity-preview-05-2026\", system_instruction=\"You are a data analyst. Use the template at /workspace/template.py for all reports.\", base_environment=interaction.environment_id, ) print(f\"Forked agent successfully: {agent.id}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: \"antigravity-preview-05-2026\", input: \"Install pandas, matplotlib, and seaborn. Create an analysis template at /workspace/template.py.\", environment: \"remote\", }, { timeout: 300000 }); const agent = await client.agents.create({ id: \"my-data-analyst\", base_agent: \"antigravity-preview-05-2026\", system_instruction: \"You are a data analyst. Use the template at /workspace/template.py for all reports.\", base_environment: interaction.environment_id, }); console.log(`Forked agent successfully: ${agent.id}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"antigravity-preview-05-2026\", \"input\": \"Install pandas, matplotlib, and seaborn. Create an analysis template at /workspace/template.py.\", \"environment\": \"remote\" }'` With network rules You can lock down outbound access or inject credentials when saving a managed agent. For the full allowlist schema, credential patterns, and wildcards, see [Environments: Network configuration](/gemini-api/docs/agent-environment#network-configuration). The following example creates an `issue-resolver` agent that can only access GitHub and PyPI, with credentials injected for GitHub: Python`from google import genai client = genai.Client() agent = client.agents.create( id=\"issue-resolver\", base_agent=\"antigravity-preview-05-2026\", system_instruction=\"You resolve GitHub issues. Clone the repo, find the bug, write the fix, run the tests, and open a PR.\", base_environment={ \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/my-org/backend\", \"target\": \"/workspace/repo\", } ], \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\", \"transform\": { \"Authorization\": \"Basic YOUR_BASE64_TOKEN\" }, }, {\"domain\": \"pypi.org\"}, ] }, }, ) print(f\"Created issue-resolver agent successfully: {agent.id}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const agent = await client.agents.create({ id: \"issue-resolver\", base_agent: \"antigravity-preview-05-2026\", system_instruction: \"You resolve GitHub issues. Clone the repo, find the bug, write the fix, run the tests, and open a PR.\", base_environment: { type: \"remote\", sources: [ { type: \"repository\", source: \"https://github.com/my-org/backend\", target: \"/workspace/repo\", } ], network: { allowlist: [ { domain: \"api.github.com\", transform: { \"Authorization\": \"Basic YOUR_BASE64_TOKEN\" }, }, { domain: \"pypi.org\" }, ] } }, }); console.log(`Created issue-resolver agent successfully: ${agent.id}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/agents\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"id\": \"issue-resolver\", \"base_agent\": \"antigravity-preview-05-2026\", \"system_instruction\": \"You resolve GitHub issues. Clone the repo, find the bug, write the fix, run the tests, and open a PR.\", \"base_environment\": { \"type\": \"remote\", \"sources\": [ { \"type\": \"repository\", \"source\": \"https://github.com/my-org/backend\", \"target\": \"/workspace/repo\" } ], \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\", \"transform\": { \"Authorization\": \"Basic YOUR_BASE64_TOKEN\" } }, {\"domain\": \"pypi.org\"} ] } } }'` Invoke the agent Call your managed agent with your agent ID by creating a new interaction. Each invocation forks the base environment, so every run starts clean. Python`result = client.interactions.create( agent=\"data-analyst\", input=\"Analyze Q1 revenue data from /workspace/templates/sample.csv and create a slide deck.\", environment=\"remote\", ) print(result.output_text)` JavaScript`const result = await client.interactions.create({ agent: \"data-analyst\", input: \"Analyze Q1 revenue data from /workspace/templates/sample.csv and create a slide deck.\", environment: \"remote\", }, { timeout: 300000 }); console.log(result.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"data-analyst\", \"input\": \"Analyze Q1 revenue data from /workspace/templates/sample.csv and create a slide deck.\", \"environment\": \"remote\" }'` For multi-turn conversations and streaming, see the [Quickstart](/gemini-api/docs/managed-agents-quickstart). The same `previous_interaction_id` and `environment` patterns apply to managed agents. Managed agents also support background execution and cancellation. For details and code examples, see [Antigravity Agent: Background execution](/gemini-api/docs/antigravity-agent#background-execution). Overriding configuration at invocation You can override the agent's default `system_instruction`, `tools`, and\n`environment` network configuration when creating an interaction. This\nlets you modify the agent's behavior, capabilities, or credentials for a\nspecific run without changing the stored agent definition. Override system instruction and tools Python`result = client.interactions.create( agent=\"data-analyst\", input=\"Analyze Q1 revenue data, but do not create a slide deck. Just output a summary table.\", system_instruction=\"You are a data analyst. Focus ONLY on summary tables. Ignore default instructions about slides.\", tools=[{\"type\": \"code_execution\"}], # Override to only use code execution environment=\"remote\", ) print(result.output_text)` JavaScript`const result = await client.interactions.create({ agent: \"data-analyst\", input: \"Analyze Q1 revenue data, but do not create a slide deck. Just output a summary table.\", system_instruction: \"You are a data analyst. Focus ONLY on summary tables. Ignore default instructions about slides.\", tools: [{ type: \"code_execution\" }], // Override to only use code execution environment: \"remote\", }, { timeout: 300000 }); console.log(result.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"data-analyst\", \"input\": \"Analyze Q1 revenue data, but do not create a slide deck. Just output a summary table.\", \"system_instruction\": \"You are a data analyst. Focus ONLY on summary tables. Ignore default instructions about slides.\", \"tools\": [{\"type\": \"code_execution\"}], \"environment\": \"remote\" }'` Override network configuration (refresh credentials) If your managed agent has network credentials baked into its `base_environment`,\nyou can override them at invocation time to refresh expired tokens or rotate API\nkeys. Pass an `environment` object with a new `network` configuration. The new\nnetwork rules fully replace the previous ones for that interaction. The base\nenvironment's sources (files, repositories) are preserved. Python`# Invoke the agent with a fresh token, overriding the base_environment credentials result = client.interactions.create( agent=\"issue-resolver\", input=\"Fix issue #42 and open a PR.\", environment={ \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\", \"transform\": { \"Authorization\": \"Bearer ghp_REFRESHED_TOKEN\" }, }, {\"domain\": \"pypi.org\"}, ] }, }, ) print(result.output_text)` JavaScript`// Invoke the agent with a fresh token, overriding the base_environment credentials const result = await client.interactions.create({ agent: \"issue-resolver\", input: \"Fix issue #42 and open a PR.\", environment: { type: \"remote\", network: { allowlist: [ { domain: \"api.github.com\", transform: { \"Authorization\": \"Bearer ghp_REFRESHED_TOKEN\" }, }, { domain: \"pypi.org\" }, ] }, }, }, { timeout: 300000 }); console.log(result.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"agent\": \"issue-resolver\", \"input\": \"Fix issue #42 and open a PR.\", \"environment\": { \"type\": \"remote\", \"network\": { \"allowlist\": [ { \"domain\": \"api.github.com\", \"transform\": { \"Authorization\": \"Bearer ghp_REFRESHED_TOKEN\" } }, {\"domain\": \"pypi.org\"} ] } } }'` Manage agents You can list, get, and delete agents. List agents Python`agents = client.agents.list() for a in agents.agents: print(f\"{a.id}: {a.description}\")` JavaScript`const agents = await client.agents.list(); if (agents.agents) { for (const a of agents.agents) { console.log(`${a.id}: ${a.description}`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1beta/agents\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Get an agent Python`agent = client.agents.get(id=\"data-analyst\") print(agent)` JavaScript`const agent = await client.agents.get(\"data-analyst\"); console.log(agent);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1beta/agents/data-analyst\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Delete an agent Deleting removes the configuration. Existing environments and interactions created by the agent are not affected. Python`client.agents.delete(id=\"data-analyst\")` JavaScript`await client.agents.delete(\"data-analyst\");` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"antigravity-preview-05-2026\")) .input(InteractionsInput.of(\"Build a simple REST API server in Node.js.\")) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/agents/data-analyst\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Agent definition reference Field Type Required Description `id` string Yes Unique agent identifier within the Google Cloud project. Used to invoke the agent. Must not use reserved prefixes. See Agent ID restrictions. `description` string No Human-readable description of the agent. `base_agent` string Yes Base agent ID (e.g., `antigravity-preview-05-2026`). `agent_config` object No Configuration for the base agent, including model selection (`{\"type\": \"antigravity\", \"model\": \"gemini-3.8-flash\"}`). Defaults to `gemini-3.8-flash` if omitted. Cannot be overridden at interaction time for named agents. `system_instruction` string No System prompt defining behavior and persona. `tools` array No Tools the agent can use. If omitted, defaults to `code_execution`, `google_search`, and `url_context`. Supported tools include `code_execution`, `google_search`, `url_context`, `mcp_server`, and custom `function` definitions. `base_environment` string or object No `\"remote\"`, an `environment_id`, or a config object with `sources` and `network`. See Environments. Agent ID restrictions When creating a managed agent, the `id` you specify must follow these rules: It must be unique to your Google Cloud project. It must **not** start with any of the following reserved prefixes (case-insensitive), otherwise creation will fail:\n `antigravity-` `veo-` `omni-` `lyria-` `imagen-` `gemma-` `gemini-` `google-` `youtube-` `android-` `chrome-` `pixel-` `waze-` `fitbit-` `nest-` `kaggle-` Iteration workflow **Prototype** with the base Antigravity agent. Pass system instruction and environment sources inline. Test instructions, skills, and environment setup interactively. **Stabilize** the environment. Install packages, mount sources, verify everything works. **Persist** as a managed agent by creating a new agent, either from sources or by forking the environment. **Update** the agent definition. Change system instruction, swap skills, or add sources. The next invocation picks up the new configuration. Limitations **Preview status**: Managed agents are in preview. Features and schemas may change. **Base agent and models**: Only `antigravity-preview-05-2026` is supported as `base_agent`. Supported model options in `agent_config` are `gemini-3.8-flash` (default), `gemini-3.7-flash`, `gemini-3.6-flash`, `gemini-3.5-flash`, and `gemini-3.5-flash-lite`. For named agents, the model cannot be overridden at interaction time. **No versioning**: Agent versioning and rollback are not yet available. **No subagent nesting**: Subagent delegation is not yet supported. You can have up to 1000 managed agents. What's next [Agents Overview](/gemini-api/docs/agents): Learn about the core concepts of managed agents. [Quickstart](/gemini-api/docs/managed-agents-quickstart): Start building with multi-turn conversations and streaming. [Antigravity Agent](/gemini-api/docs/antigravity-agent): Explore capabilities, tools, and pricing for the default agent. [Agent Environments](/gemini-api/docs/agent-environment): Configure sandboxes, sources, and networking. [Managed Agents API on Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/managed-agents): For creating agents with built-in organizational governance. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 35880, "slov": 3925, "odkazu": 138, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:02", "sha256": "a79bb1f2813bc76ef34a2dc2f8b919da301fd778a8eda09f2cc6b0eba8764cd8", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://github.com/google-gemini/Gemini-API-CLI", "https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/managed-agents", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/deep-research", "titulek": "Gemini Deep Research agent | Gemini API | Google AI for Developers", "h1": "Gemini Deep Research agent", "popis": "Deep Research is an agent designed to perform complex, long-running context gathering and synthesis tasks.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/deep-research", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini Deep Research agent  |  Gemini API  |  Google AI for Developers", "og:description": "Deep Research is an agent designed to perform complex, long-running context gathering and synthesis tasks.", "og:url": "https://ai.google.dev/gemini-api/docs/deep-research", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Gemini Deep Research agent"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Gemini Deep Research agent", "item": "https://ai.google.dev/gemini-api/docs/deep-research"}]}], "drobecky": ["Gemini API", "Gemini Deep Research agent"], "osnova": [{"uroven": 1, "text": "Gemini Deep Research agent"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Supported versions"}, {"uroven": 2, "text": "Collaborative planning"}, {"uroven": 3, "text": "Step 1: Request a plan"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Step 2: Refine the plan (optional)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Step 3: Approve and execute"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Visualization"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Supported tools"}, {"uroven": 3, "text": "Google Search"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "URL Context"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Code Execution"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "MCP servers"}, {"uroven": 4, "text": "Basic usage"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "File Search"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Steerability and formatting"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multimodal inputs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Document understanding"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Handling long-running tasks"}, {"uroven": 3, "text": "Streaming"}, {"uroven": 4, "text": "Stream event types"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Follow-up questions and interactions"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "When to use Gemini Deep Research agent"}, {"uroven": 2, "text": "Agent configuration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Availability and pricing"}, {"uroven": 3, "text": "Estimated costs"}, {"uroven": 2, "text": "Safety considerations"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Gemini Deep Research agent The Gemini Deep Research agent autonomously plans, executes, and synthesizes\nmulti-step research tasks. Powered by Gemini, it navigates complex\ninformation landscapes to produce detailed, cited reports. New\ncapabilities allow you to collaboratively plan with the agent, connect to\nexternal tools using MCP servers, include\nvisualizations (like charts and graphs), and provide documents directly\nas input. Research tasks involve iterative searching and reading and can take several minutes to complete. You must use [background execution](/gemini-api/docs/background-execution) (set `background=true`)\nto run the agent asynchronously and poll for results or stream updates. See\nHandling long-running tasks for more details. The following example shows how to start a research task in the background\nand poll for results. Python`import time from google import genai client = genai.Client() interaction = client.interactions.create( input=\"Research the history of Google TPUs.\", agent=\"deep-research-preview-04-2026\", background=True, ) print(f\"Research started: {interaction.id}\") while True: interaction = client.interactions.get(interaction.id) if interaction.status == \"completed\": print(interaction.steps[-1].content[0].text) break elif interaction.status == \"failed\": print(f\"Research failed: {interaction.error}\") break time.sleep(10)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ input: 'Research the history of Google TPUs.', agent: 'deep-research-preview-04-2026', background: true }); console.log(`Research started: ${interaction.id}`); while (true) { const result = await client.interactions.get(interaction.id); if (result.status === 'completed') { console.log(result.steps.at(-1).content[0].text); break; } else if (result.status === 'failed') { console.log(`Research failed: ${result.error}`); break; } await new Promise(resolve => setTimeout(resolve, 10000)); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`# 1. Start the research task\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"input\": \"Research the history of Google TPUs.\", \"agent\": \"deep-research-preview-04-2026\", \"background\": true }' # 2. Poll for results (Replace INTERACTION_ID) # curl -X GET \"https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID\" \\ # -H \"x-goog-api-key: $GEMINI_API_KEY\"` Supported versions The Deep Research agent comes in two versions: **Deep Research** (`deep-research-preview-04-2026`): Designed for speed and efficiency, ideal to be streamed back to a client UI. **Deep Research Max** (`deep-research-max-preview-04-2026`): Maximum comprehensiveness for automated context gathering and synthesis. Collaborative planning Collaborative planning gives you control over the research direction before the\nagent starts its work by letting you review and refine the research plan before\nexecution. When enabled, the agent returns a proposed research plan instead of\nexecuting immediately. You can then review, modify, or approve the plan through\nmulti-turn interactions. Step 1: Request a plan Set `collaborative_planning=True` in the first interaction. The agent\nreturns a research plan instead of a full report. Python`from google import genai client = genai.Client() # First interaction: request a research plan plan_interaction = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"Do some research on Google TPUs.\", agent_config={ \"type\": \"deep-research\", \"thinking_summaries\": \"auto\", \"collaborative_planning\": True, }, background=True, ) # Wait for and retrieve the plan while (result := client.interactions.get(id=plan_interaction.id)).status != \"completed\": time.sleep(5) print(result.steps[-1].content[0].text)` JavaScript`const planInteraction = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'Do some research on Google TPUs.', agent_config: { type: 'deep-research', thinking_summaries: 'auto', collaborative_planning: true }, background: true }); let result; while ((result = await client.interactions.get(planInteraction.id)).status !== 'completed') { await new Promise(r => setTimeout(r, 5000)); } console.log(result.steps.at(-1).content[0].text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"deep-research-preview-04-2026\", \"input\": \"Do some research on Google TPUs.\", \"agent_config\": { \"type\": \"deep-research\", \"thinking_summaries\": \"auto\", \"collaborative_planning\": true }, \"background\": true }'` Step 2: Refine the plan (optional) Use `previous_interaction_id` to continue the conversation and iterate\non the plan. Keep `collaborative_planning=True` to stay in planning\nmode. Python`# Second interaction: refine the plan refined_plan = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"Focus more on the differences between Google TPUs and competitor hardware, and less on the history.\", agent_config={ \"type\": \"deep-research\", \"thinking_summaries\": \"auto\", \"collaborative_planning\": True, }, previous_interaction_id=plan_interaction.id, background=True, ) while (result := client.interactions.get(id=refined_plan.id)).status != \"completed\": time.sleep(5) print(result.steps[-1].content[0].text)` JavaScript`const refinedPlan = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'Focus more on the differences between Google TPUs and competitor hardware, and less on the history.', agent_config: { type: 'deep-research', thinking_summaries: 'auto', collaborative_planning: true }, previous_interaction_id: planInteraction.id, background: true }); let result; while ((result = await client.interactions.get(refinedPlan.id)).status !== 'completed') { await new Promise(r => setTimeout(r, 5000)); } console.log(result.steps.at(-1).content[0].text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"deep-research-preview-04-2026\", \"input\": \"Focus more on the differences between Google TPUs and competitor hardware, and less on the history.\", \"agent_config\": { \"type\": \"deep-research\", \"thinking_summaries\": \"auto\", \"collaborative_planning\": true }, \"previous_interaction_id\": \"PREVIOUS_INTERACTION_ID\", \"background\": true }'` Step 3: Approve and execute Set `collaborative_planning=False` (or omit it) to approve the plan and\nstart the research. Python`# Third interaction: approve the plan and kick off research final_report = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"Plan looks good!\", agent_config={ \"type\": \"deep-research\", \"thinking_summaries\": \"auto\", \"collaborative_planning\": False, }, previous_interaction_id=refined_plan.id, background=True, ) while (result := client.interactions.get(id=final_report.id)).status != \"completed\": time.sleep(5) print(result.steps[-1].content[0].text)` JavaScript`const finalReport = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'Plan looks good!', agent_config: { type: 'deep-research', thinking_summaries: 'auto', collaborative_planning: false }, previous_interaction_id: refinedPlan.id, background: true }); let result; while ((result = await client.interactions.get(finalReport.id)).status !== 'completed') { await new Promise(r => setTimeout(r, 5000)); } console.log(result.steps.at(-1).content[0].text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"deep-research-preview-04-2026\", \"input\": \"Plan looks good!\", \"agent_config\": { \"type\": \"deep-research\", \"thinking_summaries\": \"auto\", \"collaborative_planning\": false }, \"previous_interaction_id\": \"PREVIOUS_INTERACTION_ID\", \"background\": true }'` Visualization When `visualization` is set to `\"auto\"`, the agent can generate charts,\ngraphs, and other visual elements to support its research findings.\nGenerated images are included in the response steps and streamed as\n`image` deltas. For best results, explicitly ask for visuals in your\nquery — for example, \"Include charts showing trends over time\" or\n\"Generate graphics comparing market share.\" Setting `visualization` to\n`\"auto\"` enables the capability, but the agent generates visuals only\nwhen the prompt requests them. Python`import base64 import time from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"Analyze global semiconductor market trends. Include graphics showing market share changes.\", agent_config={ \"type\": \"deep-research\", \"visualization\": \"auto\", }, background=True, ) print(f\"Research started: {interaction.id}\") while (result := client.interactions.get(id=interaction.id)).status != \"completed\": time.sleep(5) for step in result.steps: if step.type == \"model_output\": for content_item in step.content: if content_item.type == \"text\": print(content_item.text) elif content_item.type == \"image\" and content_item.data: image_bytes = base64.b64decode(content_item.data) print(f\"Received image: {len(image_bytes)} bytes\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'Analyze global semiconductor market trends. Include graphics showing market share changes.', agent_config: { type: 'deep-research', visualization: 'auto' }, background: true }); console.log(`Research started: ${interaction.id}`); let result; while ((result = await client.interactions.get(interaction.id)).status !== 'completed') { await new Promise(r => setTimeout(r, 5000)); } for (const step of result.steps) { if (step.type === 'model_output') { for (const contentItem of step.content) { if (contentItem.type === 'text') { console.log(contentItem.text); } else if (contentItem.type === 'image' && contentItem.data) { console.log(`[Image Output: ${contentItem.data.substring(0, 20)}...]`); } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"deep-research-preview-04-2026\", \"input\": \"Analyze global semiconductor market trends. Include graphics showing market share changes.\", \"agent_config\": { \"type\": \"deep-research\", \"visualization\": \"auto\" }, \"background\": true }'` Supported tools Deep Research supports multiple built-in and external tools. By default\n(when no `tools` parameter is provided), the agent has access to Google\nSearch, URL Context, and Code Execution. You can explicitly\nspecify tools to restrict or extend the agent's capabilities. Tool Type value Description Google Search `google_search` Search the public web. Enabled by default. URL Context `url_context` Read and summarize web page content. Enabled by default. Code Execution `code_execution` Execute code to perform calculations and data analysis. Enabled by default. MCP Server `mcp_server` Connect to remote MCP servers for external tool access. File Search `file_search` Search your uploaded document corpora. Google Search Explicitly enable Google Search as the only tool: Python`interaction = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"What are the latest developments in quantum computing?\", tools=[{\"type\": \"google_search\"}], background=True, )` JavaScript`const interaction = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'What are the latest developments in quantum computing?', tools: [{ type: 'google_search' }], background: true });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"deep-research-preview-04-2026\", \"input\": \"What are the latest developments in quantum computing?\", \"tools\": [{\"type\": \"google_search\"}], \"background\": true }'` URL Context Give the agent the ability to read and summarize specific web pages: Python`interaction = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"Summarize the content of https://www.wikipedia.org/.\", tools=[{\"type\": \"url_context\"}], background=True, )` JavaScript`const interaction = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'Summarize the content of https://www.wikipedia.org/.', tools: [{ type: 'url_context' }], background: true });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"deep-research-preview-04-2026\", \"input\": \"Summarize the content of https://www.wikipedia.org/.\", \"tools\": [{\"type\": \"url_context\"}], \"background\": true }'` Code Execution Allow the agent to execute code for calculations and data analysis: Python`interaction = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"Calculate the 50th Fibonacci number.\", tools=[{\"type\": \"code_execution\"}], background=True, )` JavaScript`const interaction = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'Calculate the 50th Fibonacci number.', tools: [{ type: 'code_execution' }], background: true });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"input\": \"Calculate the 50th Fibonacci number.\", \"agent\": \"deep-research-preview-04-2026\", \"tools\": [{\"type\": \"code_execution\"}], \"background\": true }'` MCP servers Connect to remote MCP servers to give the agent access to external tools and\nservices. Provide the server `name` and `url` in the tools configuration. You can also\npass authentication credentials and restrict which tools the agent can call. Field Type Required Description `type` `string` Yes Must be `\"mcp_server\"`. `name` `string` No A display name for the MCP server. `url` `string` No The full URL for the MCP server endpoint. `headers` `object` No Key-value pairs sent as HTTP headers with every request to the server (for example, authentication tokens). `allowed_tools` `array` No Restrict which tools from the server the agent may call. Basic usage Python`interaction = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"Check the status of my last server deployment.\", tools=[ { \"type\": \"mcp_server\", \"name\": \"Deployment Tracker\", \"url\": \"https://mcp.example.com/mcp\", \"headers\": {\"Authorization\": \"Bearer my-token\"}, } ], background=True, )` JavaScript`const interaction = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'Check the status of my last server deployment.', tools: [ { type: 'mcp_server', name: 'Deployment Tracker', url: 'https://mcp.example.com/mcp', headers: { Authorization: 'Bearer my-token' } } ], background: true });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"deep-research-preview-04-2026\", \"input\": \"Check the status of my last server deployment.\", \"tools\": [ { \"type\": \"mcp_server\", \"name\": \"Deployment Tracker\", \"url\": \"https://mcp.example.com/mcp\", \"headers\": {\"Authorization\": \"Bearer my-token\"} } ], \"background\": true }'` File Search Give the agent access to your own data by using the [File Search](/gemini-api/docs/file-search) tool. Python`import time from google import genai client = genai.Client() interaction = client.interactions.create( input=\"Compare our 2025 fiscal year report against current public web news.\", agent=\"deep-research-preview-04-2026\", background=True, tools=[ { \"type\": \"file_search\", \"file_search_store_names\": ['fileSearchStores/my-store-name'] } ] )` JavaScript`const interaction = await client.interactions.create({ input: 'Compare our 2025 fiscal year report against current public web news.', agent: 'deep-research-preview-04-2026', background: true, tools: [ { type: 'file_search', file_search_store_names: ['fileSearchStores/my-store-name'] }, ] });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"input\": \"Compare our 2025 fiscal year report against current public web news.\", \"agent\": \"deep-research-preview-04-2026\", \"background\": true, \"tools\": [ {\"type\": \"file_search\", \"file_search_store_names\": [\"fileSearchStores/my-store-name\"]}, ] }'` Steerability and formatting You can steer the agent's output by providing specific formatting instructions\nin your prompt. This allows you to structure reports into specific sections and\nsubsections, include data tables, or adjust tone for different audiences (e.g.,\n\"technical,\" \"executive,\" \"casual\"). Define the desired output format explicitly in your input text. Python`prompt = \"\"\" Research the competitive landscape of EV batteries. Format the output as a technical report with the following structure: 1. Executive Summary 2. Key Players (Must include a data table comparing capacity and chemistry) 3. Supply Chain Risks \"\"\" interaction = client.interactions.create( input=prompt, agent=\"deep-research-preview-04-2026\", background=True )` JavaScript`const prompt = ` Research the competitive landscape of EV batteries. Format the output as a technical report with the following structure: 1. Executive Summary 2. Key Players (Must include a data table comparing capacity and chemistry) 3. Supply Chain Risks `; const interaction = await client.interactions.create({ input: prompt, agent: 'deep-research-preview-04-2026', background: true, });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"input\": \"Research the competitive landscape of EV batteries.\\n\\nFormat the output as a technical report with the following structure: \\n1. Executive Summary\\n2. Key Players (Must include a data table comparing capacity and chemistry)\\n3. Supply Chain Risks\", \"agent\": \"deep-research-preview-04-2026\", \"background\": true }'` Multimodal inputs Deep Research supports multimodal inputs, including images and documents (PDFs), allowing\nthe agent to analyze visual content and conduct web-based research\ncontextualized by the provided inputs. Python`import time from google import genai client = genai.Client() prompt = \"\"\"Analyze the interspecies dynamics and behavioral risks present in the provided image of the African watering hole. Specifically, investigate the symbiotic relationship between the avian species and the pachyderms shown, and conduct a risk assessment for the reticulated giraffes based on their drinking posture relative to the specific predator visible in the foreground.\"\"\" interaction = client.interactions.create( input=[ {\"type\": \"text\", \"text\": prompt}, { \"type\": \"image\", \"mime_type\": \"image/jpeg\", \"uri\": \"https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg\" } ], agent=\"deep-research-preview-04-2026\", background=True ) print(f\"Research started: {interaction.id}\") while True: interaction = client.interactions.get(interaction.id) if interaction.status == \"completed\": print(interaction.steps[-1].content[0].text) break elif interaction.status == \"failed\": print(f\"Research failed: {interaction.error}\") break time.sleep(10)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const prompt = `Analyze the interspecies dynamics and behavioral risks present in the provided image of the African watering hole. Specifically, investigate the symbiotic relationship between the avian species and the pachyderms shown, and conduct a risk assessment for the reticulated giraffes based on their drinking posture relative to the specific predator visible in the foreground.`; const interaction = await client.interactions.create({ input: [ { type: 'text', text: prompt }, { type: 'image', mime_type: \"image/jpeg\", uri: 'https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg' } ], agent: 'deep-research-preview-04-2026', background: true }); console.log(`Research started: ${interaction.id}`); while (true) { const result = await client.interactions.get(interaction.id); if (result.status === 'completed') { console.log(result.steps.at(-1).content[0].text); break; } else if (result.status === 'failed') { console.log(`Research failed: ${result.error}`); break; } await new Promise(resolve => setTimeout(resolve, 10000)); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`# 1. Start the research task with image input\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"input\": [ {\"type\": \"text\", \"text\": \"Analyze the interspecies dynamics and behavioral risks present in the provided image of the African watering hole. Specifically, investigate the symbiotic relationship between the avian species and the pachyderms shown, and conduct a risk assessment for the reticulated giraffes based on their drinking posture relative to the specific predator visible in the foreground.\"}, {\"type\": \"image\", \"mime_type\": \"image/jpeg\", \"uri\": \"https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg\"} ], \"agent\": \"deep-research-preview-04-2026\", \"background\": true }' # 2. Poll for results (Replace INTERACTION_ID) # curl -X GET \"https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID\" \\ # -H \"x-goog-api-key: $GEMINI_API_KEY\"` Document understanding Document understanding allows passing documents directly as multimodal input.\nThe agent analyzes the\nprovided documents and conducts research grounded in their content. Python`from google import genai client = genai.Client() interaction = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=[ {\"type\": \"text\", \"text\": \"What is this document about?\"}, { \"type\": \"document\", \"uri\": \"https://arxiv.org/pdf/1706.03762\", \"mime_type\": \"application/pdf\", }, ], background=True, )` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: [ { type: 'text', text: 'What is this document about?' }, { type: 'document', uri: 'https://arxiv.org/pdf/1706.03762', mime_type: 'application/pdf' } ], background: true });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`# 1. Start the research task with document input\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"agent\": \"deep-research-preview-04-2026\", \"input\": [ {\"type\": \"text\", \"text\": \"What is this document about?\"}, {\"type\": \"document\", \"uri\": \"https://arxiv.org/pdf/1706.03762\", \"mime_type\": \"application/pdf\"} ], \"background\": true }'` Handling long-running tasks Deep Research is a multi-step process involving planning, searching, reading,\nand writing. This cycle typically exceeds the standard timeout limits of\nsynchronous API calls. Agents are required to use `background=True`. The API returns a partial\n`Interaction` object immediately. You can use the `id` property to retrieve an\ninteraction for polling. The interaction state will transition from\n`in_progress` to `completed` or `failed`. For a comprehensive guide on managing background tasks, see [Background execution](/gemini-api/docs/background-execution). Streaming Deep Research supports streaming to receive real-time updates on the research\nprogress including thought summaries, text output, and generated images.\nYou must set `stream=True` and `background=True`. To receive intermediate reasoning steps (thoughts) and progress updates,\nyou must enable **thinking summaries** by setting `thinking_summaries` to\n`\"auto\"` in the `agent_config`. Without this, the stream may only provide the\nfinal results. Stream event types Event type Delta type Description `step.delta` `thought` Intermediate reasoning step from the agent. `step.delta` `text` Part of the final text output. `step.delta` `image` A generated image (base64-encoded). The following example starts a research task and processes the stream with\nautomatic reconnection. It tracks the `interaction_id` and `last_event_id` so\nthat if the connection drops (for example, after the 600-second timeout), it can\nresume from where it left off. Python`from google import genai client = genai.Client() interaction_id = None last_event_id = None is_complete = False def process_stream(stream): global interaction_id, last_event_id, is_complete for event in stream: if event.event_type == \"interaction.created\": interaction_id = event.interaction.id if event.event_id: last_event_id = event.event_id if event.event_type == \"step.delta\": if event.delta.type == \"text\": print(event.delta.text, end=\"\", flush=True) elif event.delta.type == \"thought\": print(f\"Thought: {event.delta.text}\", flush=True) elif event.event_type in (\"interaction.completed\", \"interaction.error\"): is_complete = True stream = client.interactions.create( input=\"Research the history of Google TPUs.\", agent=\"deep-research-preview-04-2026\", background=True, stream=True, agent_config={\"type\": \"deep-research\", \"thinking_summaries\": \"auto\"}, ) process_stream(stream) # Reconnect if the connection drops while not is_complete and interaction_id: status = client.interactions.get(interaction_id) if status.status != \"in_progress\": break stream = client.interactions.get( id=interaction_id, stream=True, last_event_id=last_event_id, ) process_stream(stream)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); let interactionId; let lastEventId; let isComplete = false; async function processStream(stream) { for await (const event of stream) { if (event.type === 'interaction.created') { interactionId = event.interaction.id; } if (event.event_id) lastEventId = event.event_id; if (event.type === 'step.delta') { if (event.delta.type === 'text') { process.stdout.write(event.delta.text); } else if (event.delta.type === 'thought') { console.log(`Thought: ${event.delta.text}`); } } else if (['interaction.completed', 'interaction.error'].includes(event.type)) { isComplete = true; } } } const stream = await client.interactions.create({ input: 'Research the history of Google TPUs.', agent: 'deep-research-preview-04-2026', background: true, stream: true, agent_config: { type: 'deep-research', thinking_summaries: 'auto' }, }); await processStream(stream); // Reconnect if the connection drops while (!isComplete && interactionId) { const status = await client.interactions.get(interactionId); if (status.status !== 'in_progress') break; const resumeStream = await client.interactions.get(interactionId, { stream: true, last_event_id: lastEventId, }); await processStream(resumeStream); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`# 1. Start the stream (save the INTERACTION_ID from the interaction.start event # and the last \"event_id\" you receive)\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"input\": \"Research the history of Google TPUs.\", \"agent\": \"deep-research-preview-04-2026\", \"background\": true, \"stream\": true, \"agent_config\": { \"type\": \"deep-research\", \"thinking_summaries\": \"auto\" } }' # 2. If the connection drops, reconnect with your saved IDs\ncurl -X GET \"https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID?stream=true&last_event_id=LAST_EVENT_ID\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\"` Follow-up questions and interactions You can continue the conversation after the agent returns the final report by\nusing the `previous_interaction_id`. This lets you to ask for clarification,\nsummarization or elaboration on specific sections of the research without\nrestarting the entire task. Python`import time from google import genai client = genai.Client() interaction = client.interactions.create( input=\"Can you elaborate on the second point in the report?\", model=\"gemini-3.1-pro-preview\", previous_interaction_id=\"COMPLETED_INTERACTION_ID\" ) print(interaction.steps[-1].content[0].text)` JavaScript`const interaction = await client.interactions.create({ input: 'Can you elaborate on the second point in the report?', model: 'gemini-3.1-pro-preview', previous_interaction_id: 'COMPLETED_INTERACTION_ID' }); console.log(interaction.steps.at(-1).content[0].text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"input\": \"Can you elaborate on the second point in the report?\", \"model\": \"gemini-3.1-pro-preview\", \"previous_interaction_id\": \"COMPLETED_INTERACTION_ID\" }'` When to use Gemini Deep Research agent Deep Research is an **agent**, not just a model. It is best suited for workloads\nthat require an \"analyst-in-a-box\" approach rather than low-latency chat. Feature Standard Gemini Models Gemini Deep Research agent **Latency** Seconds Minutes (Async/Background) **Process** Generate -> Output Plan -> Search -> Read -> Iterate -> Output **Output** Conversational text, code, short summaries Detailed reports, long-form analysis, comparative tables **Best For** Chatbots, extraction, creative writing Market analysis, due diligence, literature reviews, competitive landscaping Agent configuration Deep Research uses the `agent_config` parameter to control behavior.\nPass it as a dictionary with the following fields: Field Type Default Description `type` `string` Required Must be `\"deep-research\"`. `thinking_summaries` `string` `\"none\"` Set to `\"auto\"` to receive intermediate reasoning steps during streaming. Set to `\"none\"` to disable. `visualization` `string` `\"auto\"` Set to `\"auto\"` to enable agent-generated charts and images. Set to `\"off\"` to disable. `collaborative_planning` `boolean` `false` Set to `true` to enable multi-turn plan review before research begins. Python`agent_config = { \"type\": \"deep-research\", \"thinking_summaries\": \"auto\", \"visualization\": \"auto\", \"collaborative_planning\": False, } interaction = client.interactions.create( agent=\"deep-research-preview-04-2026\", input=\"Research the competitive landscape of cloud GPUs.\", agent_config=agent_config, background=True, )` JavaScript`const interaction = await client.interactions.create({ agent: 'deep-research-preview-04-2026', input: 'Research the competitive landscape of cloud GPUs.', agent_config: { type: 'deep-research', thinking_summaries: 'auto', visualization: 'auto', collaborative_planning: false, }, background: true, });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.AgentOption; import com.google.genai.gaos.models.interactions.CreateAgentInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateAgentInteraction params = CreateAgentInteraction.builder() .agent(AgentOption.of(\"deep-research-pro-preview-12-2025\")) .input(InteractionsInput.of(\"I want to learn more about the history of Hadrian's Wall\")) .background(true) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(\"Deep Research started. Interaction ID: \" + interaction.id().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"input\": \"Research the competitive landscape of cloud GPUs.\", \"agent\": \"deep-research-preview-04-2026\", \"agent_config\": { \"type\": \"deep-research\", \"thinking_summaries\": \"auto\", \"visualization\": \"auto\", \"collaborative_planning\": false }, \"background\": true }'` Availability and pricing You can access the Gemini Deep Research agent using the Interactions API in Google AI Studio and the Gemini API. Pricing follows a [pay-as-you-go model](/gemini-api/docs/pricing#pricing-for-agents) based on the underlying Gemini models and the specific tools the agent utilizes. Unlike standard chat requests, where a request leads to one output, a Deep Research task is an agentic workflow. A single request triggers an autonomous loop of planning, searching, reading, and reasoning. Estimated costs Costs vary based on the depth of research required. The agent autonomously determines how much reading and searching is necessary to answer your prompt. **Deep Research** (`deep-research-preview-04-2026`): For a typical query requiring moderate analysis, the agent might use ~80 search queries, ~250k input tokens (~50-70% cached), and ~60k output tokens.\n **Estimated total:** ~$1.00 – $3.00 per task **Deep Research Max** (`deep-research-max-preview-04-2026`): For deep competitive landscape analysis or extensive due diligence, the agent might use up to ~160 search queries, ~900k input tokens (~50-70% cached), and ~80k output tokens.\n **Estimated total:** ~$3.00 – $7.00 per task Safety considerations Giving an agent access to the web and your private files requires careful\nconsideration of safety risks. **Prompt injection using files:** The agent reads the contents of the files\nyou provide. Ensure that uploaded documents (PDFs, text files) come from\ntrusted sources. A malicious file could contain hidden text designed to\nmanipulate the agent's output. **Web content risks:** The agent searches the public web. While we implement\nrobust safety filters, there is a risk that the agent may encounter and\nprocess malicious web pages. We recommend reviewing the `citations` provided\nin the response to verify the sources. **Exfiltration:** Be cautious when asking the agent to summarize sensitive\ninternal data if you are also allowing it to browse the web. Best practices **Prompt for unknowns:** Instruct the agent on how to handle missing data.\nFor example, add *\"If specific figures for 2025 are not available,\nexplicitly state they are projections or unavailable rather than\nestimating\"* to your prompt. **Provide context:** Ground the agent's research by providing background\ninformation or constraints directly in the input prompt. **Use collaborative planning:** For complex queries, enable collaborative\nplanning to review and refine the research plan before execution. **Multimodal inputs:** Deep Research agent supports multi-modal inputs.\nUse cautiously, as this increases costs and risks context window overflow. Limitations **Custom tools:** You cannot currently provide custom Function Calling tools\nbut you can use remote MCP (Model Context Protocol) servers with the Deep Research agent. **Structured output:** The Deep Research agent currently\ndoesn't support structured outputs. **Max research time:** The Deep Research agent has a maximum research time\nof 60 minutes. Most tasks should complete within 20 minutes. **Store requirement:** Agent execution using `background=True` requires\n`store=True`. **Google search:** [Google\nSearch](/gemini-api/docs/google-search) is enabled by\ndefault and [specific\nrestrictions](/gemini-api/terms#use-restrictions2)\napply to the grounded results. What's next Learn more about the [Interactions API](/gemini-api/docs/interactions-overview). Learn how to use your own data using the [File Search](/gemini-api/docs/file-search)\ntool. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-08-26 UTC.", "znaku_textu": 48887, "slov": 5232, "odkazu": 130, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:46", "sha256": "632ba3ec22ab3f6c2d4cff0e04d5ca5d6461badad6d1784f53e2b8855cd30f3f", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/deprecations", "titulek": "Gemini deprecations | Gemini API | Google AI for Developers", "h1": "Gemini deprecations", "popis": "Keep track of deprecation schedules for Gemini models and features", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/deprecations", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini deprecations  |  Gemini API  |  Google AI for Developers", "og:description": "Keep track of deprecation schedules for Gemini models and features", "og:url": "https://ai.google.dev/gemini-api/docs/deprecations", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Gemini deprecations"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Gemini deprecations", "item": "https://ai.google.dev/gemini-api/docs/deprecations"}]}], "drobecky": ["Gemini API", "Gemini deprecations"], "osnova": [{"uroven": 1, "text": "Gemini deprecations"}, {"uroven": 2, "text": "Gemini 3 models"}, {"uroven": 2, "text": "Gemini 2.5 Pro models"}, {"uroven": 2, "text": "Gemini 2.5 Flash models"}, {"uroven": 2, "text": "Gemini 2.0 models"}, {"uroven": 2, "text": "Live API models"}, {"uroven": 2, "text": "Audio models"}, {"uroven": 2, "text": "Embedding models"}, {"uroven": 2, "text": "Imagen models"}, {"uroven": 2, "text": "Veo models"}, {"uroven": 2, "text": "Gemini Omni Flash models"}, {"uroven": 2, "text": "Lyria models"}, {"uroven": 2, "text": "Robotics models"}], "markdown": "Gemini deprecations This page lists the known deprecation schedules for [stable (GA)](/gemini-api/docs/models#stable) and [preview](/gemini-api/docs/models#preview)\nmodels in the Gemini API. A \"**deprecation**\" is the announcement that we\nno longer provide support for a model, and that it will be \"**shut down**\" in\nthe near future. Once a model is \"**shutdown**\", it is completely\nturned off, and the endpoint is no longer available. Deprecation announcements are made on the\n[Release notes](/gemini-api/docs/changelog) page, and the announced earliest\nshutdown dates are tracked on this page.\nAlready-shutdown models are indicated with gray backgrounds. Gemini 3 models **Model** **Release date** **Shutdown date** **Recommended replacement** `gemini-3.8-flash` September 2, 2026 No shutdown date announced `gemini-3.7-flash` August 13, 2026 No shutdown date announced `gemini-3.6-flash` July 21, 2026 No shutdown date announced `gemini-3.5-flash-lite` July 21, 2026 No shutdown date announced `gemini-3.5-flash` May 19, 2026 No shutdown date announced `gemini-3.1-flash-image` May 28, 2026 No shutdown date announced `gemini-3-pro-image` May 28, 2026 No shutdown date announced `gemini-3.1-flash-lite` May 7, 2026 May 7, 2027 `gemini-3.5-flash-lite` Preview models `gemini-3.1-flash-image-preview` February 26, 2026 June 25, 2026 `gemini-3.1-flash-image` `gemini-3.1-pro-preview` February 19, 2026 No shutdown date announced `gemini-3-pro-image-preview` November 20, 2025 June 25, 2026 `gemini-3-pro-image` `gemini-3-flash-preview` December 17, 2025 No shutdown date announced `gemini-3.6-flash` `gemini-3-pro-preview` November 18, 2025 March 9, 2026 `gemini-3.1-pro-preview` `gemini-3.1-flash-lite-preview` March 3, 2026 May 25, 2026 `gemini-3.1-flash-lite` Gemini 2.5 Pro models **Model** **Release date** **Shutdown date** **Recommended replacement** `gemini-2.5-pro` June 17, 2025 No shutdown date announced Preview models `gemini-2.5-pro-preview-03-25` March 3, 2025 December 2, 2025 `gemini-3.1-pro-preview` `gemini-2.5-pro-preview-05-06` May 6, 2025 December 2, 2025 `gemini-3.1-pro-preview` `gemini-2.5-pro-preview-06-05` June 5, 2025 December 2, 2025 `gemini-3.1-pro-preview` Gemini 2.5 Flash models **Model** **Release date** **Shutdown date** **Recommended replacement** `gemini-2.5-flash` June 17, 2025 No shutdown date announced `gemini-2.5-flash-image` October 2, 2025 October 2, 2026 `gemini-3.1-flash-image-preview` `gemini-2.5-flash-lite` July 22, 2025 No shutdown date announced Preview models `gemini-2.5-flash-lite-preview-09-2025` September 25, 2025 March 31, 2026 `gemini-3.1-flash-lite` `gemini-2.5-flash-preview-05-20` May 20, 2025 November 18, 2025 `gemini-3.6-flash` `gemini-2.5-flash-image-preview` May 7, 2025 January 15, 2026 `gemini-2.5-flash-image` `gemini-2.5-flash-preview-09-25` September 25, 2025 February 17, 2026 `gemini-3.6-flash` Gemini 2.0 models **Model** **Release date** **Shutdown date** **Recommended replacement** `gemini-2.0-flash` February 5, 2025 June 1, 2026 `gemini-3.6-flash` `gemini-2.0-flash-001` February 5, 2025 June 1, 2026 `gemini-3.6-flash` `gemini-2.0-flash-lite` February 25, 2025 June 1, 2026 `gemini-3.1-flash-lite` `gemini-2.0-flash-lite-001` February 25, 2025 June 1, 2026 `gemini-3.1-flash-lite` Preview models `gemini-2.0-flash-preview-image-generation` May 7, 2025 November 14, 2025 `gemini-2.5-flash-image` `gemini-2.0-flash-lite-preview` February 5, 2025 December 9, 2025 `gemini-2.5-flash-lite` `gemini-2.0-flash-lite-preview-02-05` February 5, 2025 December 9, 2025 `gemini-2.5-flash-lite` Live API models **Model** **Release date** **Shutdown date** **Recommended replacement** `gemini-3.5-transcribe-live` August 2026 No shutdown date announced `gemini-2.0-flash-live-001` April 9, 2025 December 9, 2025 `gemini-3.1-flash-live-preview` Preview models `gemini-3.5-live-translate-preview` June 2026 No shutdown date announced `gemini-3.1-flash-live-preview` March 11, 2026 No shutdown date announced `gemini-2.5-flash-native-audio-preview-12-2025` December 12, 2025 No shutdown date announced `gemini-3.1-flash-live-preview` `gemini-live-2.5-flash-preview` June 17, 2025 December 9, 2025 `gemini-3.1-flash-live-preview` Audio models **Model** **Release date** **Shutdown date** **Recommended replacement** `gemini-3.5-transcribe` August 2026 No shutdown date announced Preview models `gemini-3.1-flash-tts-preview` April 13, 2026 No shutdown date announced `gemini-2.5-flash-preview-tts` May 20, 2025 No shutdown date announced `gemini-3.1-flash-tts-preview` `gemini-2.5-pro-preview-tts` May 20, 2025 No shutdown date announced `gemini-3.1-flash-tts-preview` Embedding models **Model** **Release date** **Shutdown date** **Recommended replacement** `gemini-embedding-2` April 22, 2026 No shutdown date announced `gemini-embedding-001` July 14, 2025 May 14, 2028 `gemini-embedding-2` `text-embedding-004` April 9, 2024 January 14, 2026 `gemini-embedding-2` Preview models `embedding-2-preview` March 10, 2026 August 10, 2026 `gemini-embedding-2` `embedding-001` April 9, 2024 October 30, 2025 `gemini-embedding-2` `embedding-gecko-001` October 30, 2025 `gemini-embedding-2` `gemini-embedding-exp` October 30, 2025 `gemini-embedding-2` `gemini-embedding-exp-03-07` October 30, 2025 `gemini-embedding-2` Imagen models **Model** **Release date** **Shutdown date** **Recommended replacement** `imagen-4.0-generate-001` June 24, 2025 August 17, 2026 `gemini-3.1-flash-image` `imagen-4.0-ultra-generate-001` June 24, 2025 August 17, 2026 `gemini-3.1-flash-image` `imagen-4.0-fast-generate-001` June 24, 2025 August 17, 2026 `gemini-3.1-flash-image` `imagen-3.0-generate-002` February 6, 2025 November 10, 2025 `imagen-4.0-generate-001` Preview models `imagen-4.0-generate-preview-06-06` June 24, 2025 February 17, 2026 `imagen-4.0-generate-001` `imagen-4.0-ultra-generate-preview-06-06` June 24, 2025 February 17, 2026 `imagen-4.0-ultra-generate-001` Veo models **Model** **Release date** **Shutdown date** **Recommended replacement** `veo-3.0-generate-001` September 9, 2025 June 30, 2026 `veo-3.1-generate-preview`\nor the GA models on the [Gemini Enterprise Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/veo/3-1-generate) `veo-3.0-fast-generate-001` September 9, 2025 June 30, 2026 `veo-3.1-fast-generate-preview`\nor the GA models on the [Gemini Enterprise Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/veo/3-1-generate) `veo-2.0-generate-001` April 9, 2025 June 30, 2026 `veo-3.1-generate-preview`\nor the GA models on the [Gemini Enterprise Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/veo/3-1-generate) Preview models `veo-3.1-lite-generate-preview` March 31, 2026 No shutdown date announced `veo-3.1-generate-preview` October 15, 2025 No shutdown date announced `veo-3.1-fast-generate-preview` October 15, 2025 No shutdown date announced `veo-3.0-generate-preview` July 31, 2025 November 12, 2025 `veo-3.1-generate-preview` `veo-3.0-fast-generate-preview` July 31, 2025 November 12, 2025 `veo-3.1-fast-generate-preview` Gemini Omni Flash models **Model** **Release date** **Shutdown date** **Recommended replacement** `gemini-omni-1.1-flash` August 27, 2026 No shutdown date announced Deprecated models `gemini-omni-flash-preview` June 30, 2026 September 30, 2026 `gemini-omni-1.1-flash` Lyria models **Model** **Release date** **Shutdown date** **Recommended replacement** `lyria-3.5` September 3, 2026 No shutdown date announced `lyria-3-clip-preview` March 25, 2026 No shutdown date announced `lyria-3-pro-preview` March 25, 2026 No shutdown date announced `lyria-3.5` `lyria-realtime-exp` May 20, 2025 No shutdown date announced Robotics models **Model** **Release date** **Shutdown date** **Recommended replacement** Preview models `gemini-robotics-er-1.6-preview` April 14, 2026 August 31, 2026 gemini-robotics-er-2-preview `gemini-robotics-er-1.5-preview` September 25, 2025 April 30, 2026 `gemini-robotics-er-1.6-preview` Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-05 UTC.", "znaku_textu": 8056, "slov": 1294, "odkazu": 130, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 20:13:14", "sha256": "6b10f48661f093a205b1ccf0dd9b993099ea0aa8025a6f7820bc18824ee106df", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/veo/3-1-generate", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/document-processing", "titulek": "Document understanding | Gemini API | Google AI for Developers", "h1": "Document understanding", "popis": "Learn how to use the Gemini API to process documents like PDFs", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/document-processing", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Document understanding  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to use the Gemini API to process documents like PDFs", "og:url": "https://ai.google.dev/gemini-api/docs/document-processing", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Document understanding"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Document understanding", "item": "https://ai.google.dev/gemini-api/docs/document-processing"}]}], "drobecky": ["Gemini API", "Document understanding"], "osnova": [{"uroven": 1, "text": "Document understanding"}, {"uroven": 2, "text": "Passing PDF data inline"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Uploading PDFs using the Files API"}, {"uroven": 3, "text": "Large PDFs from URLs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Large PDFs stored locally"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Passing multiple PDFs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Technical details"}, {"uroven": 3, "text": "Gemini 3 models"}, {"uroven": 3, "text": "Document types"}, {"uroven": 3, "text": "Best practices"}, {"uroven": 2, "text": "What's next"}], "markdown": "Document understanding Gemini models can process documents in PDF format, using native\nvision to understand entire document contexts. This goes beyond\njust text extraction, allowing Gemini to: Analyze and interpret content, including text, images, diagrams,\ncharts, and tables, even in long documents up to 1000 pages. Extract information into [structured output](/gemini-api/docs/structured-output) formats. Summarize and answer questions based on both the visual and textual elements\nin a document. Transcribe document content (e.g. to HTML), preserving layouts and\nformatting, for use in downstream applications. You can also pass non-PDF documents in the same way but Gemini will see them\nas normal text which will eliminate context like charts or formatting. Passing PDF data inline You can pass PDF data inline in the request. This is best\nsuited for smaller documents or temporary processing where you don't need to\nreference the file in subsequent requests. We recommend using the\n[Files API](/gemini-api/docs/document-processing#large-pdfs)\nfor larger documents that you need to refer to in multi-turn interactions to\nimprove request latency and reduce bandwidth usage. The following example shows you how to pass PDF data inline: Python`from google import genai import base64 client = genai.Client() with open('path/to/document.pdf', 'rb') as f: pdf_bytes = f.read() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ { \"type\": \"document\", \"data\": base64.b64encode(pdf_bytes).decode('utf-8'), \"mime_type\": \"application/pdf\" }, {\"type\": \"text\", \"text\": \"Summarize this document\"} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const ai = new GoogleGenAI({}); async function main() { const pdfData = fs.readFileSync(\"path/to/document.pdf\", { encoding: \"base64\" }); const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: \"Summarize this document\" }, { type: \"document\", data: pdfData, mime_type: \"application/pdf\" } ] }); console.log(interaction.output_text); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`PDF_PATH=\"path/to/document.pdf\" if [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then B64FLAGS=\"--input\" else B64FLAGS=\"-w0\" fi\n\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ { \"type\": \"document\", \"data\": \"'$(base64 $B64FLAGS $PDF_PATH)'\", \"mime_type\": \"application/pdf\" }, {\"type\": \"text\", \"text\": \"Summarize this document\"} ] }'` You can also upload a local PDF file for processing: Python`from google import genai client = genai.Client() uploaded_file = client.files.upload(file=\"file.pdf\") interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"document\", \"uri\": uploaded_file.uri, \"mime_type\": uploaded_file.mime_type}, {\"type\": \"text\", \"text\": \"Summarize this document\"} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const uploadedFile = await ai.files.upload({ file: \"file.pdf\", config: { mime_type: \"application/pdf\" } }); const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: \"Summarize this document\" }, { type: \"document\", uri: uploadedFile.uri, mime_type: uploadedFile.mime_type } ] }); console.log(interaction.output_text); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`PDF_PATH=\"file.pdf\" NUM_BYTES=$(wc -c < \"${PDF_PATH}\") DISPLAY_NAME=\"file.pdf\" tmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: application/pdf\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${PDF_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq -r \".file.uri\" file_info.json) echo file_uri=$file_uri # Now create an interaction using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"document\", \"uri\": \"'$file_uri'\", \"mime_type\": \"application/pdf\"}, {\"type\": \"text\", \"text\": \"Summarize this document\"} ] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq -r \".steps[-1].content[0].text\" response.json` Uploading PDFs using the Files API We recommend you use Files API for larger files or when you intend to reuse a\ndocument across multiple requests. This improves request latency and reduces\nbandwidth usage by decoupling the file upload from the model requests. Large PDFs from URLs Use the File API to simplify uploading and processing large PDF files from URLs: Python`from google import genai import io import httpx client = genai.Client() long_context_pdf_path = \"https://arxiv.org/pdf/2312.11805\" doc_io = io.BytesIO(httpx.get(long_context_pdf_path).content) sample_doc = client.files.upload( file=doc_io, config=dict( mime_type='application/pdf') ) prompt = \"Summarize this document\" interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"document\", \"uri\": sample_doc.uri, \"mime_type\": sample_doc.mime_type}, {\"type\": \"text\", \"text\": prompt} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const pdfBuffer = await fetch(\"https://arxiv.org/pdf/2312.11805\") .then((response) => response.arrayBuffer()); const fileBlob = new Blob([pdfBuffer], { type: 'application/pdf' }); const file = await ai.files.upload({ file: fileBlob, config: { displayName: 'A17_FlightPlan.pdf', }, }); let getFile = await ai.files.get({ name: file.name }); while (getFile.state === 'PROCESSING') { getFile = await ai.files.get({ name: file.name }); console.log(`current file status: ${getFile.state}`); console.log('File is still processing, retrying in 5 seconds'); await new Promise((resolve) => { setTimeout(resolve, 5000); }); } if (file.state === 'FAILED') { throw new Error('File processing failed.'); } const interaction = await ai.interactions.create({ model: 'gemini-3.8-flash', input: [ { type: \"document\", uri: file.uri, mime_type: file.mime_type }, { type: \"text\", text: \"Summarize this document\" } ], }); console.log(interaction.output_text); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`PDF_PATH=\"https://arxiv.org/pdf/2312.11805\" DISPLAY_NAME=\"Gemini_paper\" PROMPT=\"Summarize this document\" # Download the PDF from the provided URL\nwget -O \"${DISPLAY_NAME}.pdf\" \"${PDF_PATH}\" MIME_TYPE=$(file -b --mime-type \"${DISPLAY_NAME}.pdf\") NUM_BYTES=$(wc -c < \"${DISPLAY_NAME}.pdf\") echo \"MIME_TYPE: ${MIME_TYPE}\" echo \"NUM_BYTES: ${NUM_BYTES}\" tmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${DISPLAY_NAME}.pdf\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq -r \".file.uri\" file_info.json) echo \"file_uri: ${file_uri}\" # Create payload JSON file for safety\ncat << EOF > payload.json\n{ \"model\": \"gemini-3.8-flash\",\n \"input\": [ {\"type\": \"text\", \"text\": \"${PROMPT}\"},\n {\"type\": \"document\", \"uri\": \"${file_uri}\", \"mime_type\": \"application/pdf\"} ] }\nEOF\n\n# Now create an interaction using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d @payload.json 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".steps[-1].content[0].text\" response.json\n\n# Clean up\nrm \"${DISPLAY_NAME}.pdf\"\nrm payload.json` Large PDFs stored locally Python`from google import genai import pathlib client = genai.Client() file_path = pathlib.Path('large_file.pdf') sample_file = client.files.upload( file=file_path, ) interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"document\", \"uri\": sample_file.uri, \"mime_type\": sample_file.mime_type}, {\"type\": \"text\", \"text\": \"Summarize this document\"} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const file = await ai.files.upload({ file: 'large_file.pdf', config: { displayName: 'A17_FlightPlan.pdf', }, }); let getFile = await ai.files.get({ name: file.name }); while (getFile.state === 'PROCESSING') { getFile = await ai.files.get({ name: file.name }); console.log(`current file status: ${getFile.state}`); console.log('File is still processing, retrying in 5 seconds'); await new Promise((resolve) => { setTimeout(resolve, 5000); }); } if (file.state === 'FAILED') { throw new Error('File processing failed.'); } const interaction = await ai.interactions.create({ model: 'gemini-3.8-flash', input: [ { type: \"document\", uri: file.uri, mime_type: file.mime_type }, { type: \"text\", text: \"Summarize this document\" } ], }); console.log(interaction.output_text); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`PDF_PATH=\"large_file.pdf\" NUM_BYTES=$(wc -c < \"${PDF_PATH}\") DISPLAY_NAME=TEXT\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: application/pdf\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${PDF_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq -r \".file.uri\" file_info.json) echo file_uri=$file_uri # Now create an interaction using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"document\", \"uri\": \"'$file_uri'\", \"mime_type\": \"application/pdf\"}, {\"type\": \"text\", \"text\": \"Can you add a few more lines to this poem?\"} ] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq -r \".steps[-1].content[0].text\" response.json` You can verify the API successfully stored the uploaded file and get its\nmetadata by calling [`files.get`](/api/rest/v1beta/files/get). Only the `name`\n(and by extension, the `uri`) are unique. Python`from google import genai import pathlib client = genai.Client() fpath = pathlib.Path('example.pdf') fpath.write_text('hello') file = client.files.upload(file='example.pdf') file_info = client.files.get(name=file.name) print(file_info.model_dump_json(indent=4))` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const ai = new GoogleGenAI({}); async function main() { fs.writeFileSync(\"example.pdf\", \"hello\"); const file = await ai.files.upload({ file: \"example.pdf\", config: { mime_type: \"application/pdf\" } }); const fileInfo = await ai.files.get({ name: file.name }); console.log(fileInfo); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`name=$(jq -r \".file.name\" file_info.json) # Get the file of interest to check state\ncurl \"https://generativelanguage.googleapis.com/v1beta/$name?key=$GEMINI_API_KEY\" > file_info.json\n# Print some information about the file you got name=$(jq -r \".name\" file_info.json) echo name=$name file_uri=$(jq -r \".uri\" file_info.json) echo file_uri=$file_uri` Passing multiple PDFs The Gemini API is capable of processing multiple PDF documents (up to 1000 pages)\nin a single request, as long as the combined size of the documents and the text\nprompt stays within the model's context window. Python`from google import genai import io import httpx client = genai.Client() doc_url_1 = \"https://arxiv.org/pdf/2312.11805\" doc_url_2 = \"https://arxiv.org/pdf/2403.05530\" doc_data_1 = io.BytesIO(httpx.get(doc_url_1).content) doc_data_2 = io.BytesIO(httpx.get(doc_url_2).content) sample_pdf_1 = client.files.upload( file=doc_data_1, config=dict(mime_type='application/pdf') ) sample_pdf_2 = client.files.upload( file=doc_data_2, config=dict(mime_type='application/pdf') ) prompt = \"What is the difference between each of the main benchmarks between these two papers? Output these in a table.\" interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"document\", \"uri\": sample_pdf_1.uri, \"mime_type\": sample_pdf_1.mime_type}, {\"type\": \"document\", \"uri\": sample_pdf_2.uri, \"mime_type\": sample_pdf_2.mime_type}, {\"type\": \"text\", \"text\": prompt} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function uploadRemotePDF(url, displayName) { const pdfBuffer = await fetch(url) .then((response) => response.arrayBuffer()); const fileBlob = new Blob([pdfBuffer], { type: 'application/pdf' }); const file = await ai.files.upload({ file: fileBlob, config: { displayName: displayName, }, }); let getFile = await ai.files.get({ name: file.name }); while (getFile.state === 'PROCESSING') { getFile = await ai.files.get({ name: file.name }); console.log(`current file status: ${getFile.state}`); console.log('File is still processing, retrying in 5 seconds'); await new Promise((resolve) => { setTimeout(resolve, 5000); }); } if (file.state === 'FAILED') { throw new Error('File processing failed.'); } return file; } async function main() { const file1 = await uploadRemotePDF(\"https://arxiv.org/pdf/2312.11805\", \"PDF 1\"); const file2 = await uploadRemotePDF(\"https://arxiv.org/pdf/2403.05530\", \"PDF 2\"); const interaction = await ai.interactions.create({ model: 'gemini-3.8-flash', input: [ { type: \"document\", uri: file1.uri, mime_type: file1.mime_type }, { type: \"document\", uri: file2.uri, mime_type: file2.mime_type }, { type: \"text\", text: \"What is the difference between each of the main benchmarks between these two papers? Output these in a table.\" } ], }); console.log(interaction.output_text); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`DOC_URL_1=\"https://arxiv.org/pdf/2312.11805\" DOC_URL_2=\"https://arxiv.org/pdf/2403.05530\" DISPLAY_NAME_1=\"Gemini_paper\" DISPLAY_NAME_2=\"Gemini_1.5_paper\" PROMPT=\"What is the difference between each of the main benchmarks between these two papers? Output these in a table.\" # Function to download and upload a PDF\nupload_pdf() { local doc_url=\"$1\" local display_name=\"$2\" echo \"Downloading ${display_name} from ${doc_url}...\" >&2 # Download the PDF wget -O \"${display_name}.pdf\" \"${doc_url}\" 2> /dev/null\n\n local MIME_TYPE=$(file -b --mime-type \"${display_name}.pdf\") local NUM_BYTES=$(wc -c < \"${display_name}.pdf\") echo \"MIME_TYPE: ${MIME_TYPE}\" >&2 echo \"NUM_BYTES: ${NUM_BYTES}\" >&2 local tmp_header_file=\"upload-header-${display_name}.tmp\" # Initial resumable request # Using GEMINI_API_KEY instead of GOOGLE_API_KEY curl \"https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}\" \\ -D \"${tmp_header_file}\" \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${display_name}'}}\" 2> /dev/null\n\n local upload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\") rm \"${tmp_header_file}\" echo \"Upload URL for ${display_name}: ${upload_url}\" >&2 # Upload the PDF curl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${display_name}.pdf\" 2> /dev/null > \"file_info_${display_name}.json\" local file_uri=$(jq -r \".file.uri\" \"file_info_${display_name}.json\") echo \"file_uri for ${display_name}: ${file_uri}\" >&2 # Clean up the downloaded PDF rm \"${display_name}.pdf\" echo \"${file_uri}\" } # Upload the first PDF file_uri_1=$(upload_pdf \"${DOC_URL_1}\" \"${DISPLAY_NAME_1}\") # Upload the second PDF file_uri_2=$(upload_pdf \"${DOC_URL_2}\" \"${DISPLAY_NAME_2}\") # Create payload JSON file for safety\ncat << EOF > payload_multi.json\n{ \"model\": \"gemini-3.8-flash\",\n \"input\": [ {\"type\": \"document\", \"uri\": \"${file_uri_1}\", \"mime_type\": \"application/pdf\"},\n {\"type\": \"document\", \"uri\": \"${file_uri_2}\", \"mime_type\": \"application/pdf\"},\n {\"type\": \"text\", \"text\": \"${PROMPT}\"} ] }\nEOF\n\n# Now create an interaction using both files # Using GEMINI_API_KEY instead of GOOGLE_API_KEY\ncurl \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d @payload_multi.json 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".steps[-1].content[0].text\" response.json\n\n# Clean up\nrm payload_multi.json\nrm \"file_info_${DISPLAY_NAME_1}.json\"\nrm \"file_info_${DISPLAY_NAME_2}.json\"` Technical details Gemini supports PDF files up to 50MB or 1000 pages. This limit applies\nto both inline data and Files API uploads. Each document page is equivalent to 258\ntokens. While there are no specific limits to the number of pixels in a document besides\nthe model's [context window](/gemini-api/docs/long-context), larger pages are\nscaled down to a maximum resolution of 3072 x 3072 while preserving their original\naspect ratio, while smaller pages are scaled up to 768 x 768 pixels. There is no\ncost reduction for pages at lower sizes, other than bandwidth, or performance\nimprovement for pages at higher resolution. Gemini 3 models Gemini 3 introduces granular control over multimodal vision processing with the\n`media_resolution` parameter. You can now set the resolution to low, medium, or\nhigh per individual media part. With this addition, the processing of PDF\ndocuments has been updated: **Native text inclusion:** Text natively embedded in the PDF is extracted\nand provided to the model. **Billing & token reporting:** You are **not charged** for tokens originating from the extracted\n**native text** in PDFs. In the `usage_metadata` section of the API response, tokens generated\nfrom processing PDF pages (as images) are now counted under the `IMAGE`\nmodality, not a separate `DOCUMENT` modality as in some earlier\nversions. For more details about the media resolution parameter, see the\n[Media resolution](/gemini-api/docs/interactions/media-resolution) guide. Document types Technically, you can pass other MIME types for document understanding, like\nTXT, Markdown, HTML, XML, etc. However, document vision ***only meaningfully\nunderstands PDFs***. Other types will be extracted as pure text, and the model\nwon't be able to interpret what we see in the rendering of those files. Any\nfile-type specifics like charts, diagrams, HTML tags, Markdown formatting, etc.,\nwill be lost. To learn about other file input methods, see the\n[File input methods](/gemini-api/docs/file-input-methods) guide. Best practices For best results: Rotate pages to the correct orientation before uploading. Avoid blurry pages. If using a single page, place the text prompt after the page. What's next To learn more, see the following resources: [File prompting strategies](/gemini-api/docs/files#prompt-guide): The\nGemini API supports prompting with text, image, audio, and video data, also\nknown as multimodal prompting. [System instructions](/gemini-api/docs/text-generation#system-instructions):\nSystem instructions let you steer the behavior of the model based on your\nspecific needs and use cases. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 29366, "slov": 3061, "odkazu": 132, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:17:05", "sha256": "40aae692237db2f5c4e8c290443958338e1bad944039800e48803203d28a9904", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/embeddings", "titulek": "Embeddings | Gemini API | Google AI for Developers", "h1": "Embeddings", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/embeddings", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Embeddings  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/embeddings", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Embeddings"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Embeddings", "item": "https://ai.google.dev/gemini-api/docs/embeddings"}]}], "drobecky": ["Gemini API", "Embeddings"], "osnova": [{"uroven": 1, "text": "Embeddings"}, {"uroven": 2, "text": "Generating embeddings"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Specify task type to improve performance"}, {"uroven": 3, "text": "Task types with Embeddings 2"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Task types with Embeddings 1"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 4, "text": "Supported task types"}, {"uroven": 2, "text": "Controlling embedding size"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Ensuring quality for smaller dimensions"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Multimodal embeddings"}, {"uroven": 3, "text": "Supported modalities and limits"}, {"uroven": 3, "text": "Embedding images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Embedding aggregation"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Embedding audio"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Embedding video"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Embedding documents"}, {"uroven": 4, "text": "How the model processes PDFs"}, {"uroven": 4, "text": "PDF limits"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Use cases"}, {"uroven": 2, "text": "Storing embeddings"}, {"uroven": 2, "text": "Model versions"}, {"uroven": 3, "text": "Gemini Embedding 2"}, {"uroven": 3, "text": "Gemini Embedding"}, {"uroven": 2, "text": "Migration from gemini-embedding-001"}, {"uroven": 2, "text": "Batch embeddings"}, {"uroven": 2, "text": "Responsible use notice"}, {"uroven": 2, "text": "Start building with embeddings"}], "markdown": "Embeddings The Gemini API offers embedding models to generate embeddings for text, images,\nvideo, and other content. These resulting embeddings can then be used for tasks\nsuch as semantic search, classification, and clustering, providing more accurate,\ncontext-aware results than keyword-based approaches. The latest model, `gemini-embedding-2`, is the first multimodal\nembedding model in the Gemini API. It maps text, images,\nvideo, audio, and documents into a unified embedding space, enabling cross-modal\nsearch, classification, and clustering across over 100 languages. See the\nmultimodal embeddings section to learn more. For text-only\nuse cases, `gemini-embedding-001` remains available. Building Retrieval Augmented Generation (RAG) systems is a common use case for\nAI products. Embeddings play a key role in significantly enhancing model outputs\nwith improved factual accuracy, coherence, and contextual richness. If you prefer\nto use a managed RAG solution, we built the [File Search](/gemini-api/docs/file-search)\ntool which makes doing RAG easier to manage and more cost effective. Generating embeddings Use the `embedContent` method to generate text embeddings: Python`from google import genai client = genai.Client() result = client.models.embed_content( model=\"gemini-embedding-2\", contents=\"What is the meaning of life?\" ) print(result.embeddings)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; async function main() { const ai = new GoogleGenAI({}); const response = await ai.models.embedContent({ model: 'gemini-embedding-2', contents: 'What is the meaning of life?', }); console.log(response.embeddings); } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` Go`package main import ( \"context\" \"encoding/json\" \"fmt\" \"log\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } contents := []*genai.Content{ genai.NewContentFromText(\"What is the meaning of life?\", genai.RoleUser), } result, err := client.Models.EmbedContent(ctx, \"gemini-embedding-2\", contents, nil, ) if err != nil { log.Fatal(err) } embeddings, err := json.MarshalIndent(result.Embeddings, \"\", \" \") if err != nil { log.Fatal(err) } fmt.Println(string(embeddings)) }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2:embedContent\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"model\": \"models/gemini-embedding-2\", \"content\": { \"parts\": [{ \"text\": \"What is the meaning of life?\" }] } }'` Specify task type to improve performance You can use embeddings for a wide range of tasks from classification to document\nsearch. Specifying the right task type helps optimize the embeddings for the\nintended relationships, maximizing accuracy and efficiency. Task types with Embeddings 2 For text-only tasks with `gemini-embedding-2`, we strongly recommend you\nadd the task instruction in your prompt. This can be done by formatting the\nquery and the document with the correct task prefix. When generating a single embedding based on multimodal\ninput, we generally don't recommend prefixing the text\nportion of the input with a task instruction. In some cases it improves\nperformance, but in others it reduces performance. The following tables show examples of how to format queries and documents for\nsymmetric and asymmetric use cases using the `gemini-embedding-2` model. **Retrieval use cases (Asymmetric format)** In asymmetric use cases, add the task prefix to the query and apply\nthe document structure for the content you want to embed and retrieve. Use case Query structure Document structure Search query `task: search result | query: {content}` `title: {title} | text: {content}`\nIf there is no title, use `title: none`. Question answering `task: question answering | query: {content}` `title: {title} | text: {content}` Fact checking `task: fact checking | query: {content}` `title: {title} | text: {content}` Code retrieval `task: code retrieval | query: {content}` `title: {title} | text: {content}` **Example usage** Python`# Generate embedding for a task's query. Use your correct task here: def prepare_query(query): # return f\"task: question answering | query: {query}\" # return f\"task: fact checking | query: {query}\" # return f\"task: code retrieval | query: {query}\" return f\"task: search result | query: {query}\" # Generate embedding for document of an asymmetric retrieval task: def prepare_document(content, title=None): if title is None: title = \"none\" return f\"title: {title} | text: {content}\"` **Single-input use cases (Symmetric format)** In symmetric use cases, for the same task, use the same formatting\nfor the query and the document. Use case Input structure Classification `task: classification | query: {content}` Clustering `task: clustering | query: {content}` Semantic similarity `task: sentence similarity | query: {content}`\nDo not use this for search or retrieval. It is intended for semantic textual similarity. **Example usage** Python`# Generate embedding for query & document of your task. def prepare_query_and_document(content): # return f'task: clustering | query: {content}' # return f'task: sentence similarity | query: {content}' return f'task: classification | query: {content}'` It is important that the task is used consistently. E.g., if documents are\nembedded with `f'task: classification | query: {content}'`, the query should\nalso be embedded following this task format. Task types with Embeddings 1 For `gemini-embedding-001`, you can specify the `task_type` in the `embedContent`\nmethod. For a complete list of supported task types, see the Supported task types\ntable. The following example shows how you can use `SEMANTIC_SIMILARITY` to check how\nsimilar in meaning strings of texts are. Python`from google import genai from google.genai import types import pandas as pd from sklearn.metrics.pairwise import cosine_similarity client = genai.Client() texts = [ \"What is the meaning of life?\", \"What is the purpose of existence?\", \"How do I bake a cake?\", ] result = client.models.embed_content( model=\"gemini-embedding-001\", contents=texts, config=types.EmbedContentConfig(task_type=\"SEMANTIC_SIMILARITY\") ) # Create a 3x3 table to show the similarity matrix df = pd.DataFrame( cosine_similarity([e.values for e in result.embeddings]), index=texts, columns=texts, ) print(df)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; // npm i compute-cosine-similarity import * as cosineSimilarity from \"compute-cosine-similarity\"; async function main() { const ai = new GoogleGenAI({}); const texts = [ \"What is the meaning of life?\", \"What is the purpose of existence?\", \"How do I bake a cake?\", ]; const response = await ai.models.embedContent({ model: 'gemini-embedding-001', contents: texts, config: { taskType: 'SEMANTIC_SIMILARITY' }, }); const embeddings = response.embeddings.map(e => e.values); for (let i = 0; i < texts.length; i++) { for (let j = i + 1; j < texts.length; j++) { const text1 = texts[i]; const text2 = texts[j]; const similarity = cosineSimilarity(embeddings[i], embeddings[j]); console.log(`Similarity between '${text1}' and '${text2}': ${similarity.toFixed(4)}`); } } } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` Go`package main import ( \"context\" \"fmt\" \"log\" \"math\" \"google.golang.org/genai\" ) // cosineSimilarity calculates the similarity between two vectors. func cosineSimilarity(a, b []float32) (float64, error) { if len(a) != len(b) { return 0, fmt.Errorf(\"vectors must have the same length\") } var dotProduct, aMagnitude, bMagnitude float64 for i := 0; i < len(a); i++ { dotProduct += float64(a[i] * b[i]) aMagnitude += float64(a[i] * a[i]) bMagnitude += float64(b[i] * b[i]) } if aMagnitude == 0 || bMagnitude == 0 { return 0, nil } return dotProduct / (math.Sqrt(aMagnitude) * math.Sqrt(bMagnitude)), nil } func main() { ctx := context.Background() client, _ := genai.NewClient(ctx, nil) defer client.Close() texts := []string{ \"What is the meaning of life?\", \"What is the purpose of existence?\", \"How do I bake a cake?\", } var contents []*genai.Content for _, text := range texts { contents = append(contents, genai.NewContentFromText(text, genai.RoleUser)) } result, _ := client.Models.EmbedContent(ctx, \"gemini-embedding-001\", contents, &genai.EmbedContentRequest{TaskType: genai.TaskTypeSemanticSimilarity}, ) embeddings := result.Embeddings for i := 0; i < len(texts); i++ { for j := i + 1; j < len(texts); j++ { similarity, _ := cosineSimilarity(embeddings[i].Values, embeddings[j].Values) fmt.Printf(\"Similarity between '%s' and '%s': %.4f\\n\", texts[i], texts[j], similarity) } } }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"taskType\": \"SEMANTIC_SIMILARITY\", \"content\": { \"parts\": [ { \"text\": \"What is the meaning of life?\" }, { \"text\": \"How much wood would a woodchuck chuck?\" }, { \"text\": \"How does the brain work?\" } ] } }'` The code snippets will show how similar the different chunks of text are to one\nanother when run. Supported task types Supported task types for `gemini-embedding-001`: Task type Description Examples **SEMANTIC_SIMILARITY** Embeddings optimized to assess text similarity. Recommendation systems, duplicate detection **CLASSIFICATION** Embeddings optimized to classify texts according to preset labels. Sentiment analysis, spam detection **CLUSTERING** Embeddings optimized to cluster texts based on their similarities. Document organization, market research, anomaly detection **RETRIEVAL_DOCUMENT** Embeddings optimized for document search. Indexing articles, books, or web pages for search. **RETRIEVAL_QUERY** \n Embeddings optimized for general search queries.\n Use `RETRIEVAL_QUERY` for queries; `RETRIEVAL_DOCUMENT` for documents to be retrieved.\n Custom search **CODE_RETRIEVAL_QUERY** \n Embeddings optimized for retrieval of code blocks based on natural language queries.\n Use `CODE_RETRIEVAL_QUERY` for queries; `RETRIEVAL_DOCUMENT` for code blocks to be retrieved.\n Code suggestions and search **QUESTION_ANSWERING** \n Embeddings for questions in a question-answering system, optimized for finding documents that answer the question.\n Use `QUESTION_ANSWERING` for questions; `RETRIEVAL_DOCUMENT` for documents to be retrieved.\n Chatbox **FACT_VERIFICATION** \n Embeddings for statements that need to be verified, optimized for retrieving documents that contain evidence supporting or refuting the statement.\n Use `FACT_VERIFICATION` for the target text; `RETRIEVAL_DOCUMENT` for documents to be retrieved\n Automated fact-checking systems Controlling embedding size Both `gemini-embedding-001` and `gemini-embedding-2` are trained using\nthe Matryoshka Representation Learning (MRL) technique which teaches a model to\nlearn high-dimensional embeddings that have initial segments (or prefixes) which\nare also useful, simpler versions of the same data. Use the `output_dimensionality` parameter to control the size of\nthe output embedding vector. Selecting a smaller output dimensionality can save\nstorage space and increase computational efficiency for downstream applications,\nwhile sacrificing little in terms of quality. By default, both models output a\n3072-dimensional embedding, but you can truncate it to a smaller size without\nlosing quality to save storage space. We recommend using 768, 1536, or 3072\noutput dimensions. Python`from google import genai from google.genai import types client = genai.Client() result = client.models.embed_content( model=\"gemini-embedding-2\", contents=\"What is the meaning of life?\", config=types.EmbedContentConfig(output_dimensionality=768) ) [embedding_obj] = result.embeddings embedding_length = len(embedding_obj.values) print(f\"Length of embedding: {embedding_length}\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; async function main() { const ai = new GoogleGenAI({}); const response = await ai.models.embedContent({ model: 'gemini-embedding-2', contents: 'What is the meaning of life?', config: { outputDimensionality: 768 }, }); const embeddingLength = response.embeddings[0].values.length; console.log(`Length of embedding: ${embeddingLength}`); } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` Go`package main import ( \"context\" \"fmt\" \"log\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() // The client uses Application Default Credentials. // Authenticate with 'gcloud auth application-default login'. client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() contents := []*genai.Content{ genai.NewContentFromText(\"What is the meaning of life?\", genai.RoleUser), } result, err := client.Models.EmbedContent(ctx, \"gemini-embedding-2\", contents, &genai.EmbedContentRequest{OutputDimensionality: 768}, ) if err != nil { log.Fatal(err) } embedding := result.Embeddings[0] embeddingLength := len(embedding.Values) fmt.Printf(\"Length of embedding: %d\\n\", embeddingLength) }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2:embedContent\" \\ -H 'Content-Type: application/json' \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"content\": {\"parts\":[{ \"text\": \"What is the meaning of life?\"}]}, \"output_dimensionality\": 768 }'` Example output from the code snippet: `Length of embedding: 768` Ensuring quality for smaller dimensions While the default 3072-dimension embeddings are always normalized, Gemini\nEmbedding 2 also auto-normalizes truncated dimensions (e.g., 768, 1536). This\nensures semantic similarity is calculated via vector direction rather than\nmagnitude, providing more accurate results out of the box. **Older Models**: If you are using `gemini-embedding-001`, you must manually\nnormalize non-3072 dimensions as follows: Python`import numpy as np from numpy.linalg import norm # Only for embeddings from `gemini-embedding-001` embedding_values_np = np.array(embedding_obj.values) normed_embedding = embedding_values_np / np.linalg.norm(embedding_values_np) print(f\"Normed embedding length: {len(normed_embedding)}\") print(f\"Norm of normed embedding: {np.linalg.norm(normed_embedding):.6f}\") # Should be very close to 1` Example output from this code snippet: `Normed embedding length: 768\nNorm of normed embedding: 1.000000` The following table shows the MTEB scores, a commonly used benchmark for\nembeddings, for different dimensions. Notably, the result shows that performance\nis not strictly tied to the size of the embedding dimension, with lower\ndimensions achieving scores comparable to their higher dimension counterparts. MRL Dimension MTEB Score (Gemini Embedding 001) 2048\n\n 68.16\n\n 1536\n\n 68.17\n\n 768\n\n 67.99\n\n 512\n\n 67.55\n\n 256\n\n 66.19\n\n 128\n\n 63.31\n\n Multimodal embeddings The `gemini-embedding-2` model supports multimodal input, allowing you\nto embed images, video, audio, and documents content alongside text. All modalities\nare mapped into the same embedding space, enabling cross-modal search and\ncomparison. Supported modalities and limits The overall maximum input tokens limit is 8192 tokens. Modality Specifications and limits **Text** Supports up to 8,192 tokens. **Image** Maximum of 6 images per request. Supported formats: PNG, JPEG.\n **Audio** Maximum duration of 180 seconds. Supported formats: MP3, WAV. **Video** Maximum duration of 120 seconds. Supported formats: MP4, MOV. Supported codecs: H264, H265, AV1, VP9.\n\n The system processes a maximum of 32 frames per video: short videos (≤32s) are sampled at 1 fps, while longer videos are uniformly sampled to 32 frames. Audio tracks are not processed in video files.\n **Documents (PDF)** Maximum of 1 file per request, up to 6 pages. Embedding images The following example shows how to embed an image using\n`gemini-embedding-2`. Images can be provided as inline data or as uploaded files\nthrough the [Files API](/gemini-api/docs/files). Python`from google import genai from google.genai import types with open('example.png', 'rb') as f: image_bytes = f.read() client = genai.Client() result = client.models.embed_content( model='gemini-embedding-2', contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/png', ), ] ) print(result.embeddings)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const imgBase64 = fs.readFileSync(\"example.png\", { encoding: \"base64\" }); const response = await ai.models.embedContent({ model: 'gemini-embedding-2', contents: [{ inlineData: { mimeType: 'image/png', data: imgBase64, }, }], }); console.log(response.embeddings); } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` REST`IMG_PATH=\"/path/to/your/image.png\" IMG_BASE64=$(base64 -w0 \"${IMG_PATH}\")\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2:embedContent\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"content\": { \"parts\": [{ \"inline_data\": { \"mime_type\": \"image/png\", \"data\": \"'\"${IMG_BASE64}\"'\" } }] } }'` Embedding aggregation When working with multimodal content, how you structure your input affects the\nembedding output: **Multiple parts (aggregated):** Adding multiple inputs directly to the\n`contents` parameter produces one aggregated embedding for all inputs. **Multiple `Content` objects (separate):** Wrapping each input in a\n`Content` object and passing them in the `contents` parameter returns\nseparate embeddings for each entry. **Post-level representation:** For complex objects like social media posts\nwith multiple media items, we recommend aggregating separate embeddings\n(for example, by averaging) to create a coherent post-level representation. The following example shows how to create one aggregated embedding for text and\nimage input. Simply add multiple inputs to the `contents` parameter: Python`from google import genai from google.genai import types client = genai.Client() with open('dog.png', 'rb') as f: image_bytes = f.read() result = client.models.embed_content( model='gemini-embedding-2', contents=[ \"An image of a dog\", types.Part.from_bytes( data=image_bytes, mime_type='image/png', ), ] ) # This produces one embedding for embedding in result.embeddings: print(embedding.values)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const imgBase64 = fs.readFileSync(\"dog.png\", { encoding: \"base64\" }); const response = await ai.models.embedContent({ model: 'gemini-embedding-2', contents: [ 'An image of a dog', { inlineData: { mimeType: 'image/png', data: imgBase64, }, }, ], }); // This produces one embedding for (const embedding of response.embeddings) { console.log(embedding.values); } } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` REST`IMG_PATH=\"/path/to/your/dog.png\" IMG_BASE64=$(base64 -w0 \"${IMG_PATH}\")\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2:embedContent\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"content\": { \"parts\": [ {\"text\": \"An image of a dog\"}, { \"inline_data\": { \"mime_type\": \"image/png\", \"data\": \"'\"${IMG_BASE64}\"'\" } } ] } }'` On the other hand, if you use `Content` objects inside the `contents` parameter,\nit returns separate embeddings. This example creates multiple embeddings in one\nembedding call: Python`from google import genai from google.genai import types client = genai.Client() with open('dog.png', 'rb') as f: image_bytes = f.read() result = client.models.embed_content( model=\"gemini-embedding-2\", contents=[ types.Content(parts=[types.Part.from_text(text=\"task: classification | query: An image of a dog\")]), types.Content( parts=[ types.Part.from_bytes( data=image_bytes, mime_type=\"image/png\", ), ] ), ], ) # This produces two embeddings for embedding in result.embeddings: print(embedding.values)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const imgBase64 = fs.readFileSync(\"dog.png\", { encoding: \"base64\" }); const response = await ai.models.embedContent({ model: 'gemini-embedding-2', contents: [ { parts: [{ text: 'task: classification | query: An image of a dog' }] }, { parts: [{ inlineData: { mimeType: 'image/png', data: imgBase64, }, }], }, ], }); // This produces two embeddings for (const embedding of response.embeddings) { console.log(embedding.values); } } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` REST`IMG_PATH=\"/path/to/your/dog.png\" IMG_BASE64=$(base64 -w0 \"${IMG_PATH}\")\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2:batchEmbedContents\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"requests\": [ { \"model\": \"models/gemini-embedding-2\", \"content\": {\"parts\": [{\"text\": \"task: classification | query: An image of a dog\"}]} }, { \"model\": \"models/gemini-embedding-2\", \"content\": {\"parts\": [{\"inline_data\": {\"mime_type\": \"image/png\", \"data\": \"'\"${IMG_BASE64}\"'\"}}]} } ] }'` Embedding audio The following example shows how to embed an audio file using\n`gemini-embedding-2`. Audio files can be provided as inline data or as uploaded files\nthrough the [Files API](/gemini-api/docs/files). Python`from google import genai from google.genai import types with open('example.mp3', 'rb') as f: audio_bytes = f.read() client = genai.Client() result = client.models.embed_content( model='gemini-embedding-2', contents=[ types.Part.from_bytes( data=audio_bytes, mime_type='audio/mpeg', ), ] ) print(result.embeddings)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const audioBase64 = fs.readFileSync(\"example.mp3\", { encoding: \"base64\" }); const response = await ai.models.embedContent({ model: 'gemini-embedding-2', contents: [{ inlineData: { mimeType: 'audio/mpeg', data: audioBase64, }, }], }); console.log(response.embeddings); } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` REST`AUDIO_PATH=\"/path/to/your/example.mp3\" AUDIO_BASE64=$(base64 -w0 \"${AUDIO_PATH}\")\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2:embedContent\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"content\": { \"parts\": [{ \"inline_data\": { \"mime_type\": \"audio/mpeg\", \"data\": \"'\"${AUDIO_BASE64}\"'\" } }] } }'` Embedding video The following example shows how to embed a video using\n`gemini-embedding-2`. Videos can be provided as inline data or as uploaded files\nthrough the [Files API](/gemini-api/docs/files). Python`from google import genai from google.genai import types client = genai.Client() with open('example.mp4', 'rb') as f: video_bytes = f.read() result = client.models.embed_content( model='gemini-embedding-2', contents=[ types.Part.from_bytes( data=video_bytes, mime_type='video/mp4', ), ] ) print(result.embeddings[0].values)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const videoBase64 = fs.readFileSync(\"example.mp4\", { encoding: \"base64\" }); const response = await ai.models.embedContent({ model: 'gemini-embedding-2', contents: [{ inlineData: { mimeType: 'video/mp4', data: videoBase64, }, }], }); console.log(response.embeddings); } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` REST`VIDEO_PATH=\"/path/to/your/video.mp4\" VIDEO_BASE64=$(base64 -w0 \"${VIDEO_PATH}\")\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2:embedContent\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"content\": { \"parts\": [{ \"inline_data\": { \"mime_type\": \"video/mp4\", \"data\": \"'\"${VIDEO_BASE64}\"'\" } }] } }'` If you need to embed videos >120 seconds, you can chunk the video into\noverlapping segments and embed those chunks individually. Embedding documents Documents in PDF format can be embedded directly. The model processes the visual and text\ncontent of each page. PDFs can be provided as inline data or as uploaded files\nthrough the [Files API](/gemini-api/docs/files). How the model processes PDFs When you embed a PDF, the model processes the document using both visual and text features: **Visual representation:** The model renders each page as an image, which consumes **258 tokens** per page. **Text extraction:** The model extracts text from the document. For **native PDFs** (which contain digital text), the model extracts the text directly. For **scanned PDFs** (which contain images of text), the model automatically runs optical character recognition (OCR) to extract the text. To calculate the total token count for a PDF, add the visual tokens (258 per page) to the text tokens. Your inputs must fit within the model's **8,192 token limit** (shared across all modalities). The system silently truncates inputs that exceed this limit. PDF limits **Files per request:** You can submit a maximum of 1 PDF file. **Page limit:** You can submit a maximum of 6 pages per file. For the best quality, we strongly recommend using 1 page per PDF. The following example shows how to embed a PDF using `gemini-embedding-2`: Python`from google import genai from google.genai import types with open('example.pdf', 'rb') as f: pdf_bytes = f.read() client = genai.Client() result = client.models.embed_content( model='gemini-embedding-2', contents=[ types.Part.from_bytes( data=pdf_bytes, mime_type='application/pdf', ), ] ) print(result.embeddings)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const pdfBase64 = fs.readFileSync(\"example.pdf\", { encoding: \"base64\" }); const response = await ai.models.embedContent({ model: 'gemini-embedding-2', contents: [{ inlineData: { mimeType: 'application/pdf', data: pdfBase64, }, }], }); console.log(response.embeddings); } main();` Java`import com.google.genai.Client; import com.google.genai.types.EmbedContentResponse; import java.util.Collections; Client client = new Client(); EmbedContentResponse response = client.models.embedContent(\"text-embedding-004\", \"Why is the sky blue?\", null); response.embeddings().ifPresent(list -> { for (var emb : list) { System.out.println(\"Embedding values: \" + emb.values().orElse(Collections.emptyList())); } });` REST`PDF_PATH=\"/path/to/your/example.pdf\" PDF_BASE64=$(base64 -w0 \"${PDF_PATH}\")\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2:embedContent\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"content\": { \"parts\": [{ \"inline_data\": { \"mime_type\": \"application/pdf\", \"data\": \"'\"${PDF_BASE64}\"'\" } }] } }'` Use cases Text embeddings are crucial for a variety of common AI use cases, such as: **Retrieval-Augmented Generation (RAG):** Embeddings enhance the quality\nof generated text by retrieving and incorporating relevant information into\nthe context of a model. **Information retrieval:** Search for the most semantically similar text or\ndocuments given a piece of input text. [Document search tutorialtask](https://github.com/google-gemini/cookbook/blob/main/examples/Talk_to_documents_with_embeddings.ipynb) **Search reranking**: Prioritize the most relevant items by semantically\nscoring initial results against the query. [Search reranking tutorialtask](https://github.com/google-gemini/cookbook/blob/main/examples/Search_reranking_using_embeddings.ipynb) **Anomaly detection:** Comparing groups of embeddings can help identify\nhidden trends or outliers. [Anomaly detection tutorialbubble_chart](https://github.com/google-gemini/cookbook/blob/main/examples/Anomaly_detection_with_embeddings.ipynb) **Classification:** Automatically categorize text based on its content, such\nas sentiment analysis or spam detection [Classification tutorialtoken](https://github.com/google-gemini/cookbook/blob/main/examples/Classify_text_with_embeddings.ipynb) **Clustering:** Effectively grasp complex relationships by creating clusters\nand visualizations of your embeddings. [Clustering visualization tutorialbubble_chart](https://github.com/google-gemini/cookbook/blob/main/examples/clustering_with_embeddings.ipynb) Storing embeddings As you take embeddings to production, it is common to\nuse **vector databases** to efficiently store, index, and retrieve\nhigh-dimensional embeddings. Google Cloud offers managed data services that\ncan be used for this purpose including\n[Gemini Enterprise Agent Platform Vector Search 2.0](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/overview),\n[BigQuery](https://cloud.google.com/bigquery/docs/introduction),\n[AlloyDB](https://cloud.google.com/alloydb/docs/overview), and\n[Cloud SQL](https://cloud.google.com/sql/docs/postgres/introduction). The following tutorials show how to use other third party vector databases\nwith Gemini Embedding. [ChromaDB tutorialsbolt](https://docs.trychroma.com/integrations/embedding-models/google-gemini) [QDrant tutorialsbolt](https://qdrant.tech/documentation/embeddings/gemini/) [Weaviate tutorialsbolt](https://docs.weaviate.io/weaviate/model-providers/google) [Pinecone tutorialsbolt](https://github.com/google-gemini/cookbook/blob/main/examples/langchain/Gemini_LangChain_QA_Pinecone_WebLoad.ipynb) Model versions Gemini Embedding 2 Property Description id_cardModel code **Gemini API** `gemini-embedding-2` saveSupported data types **Input** Text, image, video, audio, PDF **Output** Text embeddings token_autoToken limits[[*]](/gemini-api/docs/tokens) **Input token limit** 8,192 **Output dimension size** Flexible, supports: 128 - 3072, Recommended: 768, 1536, 3072 123Versions Read the [model version patterns](/gemini-api/docs/models/gemini#model-versions) for more details. Stable: `gemini-embedding-2` calendar_monthLatest update April 2026 Gemini Embedding Property Description id_cardModel code **Gemini API** `gemini-embedding-001` saveSupported data types **Input** Text **Output** Text embeddings token_autoToken limits[[*]](/gemini-api/docs/tokens) **Input token limit** 2,048 **Output dimension size** Flexible, supports: 128 - 3072, Recommended: 768, 1536, 3072 123Versions Read the [model version patterns](/gemini-api/docs/models/gemini#model-versions) for more details. Stable: `gemini-embedding-001` calendar_monthLatest update June 2025 For deprecated Embeddings models, visit the [Deprecations](/gemini-api/docs/deprecations) page Migration from gemini-embedding-001 The embedding spaces between `gemini-embedding-001` and\n`gemini-embedding-2` are **incompatible**. This means you cannot\ndirectly compare embeddings generated by one model with embeddings generated by\nthe other. If you are upgrading to `gemini-embedding-2`, you must\nre-embed all of your existing data. Beyond incompatibility, there are several other notable differences between\nthe two models: **Task type specification:** With `gemini-embedding-001`, you specify the\ntask type using the `task_type` parameter (e.g., `SEMANTIC_SIMILARITY`,\n`RETRIEVAL_DOCUMENT`). With `gemini-embedding-2`, the `task_type`\nparameter is not supported. Instead, you should include task instructions\ndirectly in the prompt for text-only tasks. See\nTask types with Embeddings 2 for details on how\nto format prompts for different use cases. **Embedding aggregation:** `gemini-embedding-001` generates individual\nembeddings for each string in a list of inputs. In contrast,\n`gemini-embedding-2` produces a single, aggregated embedding when multiple\ninputs (like text and images) are provided directly in one request. To\ngenerate separate embeddings for individual inputs, wrap each input in a\n`Content` object, or use the\n[Batch API](/gemini-api/docs/batch-api#batch-embedding). See\nEmbedding aggregation for more information. **Normalization:** If you use `output_dimensionality` to request embeddings\nwith fewer than 3072 dimensions, `gemini-embedding-2` automatically\nnormalizes these truncated embeddings. With `gemini-embedding-001`, you\nneed to perform manual normalization for dimensions other than 3072. See\nEnsuring quality for smaller dimensions\nfor details. Batch embeddings If latency is not a concern, try using the Gemini Embeddings models with\n[Batch API](/gemini-api/docs/batch-api#batch-embedding). This\nallows for much higher throughput at 50% of the default Embedding price.\nFind examples on how to get started in the [Batch API cookbook](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb). Responsible use notice Unlike generative AI models that create new content, the Gemini Embedding model\nis only intended to transform the format of your input data into a numerical\nrepresentation. While Google is responsible for providing an embedding model\nthat transforms the format of your input data to the numerical-format requested,\nusers retain full responsibility for the data they input and the resulting\nembeddings. By using the Gemini Embedding model you confirm that you have the\nnecessary rights to any content that you upload. Do not generate content that\ninfringes on others' intellectual property or privacy rights. Your use of this\nservice is subject to our [Prohibited Use\nPolicy](https://policies.google.com/terms/generative-ai/use-policy) and\n[Google's Terms of Service](/gemini-api/terms). Start building with embeddings Check out the [embeddings quickstart\nnotebook](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Embeddings.ipynb)\nto explore the model capabilities and learn how to customize and visualize your\nembeddings. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 36679, "slov": 4609, "odkazu": 150, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:23", "sha256": "9f404e186989ecd59514ace63832de89964b69afdc9da42cff283012c21809df", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://github.com/google-gemini/cookbook/blob/main/examples/Talk_to_documents_with_embeddings.ipynb", "https://github.com/google-gemini/cookbook/blob/main/examples/Search_reranking_using_embeddings.ipynb", "https://github.com/google-gemini/cookbook/blob/main/examples/Anomaly_detection_with_embeddings.ipynb", "https://github.com/google-gemini/cookbook/blob/main/examples/Classify_text_with_embeddings.ipynb", "https://github.com/google-gemini/cookbook/blob/main/examples/clustering_with_embeddings.ipynb", "https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/overview", "https://cloud.google.com/bigquery/docs/introduction", "https://cloud.google.com/alloydb/docs/overview", "https://cloud.google.com/sql/docs/postgres/introduction", "https://docs.trychroma.com/integrations/embedding-models/google-gemini", "https://qdrant.tech/documentation/embeddings/gemini/", "https://docs.weaviate.io/weaviate/model-providers/google", "https://github.com/google-gemini/cookbook/blob/main/examples/langchain/Gemini_LangChain_QA_Pinecone_WebLoad.ipynb", "https://github.com/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb", "https://policies.google.com/terms/generative-ai/use-policy", "https://github.com/google-gemini/cookbook/blob/main/quickstarts/Embeddings.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/ephemeral-tokens", "titulek": "Ephemeral tokens | Gemini API | Google AI for Developers", "h1": "Ephemeral tokens", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/live-api/ephemeral-tokens", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Ephemeral tokens  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/live-api/ephemeral-tokens", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Ephemeral tokens"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Ephemeral tokens", "item": "https://ai.google.dev/gemini-api/docs/live-api/ephemeral-tokens"}]}], "drobecky": ["Gemini API", "Ephemeral tokens"], "osnova": [{"uroven": 1, "text": "Ephemeral tokens"}, {"uroven": 2, "text": "How ephemeral tokens work"}, {"uroven": 2, "text": "Create an ephemeral token"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Connect to Live API with an ephemeral token"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Ephemeral tokens Ephemeral tokens are short-lived authentication tokens for accessing the Gemini\nAPI through [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API). They are designed to enhance security when\nyou are connecting directly from a user's device to the API (a\n[client-to-server](/gemini-api/docs/live#implementation-approach)\nimplementation). Like standard API keys, ephemeral tokens can be extracted from\nclient-side applications such as web browsers or mobile apps. But because\nephemeral tokens expire quickly and can be restricted, they significantly reduce\nthe security risks in a production environment. You should use them when\naccessing the Live API directly from client-side applications to enhance API\nkey security. How ephemeral tokens work Here's how ephemeral tokens work at a high level: Your client (e.g. web app) authenticates with your backend. Your backend requests an ephemeral token from Gemini API's provisioning\nservice. Gemini API issues a short-lived token. Your backend sends the token to the client for WebSocket connections to Live\nAPI. You can do this by swapping your API key with an ephemeral token. The client then uses the token as if it were an API key. This enhances security because even if extracted, the token is short-lived,\nunlike a long-lived API key deployed client-side. Since the client sends data\ndirectly to Gemini, this also improves latency and avoids your backends needing\nto proxy the real time data. Create an ephemeral token Here is a simplified example of how to get an ephemeral token from Gemini.\nBy default, you'll have 1 minute to start new Live API sessions using the token\nfrom this request (`newSessionExpireTime`), and 30 minutes to send messages over\nthat connection (`expireTime`). Python`import datetime from google import genai now = datetime.datetime.now(tz=datetime.timezone.utc) client = genai.Client() token = client.auth_tokens.create( config = { 'uses': 1, # The ephemeral token can only be used to start a single session 'expire_time': now + datetime.timedelta(minutes=30), # Default is 30 minutes in the future # 'expire_time': '2025-05-17T00:00:00Z', # Accepts isoformat. 'new_session_expire_time': now + datetime.timedelta(minutes=1), # Default 1 minute in the future } ) # You'll need to pass the value under token.name back to your client to use it` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString(); const token = await client.authTokens.create({ config: { uses: 1, // The default expireTime: expireTime, // Default is 30 mins newSessionExpireTime: new Date(Date.now() + (1 * 60 * 1000)), // Default 1 minute in the future }, });` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/auth_tokens\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"uses\": 1, \"expireTime\": \"YYYY-MM-DDTHH:MM:SSZ\", \"newSessionExpireTime\": \"YYYY-MM-DDTHH:MM:SSZ\" }'` For `expireTime` value constraints, defaults, and other field specs, see the\n[API reference](https://ai.google.dev/api/live#ephemeral-auth-tokens).\nWithin the `expireTime` timeframe, you'll need\n[`sessionResumption`](/gemini-api/docs/live-session#session-resumption) to\nreconnect the call every 10 minutes (this can be done with the same token even\nif `uses: 1`). It's also possible to lock an ephemeral token to a set of configurations. This\nmight be useful to further improve security of your application and keep your\nsystem instructions on the server side. Python`from google import genai client = genai.Client() token = client.auth_tokens.create( config = { 'uses': 1, 'live_connect_constraints': { 'model': 'gemini-3.1-flash-live-preview', 'config': { 'session_resumption':{}, 'response_modalities':['AUDIO'] } }, } ) # You'll need to pass the value under token.name back to your client to use it` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString(); const token = await client.authTokens.create({ config: { uses: 1, // The default expireTime: expireTime, liveConnectConstraints: { model: 'gemini-3.1-flash-live-preview', config: { sessionResumption: {}, responseModalities: ['AUDIO'] } }, } }); // You'll need to pass the value under token.name back to your client to use it` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/auth_tokens\" \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"uses\": 1, \"expireTime\": \"YYYY-MM-DDTHH:MM:SSZ\", \"liveConnectConstraints\": { \"model\": \"models/gemini-3.1-flash-live-preview\", \"config\": { \"sessionResumption\": {}, \"responseModalities\": [\"AUDIO\"] } } }'` You can also lock a subset of fields, see the [SDK documentation](https://googleapis.github.io/python-genai/genai.html#genai.types.CreateAuthTokenConfig.lock_additional_fields)\nfor more info. Connect to Live API with an ephemeral token Once you have an ephemeral token, you use it as if it were an API key (but\nremember, it only works for the live API, and only with the `v1beta` version of\nthe API). The use of ephemeral tokens only adds value when deploying applications\nthat follow [client-to-server implementation](/gemini-api/docs/live#implementation-approach) approach. JavaScript`import { GoogleGenAI, Modality } from '@google/genai'; // Use the token generated in the \"Create an ephemeral token\" section here const ai = new GoogleGenAI({ apiKey: token.name }); const model = 'gemini-3.1-flash-live-preview'; const config = { responseModalities: [Modality.AUDIO] }; async function main() { const session = await ai.live.connect({ model: model, config: config, callbacks: { ... }, }); // Send content... session.close(); } main();` See [Get started with Live API](/gemini-api/docs/live) for more examples. Best practices Set a short expiration duration using the `expire_time` parameter. Tokens expire, requiring re-initiation of the provisioning process. Verify secure authentication for your own backend. Ephemeral tokens will\nonly be as secure as your backend authentication method. Generally, avoid using ephemeral tokens for backend-to-Gemini connections,\nas this path is typically considered secure. Limitations Ephemeral tokens are only compatible with [Live API](/gemini-api/docs/live) at this time. What's next Read the Live API [reference](https://ai.google.dev/api/live#ephemeral-auth-tokens)\non ephemeral tokens for more information. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-07-30 UTC.", "znaku_textu": 6953, "slov": 979, "odkazu": 135, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:52:57", "sha256": "4f18f6ca5e7a75800b0e342337f1270d6a9cfc5d1eaa693d6d4f33e76f99bdb0", "hloubka": 2, "zdroj_objevu": "odkaz", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://cloud.google.com/products", "https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API", "https://googleapis.github.io/python-genai/genai.html", "https://datatracker.ietf.org/doc/html/rfc7235", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/feedback-policies", "titulek": "Feedback | Gemini API | Google AI for Developers", "h1": "Feedback", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/feedback-policies", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Feedback  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/feedback-policies", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Feedback"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Feedback", "item": "https://ai.google.dev/gemini-api/docs/feedback-policies"}]}], "drobecky": ["Gemini API", "Feedback"], "osnova": [{"uroven": 1, "text": "Feedback"}, {"uroven": 2, "text": "Inline Preference Voting"}, {"uroven": 3, "text": "Why are we doing this?"}, {"uroven": 3, "text": "What data is included in Feedback?"}, {"uroven": 3, "text": "Your Privacy"}, {"uroven": 3, "text": "Opting Out"}], "markdown": "Feedback Inline Preference Voting In Google AI Studio, you might occasionally see a side-by-side comparison of two\ndifferent responses to your prompt. This is part of our Inline Preference Voting\nsystem. You'll be asked to choose which response you prefer. This helps us\nunderstand which model outputs users find most helpful. Why are we doing this? We're constantly working to improve our AI models and services. Your feedback\nthrough Inline Preference Voting helps us provide, improve, and develop Google\nproducts and services and machine learning technologies, including Google's\nenterprise features, products and services, consistent with the\n[Gemini API Additional Terms of Service](/gemini-api/terms) and\n[Privacy Policy](https://policies.google.com/privacy). What data is included in Feedback? To make informed decisions about our models, we collect certain data when you\nparticipate in Inline Preference Voting: **Prompts and Responses:** We record all prompts and responses, including any\nuploaded content, in the conversation you submitted feedback about. We also\nrecord the two response options that you selected from. This helps us\nunderstand the context of your preference. **Your Vote:** We record which response you preferred. This is the core of the\nfeedback we're collecting. **Usage Details:** This includes information about which model generated the\nresponse and other technical and operational details about your usage of this\nfeature. Your Privacy We take your privacy seriously. Google takes steps to protect your privacy as\npart of this process. This includes disconnecting this data from your Google\nAccount, API key, and Cloud project before reviewers see or annotate it. **Do\nnot submit feedback on conversations that include sensitive, confidential, or\npersonal information.** Opting Out You'll have the option to skip the Inline Preference Voting when it appears. Thank you for helping us improve Google AI Studio! Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-04-28 UTC.", "znaku_textu": 2392, "slov": 342, "odkazu": 128, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:15", "sha256": "b9cd03c05617e523e684f87ea623626c963c94ed41b5ee50bd2f6af04c58d918", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://policies.google.com/privacy", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms"]} {"url": "https://ai.google.dev/gemini-api/docs/file-input-methods", "titulek": "File input methods | Gemini API | Google AI for Developers", "h1": "File input methods", "popis": "Get started building with Gemini's multimodal capabilities in the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/file-input-methods", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "File input methods  |  Gemini API  |  Google AI for Developers", "og:description": "Get started building with Gemini's multimodal capabilities in the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/file-input-methods", "og:image": "https://ai.google.dev/static/site-assets/images/vision.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "File input methods"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "File input methods", "item": "https://ai.google.dev/gemini-api/docs/file-input-methods"}]}], "drobecky": ["Gemini API", "File input methods"], "osnova": [{"uroven": 1, "text": "File input methods"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Input method comparison"}, {"uroven": 2, "text": "Inline data"}, {"uroven": 3, "text": "Fetch from a URL"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Gemini File API"}, {"uroven": 3, "text": "Standard file upload"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Register Google Cloud Storage files"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "CLI"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "CLI"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "CLI"}, {"uroven": 2, "text": "External HTTP / Signed URLs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Accessibility"}, {"uroven": 3, "text": "Safety checks"}, {"uroven": 3, "text": "Supported content types"}, {"uroven": 4, "text": "Text file types"}, {"uroven": 4, "text": "Application file types"}, {"uroven": 4, "text": "Image file types"}, {"uroven": 4, "text": "Video file types"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "File input methods This guide explains the different ways you can include media files such as\nimages, audio, video, and documents when making requests to the Gemini API.\nThe new methods are supported in all of the Gemini API endpoints, including\nBatch, Interactions and Live API.\nChoosing the right method depends on the size of your file, where your data is\nstored, and how frequently you plan to use the file. The simplest way to include a file as your input is to read a local file and\ninclude it in a prompt. The following example shows how to read a local PDF\nfile. PDFs are limited to 50MB for this method. See the\nInput method comparison table for a complete list of file\ninput types and limits. Python`from google import genai import pathlib import base64 client = genai.Client() filepath = pathlib.Path('my_local_file.pdf') prompt = \"Summarize this document\" interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": prompt}, {\"type\": \"document\", \"data\": base64.b64encode(filepath.read_bytes()).decode('utf-8'), \"mime_type\": \"application/pdf\"} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from 'node:fs'; const client = new GoogleGenAI({}); const prompt = \"Summarize this document\"; async function main() { const filePath = 'my_local_file.pdf'; const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: prompt }, { type: \"document\", data: fs.readFileSync(filePath).toString(\"base64\"), mime_type: \"application/pdf\" } ] }); console.log(interaction.output_text); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# Encode the local file to base64 B64_CONTENT=$(base64 -w 0 my_local_file.pdf)\n\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"text\", \"text\": \"Summarize this document\"}, { \"type\": \"document\", \"data\": \"'${B64_CONTENT}'\", \"mime_type\": \"application/pdf\" } ] }'` Input method comparison The following table compares each input method with file limits and best use\ncases. Note that the file size limit may vary depending on the file type and\nmodel or tokenizer used to process the file. Method Best for Max file size Persistence **Inline data** Quick testing, small files, real-time applications. 100 MB per request or payload \n (**50 MB for PDFs**) None (sent with every request) **File API upload** Large files, files used multiple times. 2 GB per file, \n up to 20GB per project 48 Hours **File API GCS URI registration** Large files already in Google Cloud Storage, files used multiple times. 2 GB per file, no overall storage limits None (fetched per request). One time registration can give access for up to 30 days. **External URLs** Public data or data in cloud buckets (AWS, Azure, GCS) without re-uploading. 100 MB per request/payload None (fetched per request) Inline data For smaller files (under 100MB, or 50MB for PDFs), you can pass the data\ndirectly in the request payload. This is the simplest method for quick tests or\napplications handling real-time, transient data. You can provide data as\nbase64 encoded strings or by reading local files directly. For an example of reading from a local file, see the example at the beginning of\nthis page. Fetch from a URL You can also fetch a file from a URL, convert it to bytes, and include it in the\ninput. Python`from google import genai import httpx client = genai.Client() doc_url = \"https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf\" doc_data = httpx.get(doc_url).content prompt = \"Summarize this document\" interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"document\", \"data\": base64.b64encode(doc_data).decode('utf-8'), \"mime_type\": \"application/pdf\"}, {\"type\": \"text\", \"text\": prompt} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const docUrl = 'https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf'; const prompt = \"Summarize this document\"; async function main() { const pdfResp = await fetch(docUrl) .then((response) => response.arrayBuffer()); const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: prompt }, { type: \"document\", data: Buffer.from(pdfResp).toString(\"base64\"), mime_type: \"application/pdf\" } ] }); console.log(interaction.output_text); } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`DOC_URL=\"https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf\" PROMPT=\"Summarize this document\" DISPLAY_NAME=\"base64_pdf\" # Download the PDF\nwget -O \"${DISPLAY_NAME}.pdf\" \"${DOC_URL}\" # Check for FreeBSD base64 and set flags accordingly if [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then B64FLAGS=\"--input\" else B64FLAGS=\"-w0\" fi # Base64 encode the PDF ENCODED_PDF=$(base64 $B64FLAGS \"${DISPLAY_NAME}.pdf\") # Create JSON payload file\ncat < payload.json\n{ \"model\": \"gemini-3.8-flash\",\n\"input\": [ {\"type\": \"document\", \"data\": \"${ENCODED_PDF}\", \"mime_type\": \"application/pdf\"},\n{\"type\": \"text\", \"text\": \"${PROMPT}\"} ] }\nEOF\n\n# Generate content using interactions\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d @payload.json 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".outputs[] | select(.type == \\\"text\\\") | .text\" response.json` Gemini File API The File API is designed for larger files (up to 2GB) or files you intend to\nuse in multiple requests. Standard file upload Upload a local file to the Gemini API. Files uploaded this way are stored\ntemporarily (48 hours) and processed for efficient retrieval by the model. Python`from google import genai client = genai.Client() doc_file = client.files.upload(file=\"path/to/your/sample.pdf\") prompt = \"Summarize this document\" interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": prompt}, {\"type\": \"document\", \"uri\": doc_file.uri, \"mime_type\": doc_file.mime_type} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const prompt = \"Summarize this document\"; async function main() { const filePath = \"path/to/your/sample.pdf\"; const myfile = await client.files.upload({ file: filePath, config: { mime_type: \"application/pdf\" }, }); const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: prompt }, { type: \"document\", uri: myfile.uri, mime_type: myfile.mimeType } ] }); console.log(interaction.output_text); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`FILE_PATH=\"path/to/sample.pdf\" MIME_TYPE=$(file -b --mime-type \"${FILE_PATH}\") NUM_BYTES=$(wc -c < \"${FILE_PATH}\") DISPLAY_NAME=DOCUMENT\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files\" \\ -D \"${tmp_header_file}\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${FILE_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) # Now use in an interaction\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"text\", \"text\": \"Summarize this document\"}, {\"type\": \"document\", \"uri\": '$file_uri', \"mime_type\": \"'${MIME_TYPE}'\"} ] }'` Register Google Cloud Storage files If your data is already in Google Cloud Storage, you don't need to\ndownload and re-upload it. You can register it directly with the File API. Grant **Service Agent** access to each bucket Enable the Gemini API in your Google Cloud project. Create the Service Agent: `gcloud beta services identity create --service=generativelanguage.googleapis.com --project=` **Grant the Gemini API Service Agent permissions** to read your storage\nbuckets. The user needs to assign the `Storage Object Viewer` [IAM role](https://docs.cloud.google.com/storage/docs/access-control/iam-roles#storage.objectViewer)\nto this service agent on the specific storage buckets they intend to use. This access doesn't expire by default, but can be changed at any time. You can\nalso use the\n[Google Cloud Storage IAM SDK](https://cloud.google.com/iam/docs/write-policy-client-libraries)\ncommands to grant permissions. Authenticate your service **Prerequisites** Enable API Create a service account or agent with appropriate permissions. You first need to authenticate as the service that has storage object viewer\npermissions. How this happens depends on the environment in which your file\nmanagement code will be running. **Outside of Google Cloud** If your code is running from outside of Google Cloud, such as your desktop,\ndownload the account credentials from the Google Cloud Console with the\nfollowing steps: Browse to the [Service Account console](https://console.cloud.google.com/iam-admin/serviceaccounts) Select the relevant service account Select the **Keys** tab and choose **Add key, Create new key** Choose the **JSON** key type, and note where the file was downloaded to on\nyour machine. For more details, see the official Google Cloud documentation on\n[service account key management](https://docs.cloud.google.com/iam/docs/keys-create-delete). Then use the following commands to authenticate. These commands assume your\nservice account file is in the current directory, named\n`service-account.json`. Python`from google.oauth2.service_account import Credentials GCS_READ_SCOPES = [ 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/cloud-platform' ] SERVICE_ACCOUNT_FILE = 'service-account.json' credentials = Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=GCS_READ_SCOPES )` Javascript`const { GoogleAuth } = require('google-auth-library'); const GCS_READ_SCOPES = [ 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/cloud-platform' ]; const SERVICE_ACCOUNT_FILE = 'service-account.json'; const auth = new GoogleAuth({ keyFile: SERVICE_ACCOUNT_FILE, scopes: GCS_READ_SCOPES });` CLI`gcloud auth application-default login \\ --client-id-file=service-account.json \\ --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only'` **On Google Cloud** If you are running directly in Google Cloud, for example by using [Cloud\nRun functions](https://cloud.google.com/functions) or a\n[Compute Engine instance](https://cloud.google.com/products/compute), you will\nhave implicit credentials but will need to re-authenticate to grant the\nappropriate scopes. PythonThis code expects that the service is running in an environment where\n[Application Default Credentials](https://docs.cloud.google.com/docs/authentication/application-default-credentials)\ncan be obtained automatically, such as Cloud Run or Compute Engine. `import google.auth GCS_READ_SCOPES = [ 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/cloud-platform' ] credentials, project = google.auth.default(scopes=GCS_READ_SCOPES)` JavaScriptThis code expects that the service is running in an environment where\n[Application Default Credentials](https://docs.cloud.google.com/docs/authentication/application-default-credentials)\ncan be obtained automatically, such as Cloud Run or Compute Engine. `const { GoogleAuth } = require('google-auth-library'); const auth = new GoogleAuth({ scopes: [ 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/cloud-platform' ] });` Java`java\nimport com.google.genai.Client;\nimport com.google.genai.gaos.models.interactions.Content;\nimport com.google.genai.gaos.models.interactions.CreateModelInteraction;\nimport com.google.genai.gaos.models.interactions.DocumentContent;\nimport com.google.genai.gaos.models.interactions.DocumentContentMimeType;\nimport com.google.genai.gaos.models.interactions.Interaction;\nimport com.google.genai.gaos.models.interactions.InteractionsInput;\nimport com.google.genai.gaos.models.interactions.Model;\nimport com.google.genai.gaos.models.interactions.TextContent;\nimport com.google.genai.gaos.models.operations.CreateInteractionRequestBody;\nimport java.util.Arrays;\nimport java.util.List;\n\nClient client = new Client();\n\nContent textContent = TextContent.builder().text(\"Summarize this document.\").build();\nContent docContent =\n DocumentContent.builder()\n .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\")\n .mimeType(DocumentContentMimeType.APPLICATION_PDF)\n .build();\n\nList contents = Arrays.asList(textContent, docContent);\n\nCreateModelInteraction params =\n CreateModelInteraction.builder()\n .model(Model.of(\"gemini-3.8-flash\"))\n .input(InteractionsInput.ofContent(contents))\n .build();\n\nInteraction interaction =\n client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();\n\nSystem.out.println(interaction.outputText().orElse(\"\"));` CLIThis is an interactive command. For services like Compute Engine you can attach scopes to\nthe running service at the config level. See the [user-managed service\ndocs](https://docs.cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#using)\nfor an example. `gcloud auth application-default login \\\n--scopes=\"https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only\"` File registration (Files API)\n\nUse the Files API to register files and produce a Files API path that can\ndirectly be used in the Gemini API. Python`from google import genai client = genai.Client(credentials=credentials) registered_gcs_files = client.files.register_files( uris=[\"gs://my_bucket/some_object.pdf\", \"gs://bucket2/object2.txt\"] ) prompt = \"Summarize this file.\" for f in registered_gcs_files.files: print(f.name) interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": prompt}, {\"type\": \"document\", \"uri\": f.uri, \"mime_type\": f.mime_type} ], ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({ auth: auth }); async function main() { const registeredGcsFiles = await ai.files.registerFiles({ uris: [\"gs://my_bucket/some_object.pdf\", \"gs://bucket2/object2.txt\"] }); const prompt = \"Summarize this file.\"; for (const file of registeredGcsFiles.files) { console.log(file.name); const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: prompt }, { type: \"document\", uri: file.uri, mime_type: file.mimeType } ] }); console.log(interaction.output_text); } } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` CLI`access_token=$(gcloud auth application-default print-access-token) project_id=$(gcloud config get-value project)\ncurl -X POST https://generativelanguage.googleapis.com/v1beta/files:register \\ -H 'Content-Type: application/json' \\ -H \"Authorization: Bearer ${access_token}\" \\ -H \"x-goog-user-project: ${project_id}\" \\ -d '{\"uris\": [\"gs://bucket/object1\", \"gs://bucket/object2\"]}'` External HTTP / Signed URLs You can pass publicly accessible HTTPS URLs or pre-signed URLs directly in your\nrequest. The Gemini API will fetch the content securely during processing.\nThis is ideal for files up to 100MB that you don't want to re-upload. Python`from google import genai uri = \"https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf\" prompt = \"Summarize this file\" client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"document\", \"uri\": uri, \"mime_type\": \"application/pdf\"}, {\"type\": \"text\", \"text\": prompt} ] ) print(interaction.output_text)` Javascript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const uri = \"https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf\"; async function main() { const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: [ { type: \"document\", uri: uri, mime_type: \"application/pdf\" }, { type: \"text\", text: \"summarize this file\" } ] }); console.log(interaction.output_text); } main();` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H 'x-goog-api-key: $GEMINI_API_KEY' \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"text\", \"text\": \"Summarize this pdf\"}, { \"type\": \"document\", \"uri\": \"https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf\", \"mime_type\": \"application/pdf\" } ] }'` Accessibility Verify that the URLs you provide don't lead to pages that require a login or\nare behind a paywall. For private databases, ensure you create a signed URL\nwith the correct access permissions and expiry. Safety checks The system performs a content moderation check on the URL to confirm they meet\nsafety and policy standards. If the URL fails this check, you will get an\n`url_retrieval_status` of `URL_RETRIEVAL_STATUS_UNSAFE`. Supported content types This list of supported file types and limitations is intended as initial\nguidance and is not comprehensive. The effective\nset of supported types is subject to change and can vary based on the specific\nmodel and tokenizer version in use. Unsupported types will result in an error.\nAdditionally, content retrieval for these file types\nonly supports publicly accessible URLs. Text file types `text/html` `text/css` `text/plain` `text/xml` `text/csv` `text/rtf` `text/javascript` Application file types `application/json` `application/pdf` Image file types `image/bmp` `image/jpeg` `image/png` `image/webp` Video file types `video/mp4` `video/mpeg` `video/quicktime` `video/avi` `video/x-flv` `video/mpg` `video/webm` `video/wmv` `video/3gpp` Best practices **Choose the right method:** Use inline data for small, transient files.\nUse the File API for larger or frequently used files. Use external URLs\nfor data already hosted online. **Specify MIME Types:** Always provide the correct MIME type for the file\ndata to ensure proper processing. **Handle Errors:** Implement error handling in your code to manage\npotential issues like network failures, file access problems, or API\nerrors. Limitations File size limits vary by method (see comparison table)\nand file type. Inline data increases request payload size. File API uploads are temporary and expire after 48 hours. External URL fetching is limited to 100MB per payload and supports specific\ncontent types. What's next Try writing your own multimodal prompts using\n[Google AI Studio](http://aistudio.google.com/). For information on including files in your prompts, see the\n[Vision](/gemini-api/docs/vision),\n[Audio](/gemini-api/docs/audio), and\n[Document processing](/gemini-api/docs/document-processing)\nguides. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 25174, "slov": 2645, "odkazu": 138, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:02:46", "sha256": "d77fa029980a9296f59017a733972e15cc4446853237eb07389f533b477765b5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://docs.cloud.google.com/storage/docs/access-control/iam-roles", "https://cloud.google.com/iam/docs/write-policy-client-libraries", "https://console.cloud.google.com/iam-admin/serviceaccounts", "https://docs.cloud.google.com/iam/docs/keys-create-delete", "https://cloud.google.com/functions", "https://cloud.google.com/products/compute", "https://docs.cloud.google.com/docs/authentication/application-default-credentials", "https://docs.cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances", "http://aistudio.google.com/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/file-search", "titulek": "File search | Gemini API | Google AI for Developers", "h1": "File search", "popis": "Get started building RAG solutions with the File Search tool in the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/file-search", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "File search  |  Gemini API  |  Google AI for Developers", "og:description": "Get started building RAG solutions with the File Search tool in the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/file-search", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "File search"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "File search", "item": "https://ai.google.dev/gemini-api/docs/file-search"}]}], "drobecky": ["Gemini API", "File search"], "osnova": [{"uroven": 1, "text": "File search"}, {"uroven": 2, "text": "Directly upload to File Search store"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Importing files"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Chunking configuration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How it works"}, {"uroven": 2, "text": "File Search stores"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "File Search documents"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "File metadata"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multimodal File Search"}, {"uroven": 3, "text": "Configure the embedding model"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Upload images"}, {"uroven": 2, "text": "Citations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Page numbers"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Media citations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Custom metadata"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Structured output"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Supported models"}, {"uroven": 2, "text": "Supported file types"}, {"uroven": 3, "text": "Application file types"}, {"uroven": 3, "text": "Text file types"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 3, "text": "Rate limits"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "What's next"}], "markdown": "File search The Gemini API enables Retrieval Augmented Generation (\"RAG\") through the File\nSearch tool. File Search imports, chunks, and indexes your data to\nenable fast retrieval of relevant information based on a provided prompt. This\nretrieved information is then used as context for the model, allowing it to\nprovide more accurate and relevant answers. File search is also able to\nprovide multimodal capabilities with text embeddings supported by\n`gemini-embedding-001`, and image/multimodal embedding supported by `gemini-embedding-2`. File storage and embedding generation at query time is free, and you'll only pay\nfor creating embeddings when you first index your files and the normal Gemini\nmodel input / output tokens cost. This new billing paradigm makes the File\nSearch Tool both easier and more cost-effective to build and scale with. See\npricing section for details. Directly upload to File Search store This example shows how to directly upload a file to the\n[file search store](/api/file-search/file-search-stores#method:-media.uploadtofilesearchstore): Python`from google import genai from google.genai import types import time client = genai.Client() file_search_store = client.file_search_stores.create( config={ 'display_name': 'your-fileSearchStore-name', 'embedding_model': 'models/gemini-embedding-2' } ) operation = client.file_search_stores.upload_to_file_search_store( file='sample.txt', file_search_store_name=file_search_store.name, config={ 'display_name' : 'display-file-name', } ) while not operation.done: time.sleep(5) operation = client.operations.get(operation) interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Can you tell me about [insert question]\", tools=[{ \"type\": \"file_search\", \"file_search_store_names\": [file_search_store.name] }] ) for step in interaction.steps: if step.type == \"model_output\": for content_block in step.content: if content_block.type == \"text\": print(content_block.text) if content_block.annotations: print(\"\\nSources:\") for annotation in content_block.annotations: if annotation.type == \"file_citation\": print(f\" - {annotation.file_name}: {annotation.source}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); async function run() { const fileSearchStore = await ai.fileSearchStores.create({ config: { displayName: 'your-fileSearchStore-name', embeddingModel: 'models/gemini-embedding-2' } }); let operation = await ai.fileSearchStores.uploadToFileSearchStore({ file: 'file.txt', fileSearchStoreName: fileSearchStore.name, config: { displayName: 'file-name', } }); while (!operation.done) { await new Promise(resolve => setTimeout(resolve, 5000)); operation = await ai.operations.get({ operation }); } const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Can you tell me about [insert question]\", tools: [{ type: \"file_search\", file_search_store_names: [fileSearchStore.name] }] }); for (const step of interaction.steps) { if (step.type === 'model_output') { for (const contentBlock of step.content) { if (contentBlock.type === 'text') { console.log(contentBlock.text); if (contentBlock.annotations) { console.log(\"\\nSources:\"); for (const annotation of contentBlock.annotations) { if (annotation.type === 'file_citation') { console.log(` - ${annotation.file_name}: ${annotation.source}`); } } } } } } } } run();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# 1. Create a File Search store\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=$GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"displayName\": \"your-file-search-store-name\", \"embeddingModel\": \"models/gemini-embedding-2\" }' > store_res.json\n\nFILE_SEARCH_STORE_NAME=$(jq -r \".name\" store_res.json) # 2. Upload directly to File Search store using resumable upload NUM_BYTES=$(wc -c < \"sample.txt\")\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/fileSearchStores/$FILE_SEARCH_STORE_NAME:uploadToFileSearchStore?key=$GEMINI_API_KEY\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: $NUM_BYTES\" \\ -H \"X-Goog-Upload-Header-Content-Type: text/plain\" \\ -H \"Content-Type: application/json\" \\ -d '{\"displayName\": \"sample.txt\"}' 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" upload-header.tmp | cut -d\" \" -f2 | tr -d \"\\r\")\nrm upload-header.tmp\n\ncurl \"${upload_url}\" \\ -H \"Content-Length: $NUM_BYTES\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@sample.txt\" 2> /dev/null > upload_response.json\n\ncat upload_response.json\n\n# 3. Query using the File Search store\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Can you tell me about [insert question]\", \"tools\": [{ \"type\": \"file_search\", \"file_search_store_names\": [\"'\"$FILE_SEARCH_STORE_NAME\"'\"] }] }'` Check the API reference for [`uploadToFileSearchStore`](/api/file-search/file-search-stores#method:-media.uploadtofilesearchstore) for more information. Importing files Alternatively, you can upload an existing file and [import it to your file search store](/api/file-search/file-search-stores#method:-filesearchstores.importfile): Python`from google import genai from google.genai import types import time client = genai.Client() sample_file = client.files.upload(file='sample.txt', config={'display_name': 'display_file_name'}) file_search_store = client.file_search_stores.create( config={ 'display_name': 'your-fileSearchStore-name', 'embedding_model': 'models/gemini-embedding-2' } ) operation = client.file_search_stores.import_file( file_search_store_name=file_search_store.name, file_name=sample_file.name ) while not operation.done: time.sleep(5) operation = client.operations.get(operation) interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Can you tell me about [insert question]\", tools=[{ \"type\": \"file_search\", \"file_search_store_names\": [file_search_store.name] }] ) for step in interaction.steps: if step.type == \"model_output\": for content_block in step.content: if content_block.type == \"text\": print(content_block.text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); async function run() { const sampleFile = await ai.files.upload({ file: 'sample.txt', config: { displayName: 'file-name' } }); const fileSearchStore = await ai.fileSearchStores.create({ config: { displayName: 'your-fileSearchStore-name', embeddingModel: 'models/gemini-embedding-2' } }); let operation = await ai.fileSearchStores.importFile({ fileSearchStoreName: fileSearchStore.name, fileName: sampleFile.name }); while (!operation.done) { await new Promise(resolve => setTimeout(resolve, 5000)); operation = await ai.operations.get({ operation: operation }); } const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Can you tell me about [insert question]\", tools: [{ type: \"file_search\", file_search_store_names: [fileSearchStore.name] }] }); for (const step of interaction.steps) { if (step.type === 'model_output') { for (const contentBlock of step.content) { if (contentBlock.type === 'text') { console.log(contentBlock.text); } } } } } run();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`# 1. Upload file using the Files API NUM_BYTES=$(wc -c < \"sample.txt\")\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files?key=$GEMINI_API_KEY\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: $NUM_BYTES\" \\ -H \"X-Goog-Upload-Header-Content-Type: text/plain\" \\ -H \"Content-Type: application/json\" \\ -d '{\"file\": {\"displayName\": \"sample.txt\"}}' 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" upload-header.tmp | cut -d\" \" -f2 | tr -d \"\\r\")\nrm upload-header.tmp\n\ncurl \"${upload_url}\" \\ -H \"Content-Length: $NUM_BYTES\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@sample.txt\" 2> /dev/null > file_info.json\n\nFILE_NAME=$(jq -r \".file.name\" file_info.json) # 2. Create a File Search store\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=$GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"displayName\": \"your-file-search-store-name\", \"embeddingModel\": \"models/gemini-embedding-2\" }' > store_res.json\n\nFILE_SEARCH_STORE_NAME=$(jq -r \".name\" store_res.json) # 3. Import the file into the File Search store\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/$FILE_SEARCH_STORE_NAME:importFile?key=$GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{\"fileName\": \"'\"$FILE_NAME\"'\"}' # 4. Query using the File Search store\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Can you tell me about [insert question]\", \"tools\": [{ \"type\": \"file_search\", \"file_search_store_names\": [\"'\"$FILE_SEARCH_STORE_NAME\"'\"] }] }'` Check the API reference for [`importFile`](/api/file-search/file-search-stores#method:-filesearchstores.importfile) for more information. Chunking configuration When you import a file into a File Search store, it's automatically broken down\ninto chunks, embedded, indexed, and uploaded to your File Search store. If you\nneed more control over the chunking strategy, you can specify a\n[`chunking_config`](/api/file-search/file-search-stores#request-body_5) setting\nto set a maximum number of tokens per chunk and maximum number of overlapping\ntokens. Python`from google import genai from google.genai import types import time client = genai.Client() operation = client.file_search_stores.upload_to_file_search_store( file_search_store_name=file_search_store.name, file='sample.txt', config={ 'chunking_config': { 'white_space_config': { 'max_tokens_per_chunk': 200, 'max_overlap_tokens': 20 } } } ) while not operation.done: time.sleep(5) operation = client.operations.get(operation) print(\"Custom chunking complete.\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); let operation = await ai.fileSearchStores.uploadToFileSearchStore({ file: 'file.txt', fileSearchStoreName: fileSearchStore.name, config: { displayName: 'file-name', chunkingConfig: { whiteSpaceConfig: { maxTokensPerChunk: 200, maxOverlapTokens: 20 } } } }); while (!operation.done) { await new Promise(resolve => setTimeout(resolve, 5000)); operation = await ai.operations.get({ operation }); } console.log(\"Custom chunking complete.\");` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`NUM_BYTES=$(wc -c < \"sample.txt\")\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/fileSearchStores/$FILE_SEARCH_STORE_NAME:uploadToFileSearchStore?key=$GEMINI_API_KEY\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: $NUM_BYTES\" \\ -H \"X-Goog-Upload-Header-Content-Type: text/plain\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"displayName\": \"sample.txt\", \"chunkingConfig\": { \"whiteSpaceConfig\": { \"maxTokensPerChunk\": 200, \"maxOverlapTokens\": 20 } } }' 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" upload-header.tmp | cut -d\" \" -f2 | tr -d \"\\r\")\nrm upload-header.tmp\n\ncurl \"${upload_url}\" \\ -H \"Content-Length: $NUM_BYTES\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@sample.txt\" 2> /dev/null > upload_response.json\n\ncat upload_response.json` To use your File Search store, pass it as a tool to the `interactions.create`\nmethod, as shown in the Upload and Import examples. How it works File Search uses a technique called semantic search to find information relevant\nto the user prompt. Unlike standard keyword-based search, semantic search\nunderstands the meaning and context of your query. When you import a file, it's converted into numerical representations called\n[embeddings](/gemini-api/docs/embeddings), which capture the semantic meaning of\nthe uploaded content. These embeddings are stored in a specialized File Search database.\nWhen you make a query, it's also converted into an embedding. Then the system\nperforms a File Search to find the most similar and relevant document chunks\nfrom the File Search store. There is no Time To Live (TTL) for embeddings;\nthey persist until manually deleted, or when the model is deprecated. Files,\nhowever, are deleted after 48 hours. Here's a breakdown of the process for using the File Search\n`uploadToFileSearchStore` API: **Create a File Search store**: A File Search store contains the processed\ndata from your files. It's the persistent container for the embeddings that the\nsemantic search will operate on. **Upload a file and import into a File Search store**: Simultaneously upload\na file and import the results into your File Search store. This creates a\ntemporary `File` object, which is a reference to your raw document. That data is\nthen chunked, converted into File Search embeddings, and indexed. The `File`\nobject gets deleted after 48 hours, while the data imported into the File Search\nstore will be stored indefinitely until you choose to delete it. **Query with File Search**: Finally, you use the `FileSearch` tool in a\n`generateContent` call. In the tool configuration, you specify a\n`FileSearchRetrievalResource`, which points to the `FileSearchStore` you want to\nsearch. This tells the model to perform a semantic search on that specific\nFile Search store to find relevant information to ground its response. The indexing and querying process of File Search In this diagram, the dotted line from *Documents* to *Embedding model*\n(using [`gemini-embedding-001`](/gemini-api/docs/embeddings))\nrepresents the `uploadToFileSearchStore` API (bypassing *File storage*).\nOtherwise, using the [Files API](/gemini-api/docs/files) to separately create\nand then import files moves the indexing process from *Documents* to\n*File storage* and then to *Embedding model*. File Search stores A File Search store is a container for your document embeddings. While raw files\nuploaded through the File API are deleted after 48 hours, the data imported into\na File Search store is stored indefinitely until you manually delete it. You can\ncreate multiple File Search stores to organize your documents. The\n`FileSearchStore` API lets you create, list, get, and delete to manage your file\nsearch stores. File Search store names are globally scoped. Here are some examples of how to manage your File Search stores: Python`file_search_store = client.file_search_stores.create( config={ 'display_name': 'myfilesearchstore123', 'embedding_model': 'models/gemini-embedding-2' } ) for store in client.file_search_stores.list(): print(store) my_file_search_store = client.file_search_stores.get(name=file_search_store.name) client.file_search_stores.delete(name=file_search_store.name, config={'force': True})` JavaScript`const fileSearchStore = await ai.fileSearchStores.create({ config: { displayName: 'myfilesearchstore123', embeddingModel: 'models/gemini-embedding-2' } }); const fileSearchStores = await ai.fileSearchStores.list(); for await (const store of fileSearchStores) { console.log(store); } const myFileSearchStore = await ai.fileSearchStores.get({ name: fileSearchStore.name }); await ai.fileSearchStores.delete({ name: fileSearchStore.name, config: { force: true } });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=${GEMINI_API_KEY}\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"displayName\": \"My Store\", \"embedding_model\": \"models/gemini-embedding-2\" }'\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=${GEMINI_API_KEY}\"\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/myfilesearchstore123?key=${GEMINI_API_KEY}\"\n\ncurl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/myfilesearchstore123?key=${GEMINI_API_KEY}\"` File Search documents You can manage individual documents in your file stores with the\n[File Search Documents](/api/file-search/documents) API to `list` each document\nin a file search store, `get` information about a document, and `delete` a\ndocument by name. Python`for document_in_store in client.file_search_stores.documents.list(parent='fileSearchStores/myfilesearchstore123'): print(document_in_store) file_search_document = client.file_search_stores.documents.get(name='fileSearchStores/myfilesearchstore123/documents/sampletxt123') print(file_search_document) client.file_search_stores.documents.delete(name='fileSearchStores/myfilesearchstore123/documents/sampletxt123', config={'force': True})` JavaScript`const documents = await ai.fileSearchStores.documents.list({ parent: 'fileSearchStores/myfilesearchstore123' }); for await (const doc of documents) { console.log(doc); } const fileSearchDocument = await ai.fileSearchStores.documents.get({ name: 'fileSearchStores/myfilesearchstore123/documents/sampletxt123' }); await ai.fileSearchStores.documents.delete({ name: 'fileSearchStores/myfilesearchstore123/documents/sampletxt123', config: { force: true } });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/myfilesearchstore123/documents?key=${GEMINI_API_KEY}\"\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/myfilesearchstore123/documents/sampletxt123?key=${GEMINI_API_KEY}\"\n\ncurl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/myfilesearchstore123/documents/sampletxt123?key=${GEMINI_API_KEY}&force=true\"` File metadata You can add custom metadata to your files to help filter them or provide\nadditional context. Metadata is a set of key-value pairs. Python`op = client.file_search_stores.import_file( file_search_store_name=file_search_store.name, file_name=sample_file.name, config={ 'custom_metadata': [ {\"key\": \"author\", \"string_value\": \"Robert Graves\"}, {\"key\": \"year\", \"numeric_value\": 1934} ] } )` JavaScript`let operation = await ai.fileSearchStores.importFile({ fileSearchStoreName: fileSearchStore.name, fileName: sampleFile.name, config: { customMetadata: [ { key: \"author\", stringValue: \"Robert Graves\" }, { key: \"year\", numericValue: 1934 } ] } });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` This is useful when you have multiple documents in a File Search store and want\nto search only a subset of them. Python`interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Tell me about the book 'I, Claudius'\", tools=[{ \"type\": \"file_search\", \"file_search_store_names\": [file_search_store.name], \"metadata_filter\": 'author=\"Robert Graves\"', }] ) for step in interaction.steps: if step.type == \"model_output\": for content_block in step.content: if content_block.type == \"text\": print(content_block.text)` JavaScript`const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Tell me about the book 'I, Claudius'\", tools: [{ type: \"file_search\", file_search_store_names: [fileSearchStore.name], metadata_filter: 'author=\"Robert Graves\"', }] }); for (const step of interaction.steps) { if (step.type === 'model_output') { for (const contentBlock of step.content) { if (contentBlock.type === 'text') { console.log(contentBlock.text); } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [{\"type\": \"text\", \"text\": \"Tell me about the book I, Claudius\"}], \"tools\": [{ \"type\": \"file_search\", \"file_search_store_names\": [\"'$STORE_NAME'\"], \"metadata_filter\": \"author = \\\"Robert Graves\\\"\" }] }' 2> /dev/null > response.json\n\ncat response.json` Guidance on implementing list filter syntax for `metadata_filter` can be found\nat [google.aip.dev/160](https://google.aip.dev/160) Multimodal File Search Multimodal File Search lets you to natively embed and search through images,\nenabling rich, multimodal RAG applications. Configure the embedding model When you create a `FileSearchStore`, you must override the default text-only\nembedding model to use a multimodal model. Use `models/gemini-embedding-2` to\nprocess both text and images. Python`store = client.file_search_stores.create( config={ \"display_name\": \"Multimodal Catalog\", \"embedding_model\": \"models/gemini-embedding-2\", } )` JavaScript`const fileSearchStore = await ai.fileSearchStores.create({ config: { displayName: \"Multimodal Catalog\", embeddingModel: \"models/gemini-embedding-2\", }, });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=$GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"display_name\": \"Multimodal Catalog\", \"embedding_model\": \"models/gemini-embedding-2\" }'` Upload images After you create the store with a multimodal embedding model, you can upload\nimage files directly using the same upload APIs described in\nDirectly upload to File Search store or Importing files. **Image file requirements:** Image files must be at most 4K x 4K pixels in resolution. Supported formats are PNG, JPEG. Citations When you use File Search, the model's response may include citations that\nspecify which parts of your uploaded documents were used to generate the\nanswer. This helps with fact-checking and verification. You can access citation information through the `annotations` attribute inside the `model_output` step's `content` blocks of the response. Python`for step in interaction.steps: if step.type == 'model_output': for content in step.content: if content.type == 'text' and content.annotations: print(content.annotations)` JavaScript`for (const step of interaction.steps) { if (step.type === 'model_output') { for (const contentBlock of step.content) { if (contentBlock.type === 'text' && contentBlock.annotations) { console.log(JSON.stringify(contentBlock.annotations, null, 2)); } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`{ \"steps\": [ { \"type\": \"model_output\", \"content\": [ { \"type\": \"text\", \"text\": \"...\", \"annotations\": [ { \"type\": \"file_citation\", \"file_name\": \"sample.txt\", \"source\": \"...\" } ] } ] } ] }` For detailed information on the structure of the citations, see the\n[API reference for Interactions](/api/interactions-api#Resource:FileCitation). Page numbers When you use File Search with documents that have pages (such as PDFs), the\nmodel's response may include the page number where the information was found.\nYou can access this information through the `page_number` attribute of a\n`file_citation` annotation. Python`for step in interaction.steps: if step.type == \"model_output\": for content in step.content: if content.type == \"text\" and content.annotations: for annotation in content.annotations: if annotation.type == \"file_citation\" and annotation.page_number: print(f\"Cited Page: {annotation.page_number}\")` JavaScript`for (const step of interaction.steps) { if (step.type === 'model_output') { for (const block of step.content) { if (block.type === 'text' && block.annotations) { for (const annotation of block.annotations) { if (annotation.type === 'file_citation' && annotation.pageNumber) { console.log(`Cited Page: ${annotation.pageNumber}`); } } } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`{ \"steps\": [ { \"type\": \"model_output\", \"content\": [ { \"type\": \"text\", \"text\": \"...\", \"annotations\": [ { \"type\": \"file_citation\", \"file_name\": \"document.pdf\", \"page_number\": 1, \"source\": \"...\" } ] } ] } ] }` Media citations When the model references an image chunk during generation, the API returns an\nannotation of type `file_citation` in the annotations that includes a `media_id`. You can use this\nID to download the exact image chunk the model referenced. This `media_id` is\npersistent across multiple search calls, which lets you reliably retrieve\nthe same image or cache it using the ID. The following snippet is an example REST response step: `{ \"type\": \"model_output\", \"content\": [ { \"type\": \"text\", \"text\": \"...\", \"annotations\": [ { \"type\": \"file_citation\", \"file_name\": \"product_image\", \"media_id\": \"fileSearchStores/my-store-123/media/BlobId-456\" } ] } ] }` The following code snippets demonstrate how to retrieve the `media_id` and\ndownload the media: Python`for step in interaction.steps: if step.type == \"model_output\": for content in step.content: if content.type == \"text\" and content.annotations: for annotation in content.annotations: if annotation.type == \"file_citation\" and annotation.media_id: print(f\"Cited Media ID: {annotation.media_id}\") blob_content = client.file_search_stores.download_media( media_id=annotation.media_id )` JavaScript`for (const step of interaction.steps) { if (step.type === 'model_output') { for (const block of step.content) { if (block.type === 'text' && block.annotations) { for (const annotation of block.annotations) { if (annotation.type === 'file_citation' && annotation.mediaId) { console.log(`Cited Media ID: ${annotation.mediaId}`); const blobContent = await ai.fileSearchStores.downloadMedia(annotation.mediaId); } } } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1/fileSearchStores/my-store-123/media/BlobId-456\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Custom metadata If you have added custom metadata to your files, you can access it in the\nannotations of the model's response. This is useful for passing\nadditional context (like URLs, page numbers, or authors) from your source\ndocuments to your application logic. Each citation annotation of type `file_citation`\ncontains this custom metadata. Python`interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Tell me about [insert question]\", tools=[{ \"type\": \"file_search\", \"file_search_store_names\": [file_search_store.name] }] ) for step in interaction.steps: if step.type == \"model_output\": for content_block in step.content: if content_block.annotations: for annotation in content_block.annotations: print(annotation)` JavaScript`const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Tell me about [insert question]\", tools: [{ type: \"file_search\", file_search_store_names: [fileSearchStore.name] }] }); for (const step of interaction.steps) { if (step.type === 'model_output') { for (const contentBlock of step.content) { if (contentBlock.annotations) { contentBlock.annotations.forEach((annotation) => { console.log(annotation); }); } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`{ \"steps\": [ { \"type\": \"model_output\", \"content\": [ { \"type\": \"text\", \"text\": \"...\", \"annotations\": [ { \"file_name\": \"...\", \"source\": \"...\", \"custom_metadata\": [ { \"key\": \"author\", \"string_value\": \"Robert Graves\" }, { \"key\": \"year\", \"numeric_value\": 1934 } ] } ] } ] } ] }` Structured output Starting with Gemini 3 models, you can combine file search tool with\n[structured outputs](/gemini-api/docs/structured-output). Python`from pydantic import BaseModel, Field class Money(BaseModel): amount: str = Field(description=\"The numerical part of the amount.\") currency: str = Field(description=\"The currency of amount.\") interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What is the minimum hourly wage in Tokyo right now?\", tools=[{ \"type\": \"file_search\", \"file_search_store_names\": [file_search_store.name] }], response_format={ \"type\": \"text\", \"mime_type\": \"application/json\", \"schema\": Money.model_json_schema() }, ) result = Money.model_validate_json(interaction.output_text) print(result)` JavaScript`import { z } from \"zod\"; const moneyJsonSchema = { type: \"object\", properties: { amount: { type: \"string\", description: \"The numerical part of the amount.\" }, currency: { type: \"string\", description: \"The currency of amount.\" } }, required: [\"amount\", \"currency\"] }; const moneySchema = z.fromJSONSchema(moneyJsonSchema); async function run() { const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"What is the minimum hourly wage in Tokyo right now?\", tools: [{ type: \"file_search\", file_search_store_names: [fileSearchStore.name], }], response_format: { type: 'text', mime_type: 'application/json', schema: moneyJsonSchema }, }); const result = moneySchema.parse(JSON.parse(interaction.output_text)); console.log(result); } run();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.Content; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.DocumentContent; import com.google.genai.gaos.models.interactions.DocumentContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.List; Client client = new Client(); Content textContent = TextContent.builder().text(\"Summarize this document.\").build(); Content docContent = DocumentContent.builder() .uri(\"gs://cloud-samples-data/generative-ai/pdf/sample.pdf\") .mimeType(DocumentContentMimeType.APPLICATION_PDF) .build(); List contents = Arrays.asList(textContent, docContent); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.ofContent(contents)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the minimum hourly wage in Tokyo right now?\", \"tools\": [{ \"type\": \"file_search\", \"file_search_store_names\": [\"$FILE_SEARCH_STORE_NAME\"] }], \"response_format\": { \"type\": \"text\", \"mime_type\": \"application/json\", \"schema\": { \"type\": \"object\", \"properties\": { \"amount\": {\"type\": \"string\", \"description\": \"The numerical part of the amount.\"}, \"currency\": {\"type\": \"string\", \"description\": \"The currency of amount.\"} }, \"required\": [\"amount\", \"currency\"] } } }'` Supported models The following models support File Search: Model File Search [Gemini 3.8 Flash](/gemini-api/docs/models/gemini-3.8-flash) ✔️ [Gemini 3.7 Flash](/gemini-api/docs/models/gemini-3.7-flash) ✔️ [Gemini 3.6 Flash](/gemini-api/docs/models/gemini-3.6-flash) ✔️ [Gemini 3.5 Flash-Lite](/gemini-api/docs/models/gemini-3.5-flash-lite) ✔️ [Gemini 3.5 Flash](/gemini-api/docs/models/gemini-3.5-flash) ✔️ [Gemini 3.1 Pro Preview](/gemini-api/docs/models/gemini-3.1-pro-preview) ✔️ [Gemini 3.1 Flash-Lite](/gemini-api/docs/models/gemini-3.1-flash-lite) ✔️ [Gemini 3 Flash Preview](/gemini-api/docs/models/gemini-3-flash-preview) ✔️ Supported file types File Search supports a wide range of file formats, listed in the following\nsections. Application file types `application/dart` `application/ecmascript` `application/json` `application/ms-java` `application/msword` `application/pdf` `application/sql` `application/typescript` `application/vnd.curl` `application/vnd.dart` `application/vnd.ibm.secure-container` `application/vnd.jupyter` `application/vnd.ms-excel` `application/vnd.oasis.opendocument.text` `application/vnd.openxmlformats-officedocument.presentationml.presentation` `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` `application/vnd.openxmlformats-officedocument.wordprocessingml.document` `application/vnd.openxmlformats-officedocument.wordprocessingml.template` `application/x-csh` `application/x-hwp` `application/x-hwp-v5` `application/x-latex` `application/x-php` `application/x-powershell` `application/x-sh` `application/x-shellscript` `application/x-tex` `application/x-zsh` `application/xml` `application/zip` Text file types `text/1d-interleaved-parityfec` `text/RED` `text/SGML` `text/cache-manifest` `text/calendar` `text/cql` `text/cql-extension` `text/cql-identifier` `text/css` `text/csv` `text/csv-schema` `text/dns` `text/encaprtp` `text/enriched` `text/example` `text/fhirpath` `text/flexfec` `text/fwdred` `text/gff3` `text/grammar-ref-list` `text/hl7v2` `text/html` `text/javascript` `text/jcr-cnd` `text/jsx` `text/markdown` `text/mizar` `text/n3` `text/parameters` `text/parityfec` `text/php` `text/plain` `text/provenance-notation` `text/prs.fallenstein.rst` `text/prs.lines.tag` `text/prs.prop.logic` `text/raptorfec` `text/rfc822-headers` `text/rtf` `text/rtp-enc-aescm128` `text/rtploopback` `text/rtx` `text/sgml` `text/shaclc` `text/shex` `text/spdx` `text/strings` `text/t140` `text/tab-separated-values` `text/texmacs` `text/troff` `text/tsv` `text/tsx` `text/turtle` `text/ulpfec` `text/uri-list` `text/vcard` `text/vnd.DMClientScript` `text/vnd.IPTC.NITF` `text/vnd.IPTC.NewsML` `text/vnd.a` `text/vnd.abc` `text/vnd.ascii-art` `text/vnd.curl` `text/vnd.debian.copyright` `text/vnd.dvb.subtitle` `text/vnd.esmertec.theme-descriptor` `text/vnd.exchangeable` `text/vnd.familysearch.gedcom` `text/vnd.ficlab.flt` `text/vnd.fly` `text/vnd.fmi.flexstor` `text/vnd.gml` `text/vnd.graphviz` `text/vnd.hans` `text/vnd.hgl` `text/vnd.in3d.3dml` `text/vnd.in3d.spot` `text/vnd.latex-z` `text/vnd.motorola.reflex` `text/vnd.ms-mediapackage` `text/vnd.net2phone.commcenter.command` `text/vnd.radisys.msml-basic-layout` `text/vnd.senx.warpscript` `text/vnd.sosi` `text/vnd.sun.j2me.app-descriptor` `text/vnd.trolltech.linguist` `text/vnd.wap.si` `text/vnd.wap.sl` `text/vnd.wap.wml` `text/vnd.wap.wmlscript` `text/vtt` `text/wgsl` `text/x-asm` `text/x-bibtex` `text/x-boo` `text/x-c` `text/x-c++hdr` `text/x-c++src` `text/x-cassandra` `text/x-chdr` `text/x-coffeescript` `text/x-component` `text/x-csh` `text/x-csharp` `text/x-csrc` `text/x-cuda` `text/x-d` `text/x-diff` `text/x-dsrc` `text/x-emacs-lisp` `text/x-erlang` `text/x-gff3` `text/x-go` `text/x-haskell` `text/x-java` `text/x-java-properties` `text/x-java-source` `text/x-kotlin` `text/x-lilypond` `text/x-lisp` `text/x-literate-haskell` `text/x-lua` `text/x-moc` `text/x-objcsrc` `text/x-pascal` `text/x-pcs-gcd` `text/x-perl` `text/x-perl-script` `text/x-python` `text/x-python-script` `text/x-r-markdown` `text/x-rsrc` `text/x-rst` `text/x-ruby-script` `text/x-rust` `text/x-sass` `text/x-scala` `text/x-scheme` `text/x-script.python` `text/x-scss` `text/x-setext` `text/x-sfv` `text/x-sh` `text/x-siesta` `text/x-sos` `text/x-sql` `text/x-swift` `text/x-tcl` `text/x-tex` `text/x-vbasic` `text/x-vcalendar` `text/xml` `text/xml-dtd` `text/xml-external-parsed-entity` `text/yaml` Limitations **Live API:** File Search is not supported in the\n[Live API](/gemini-api/docs/live). **Tool incompatibility:** Built-in grounding tools cannot be combined with one another;\nfor example, File Search cannot be used simultaneously with [Grounding with Google Search](/gemini-api/docs/google-search) or\n[URL Context](/gemini-api/docs/url-context) in the same request. Rate limits The File Search API has the following limits to enforce service stability: **Maximum file size / per document limit**: 100 MB **Total size of project File Search stores** (based on user tier):\n **Free**: 1 GB **Tier 1**: 10 GB **Tier 2**: 100 GB **Tier 3**: 1 TB **Recommendation**: Limit the size of each File Search store to under 20 GB to ensure optimal retrieval latencies. Pricing You are charged for embeddings at indexing time based on existing\n[embeddings pricing](/gemini-api/docs/pricing#gemini-embedding-2). Storage is free of charge. Query time embeddings are free of charge. Retrieved document tokens are charged as regular\n[context tokens](/gemini-api/docs/tokens). What's next Visit the API reference for [File Search Stores](/api/file-search/file-search-stores) and File Search [Documents](/api/file-search/documents). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 51962, "slov": 4896, "odkazu": 147, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:14", "sha256": "84a3f8ebd0d09868268f3125768a98e26324b03c1f463a40c8bf1de5ff4194d5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://google.aip.dev/160", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/files", "titulek": "Files API | Gemini API | Google AI for Developers", "h1": "Files API", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/files", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Files API  |  Gemini API  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/files", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Files API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Files API", "item": "https://ai.google.dev/gemini-api/docs/files"}]}], "drobecky": ["Gemini API", "Files API"], "osnova": [{"uroven": 1, "text": "Files API"}, {"uroven": 2, "text": "Upload a file"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Get metadata for a file"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "List uploaded files"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Delete uploaded files"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Usage information"}, {"uroven": 2, "text": "File prompting strategies"}, {"uroven": 3, "text": "Prompt design fundamentals"}, {"uroven": 3, "text": "Troubleshooting your multimodal prompt"}, {"uroven": 3, "text": "Be specific in your instructions"}, {"uroven": 3, "text": "Add a few examples"}, {"uroven": 3, "text": "Break it down step-by-step"}, {"uroven": 3, "text": "Specify the output format"}, {"uroven": 3, "text": "Put your image first for single-image prompts"}, {"uroven": 3, "text": "Troubleshooting your multimodal prompt"}, {"uroven": 4, "text": "If the model is not drawing information from the relevant part of the image"}, {"uroven": 4, "text": "If the model output is too generic and not tailored enough to the image input"}, {"uroven": 4, "text": "Troubleshooting which part of the prompt failed"}, {"uroven": 2, "text": "What's next"}], "markdown": "Files API Gemini can handle various types of input data, including text, images, and\naudio, at the same time. This guide shows you how to work with media files using the Files API. The\nbasic operations are the same for audio files, images, videos, documents, and\nother supported file types. For file prompting guidance, check out the [File prompt guide](/gemini-api/docs/files#prompt-guide) section. Upload a file You can use the Files API to upload a media file. Always use the Files API when\nthe total request size (including the files, text prompt, system instructions,\netc.) is larger than 100 MB. For PDF files, the limit is 50 MB. The following code uploads a file and then uses the file in a call to\n`interactions.create`. Python`from google import genai client = genai.Client() myfile = client.files.upload(file=\"path/to/sample.mp3\") interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ {\"type\": \"text\", \"text\": \"Describe this audio clip\"}, {\"type\": \"audio\", \"uri\": myfile.uri, \"mime_type\": myfile.mime_type} ] ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); async function main() { const myfile = await client.files.upload({ file: \"path/to/sample.mp3\", config: { mime_type: \"audio/mpeg\" }, }); const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: [ { type: \"text\", text: \"Describe this audio clip\" }, { type: \"audio\", uri: myfile.uri, mime_type: myfile.mimeType } ] }); console.log(interaction.output_text); } await main();` Java`import com.google.genai.Client; import com.google.genai.types.File; import com.google.genai.types.UploadFileConfig; Client client = new Client(); File file = client.files.upload( new java.io.File(\"path/to/sample.txt\"), UploadFileConfig.builder().mimeType(\"text/plain\").build() ); System.out.println(\"Uploaded file URI: \" + file.uri().orElse(\"\"));` Go`file, err := client.Files.UploadFromPath(ctx, \"path/to/sample.mp3\", nil) if err != nil { log.Fatal(err) } defer client.Files.Delete(ctx, file.Name) interaction, err := client.Interactions.Create(ctx, \"gemini-3.8-flash\", &genai.InteractionRequest{ Input: []interface{}{ genai.NewPartFromFile(*file), genai.NewPartFromText(\"Describe this audio clip\"), }, }, nil) if err != nil { log.Fatal(err) } // Print the model's text response for _, step := range interaction.Steps { if step.Type == \"model_output\" { for _, part := range step.Content { if part.Type == \"text\" { fmt.Println(part.Text) } } } }` REST`AUDIO_PATH=\"path/to/sample.mp3\" MIME_TYPE=$(file -b --mime-type \"${AUDIO_PATH}\") NUM_BYTES=$(wc -c < \"${AUDIO_PATH}\") DISPLAY_NAME=AUDIO\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"${BASE_URL}/upload/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -D \"${tmp_header_file}\" \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${AUDIO_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) echo file_uri=$file_uri # Now create an interaction using the Interactions API\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": [ {\"type\": \"text\", \"text\": \"Describe this audio clip\"}, {\"type\": \"audio\", \"uri\": '$file_uri', \"mime_type\": \"'${MIME_TYPE}'\"} ] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".outputs[] | select(.type == \\\"text\\\") | .text\" response.json` Get metadata for a file You can verify that the API successfully stored the uploaded file and get its\nmetadata by calling `files.get`. Python`from google import genai client = genai.Client() myfile = client.files.upload(file='path/to/sample.mp3') file_name = myfile.name myfile = client.files.get(name=file_name) print(myfile)` JavaScript`import { GoogleGenAI, } from \"@google/genai\"; const client = new GoogleGenAI({}); async function main() { const myfile = await client.files.upload({ file: \"path/to/sample.mp3\", config: { mime_type: \"audio/mpeg\" }, }); const fileName = myfile.name; const fetchedFile = await client.files.get({ name: fileName }); console.log(fetchedFile); } await main();` Java`import com.google.genai.Client; import com.google.genai.types.File; import com.google.genai.types.UploadFileConfig; Client client = new Client(); File file = client.files.upload( new java.io.File(\"path/to/sample.txt\"), UploadFileConfig.builder().mimeType(\"text/plain\").build() ); System.out.println(\"Uploaded file URI: \" + file.uri().orElse(\"\"));` Go`file, err := client.Files.UploadFromPath(ctx, \"path/to/sample.mp3\", nil) if err != nil { log.Fatal(err) } gotFile, err := client.Files.Get(ctx, file.Name) if err != nil { log.Fatal(err) } fmt.Println(\"Got file:\", gotFile.Name)` REST`# file_info.json was created in the upload example name=$(jq -r \".file.name\" file_info.json) # Get the file of interest to check state\ncurl https://generativelanguage.googleapis.com/v1beta/$name \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" > file_info.json\n# Print some information about the file you got name=$(jq -r \".name\" file_info.json) echo name=$name file_uri=$(jq -r \".uri\" file_info.json) echo file_uri=$file_uri` List uploaded files The following code gets a list of all the files uploaded: Python`from google import genai client = genai.Client() print('My files:') for f in client.files.list(): print(' ', f.name)` JavaScript`import { GoogleGenAI, } from \"@google/genai\"; const client = new GoogleGenAI({}); async function main() { const listResponse = await client.files.list({ config: { pageSize: 10 } }); for await (const file of listResponse) { console.log(file.name); } } await main();` Java`import com.google.genai.Client; import com.google.genai.types.File; import com.google.genai.types.UploadFileConfig; Client client = new Client(); File file = client.files.upload( new java.io.File(\"path/to/sample.txt\"), UploadFileConfig.builder().mimeType(\"text/plain\").build() ); System.out.println(\"Uploaded file URI: \" + file.uri().orElse(\"\"));` Go`for file, err := range client.Files.All(ctx) { if err != nil { log.Fatal(err) } fmt.Println(file.Name) }` REST`echo \"My files: \"\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Delete uploaded files Files are automatically deleted after 48 hours. You can also manually delete an\nuploaded file: Python`from google import genai client = genai.Client() myfile = client.files.upload(file='path/to/sample.mp3') client.files.delete(name=myfile.name)` JavaScript`import { GoogleGenAI, } from \"@google/genai\"; const client = new GoogleGenAI({}); async function main() { const myfile = await client.files.upload({ file: \"path/to/sample.mp3\", config: { mime_type: \"audio/mpeg\" }, }); const fileName = myfile.name; await client.files.delete({ name: fileName }); } await main();` Java`import com.google.genai.Client; import com.google.genai.types.File; import com.google.genai.types.UploadFileConfig; Client client = new Client(); File file = client.files.upload( new java.io.File(\"path/to/sample.txt\"), UploadFileConfig.builder().mimeType(\"text/plain\").build() ); System.out.println(\"Uploaded file URI: \" + file.uri().orElse(\"\"));` Go`file, err := client.Files.UploadFromPath(ctx, \"path/to/sample.mp3\", nil) if err != nil { log.Fatal(err) } client.Files.Delete(ctx, file.Name)` REST`curl --request \"DELETE\" https://generativelanguage.googleapis.com/v1beta/$name \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Usage information You can use the Files API to upload and interact with media files. The Files API\nlets you store up to 20 GB of files per project, with a per-file maximum\nsize of 2 GB. Files are stored for 48 hours. During that time, you can use the API to get metadata about the files. However,\nyou can't download user-uploaded files. You can download files generated by\nmodels, such as videos, using the `files.download` method. The Files API is\navailable at no cost in all regions where the Gemini API is available. File prompting strategies This section provides guidance and best practices for using media files with\nprompts for the Gemini API. Being able to use various types of data in your prompts gives you more\nflexibility in terms of what tasks you can tackle with the Gemini API. For\nexample, you can send the model a photo of a delicious meal and ask it to write\na short blog about the meal. **Prompt** **Response** Write a short, engaging blog post based on this picture. It should\n include a description of the meal in the photo and talk about my journey\n meal prepping. \n Meal prepping is a great way to save time and money, and it can also\n help you to eat healthier. This meal is a great example of a healthy\n and delicious meal that can be prepped ahead of time. This meal features brown rice, roasted vegetables, and chicken teriyaki.\n The brown rice is a healthy and complex carbohydrate that will give you\n sustained energy. The roasted vegetables are a great way to get your daily\n dose of vitamins and minerals, and the chicken teriyaki is a delicious and\n protein-rich option. This meal is also straightforward to prepare. Simply cook the brown rice, roast\n the vegetables, and cook the chicken teriyaki. Once everything is cooked,\n divide it into meal prep containers and store them in the refrigerator.\n You can then grab a container and go on busy mornings! If you're looking for a healthy and delicious meal that can be\n prepped ahead of time, this meal is a great option. It's packed with\n nutrients and flavor, and it's sure to keep you feeling full and satisfied. Here's to healthy and delicious meal prepping! If you are having trouble getting the output you want from prompts that use\nmedia files, there are some strategies that can help you get the results you\nwant. The following sections provide design approaches and troubleshooting\ntips for improving prompts that use multimodal input. You can improve your multimodal prompts by following these best practices: Prompt design fundamentals **Be specific in your instructions**: Craft clear and concise instructions that leave minimal room for misinterpretation. **Add a few examples to your prompt:** Use realistic few-shot examples to illustrate what you want to achieve. **Break it down step-by-step**: Divide complex tasks into manageable sub-goals, guiding the model through the process. **Specify the output format**: In your prompt, ask for the output to be in the format you want, like Markdown, JSON, HTML and more. **Put your image first for single-image prompts**: While Gemini can handle image and text inputs in any order, for prompts containing a single image, it might perform better if that image (or video) is placed before the text prompt. However, for prompts that require images to be highly interleaved with texts to make sense, use whatever order is most natural. Troubleshooting your multimodal prompt **If the model is not drawing information from the relevant part of the image:** Drop hints with which aspects of the image you want the prompt to draw information from. **If the model output is too generic (not tailored enough to the image/video input):**At the start of the prompt, try asking the model to describe the image(s) or video before providing the task instruction, or try asking the model to refer to what's in the image. **To troubleshoot which part failed:** Ask the model to describe the image, or ask the model to explain its reasoning, to gauge the model's initial understanding. **If your prompt results in hallucinated content:** Try dialing down the temperature setting or asking the model for shorter descriptions so that it's less likely to extrapolate additional details. **Tuning the sampling parameters:** Experiment with different temperature settings and top-k selections to adjust the model's creativity.\n\n Be specific in your instructions Prompts have the most success when they are clear and detailed. If you have a\nspecific output in mind, it's better to include that requirement in the prompt\nto ensure you get the output you want. For this image of an airport board, asking the model to just \"describe this\nimage\" could generate a general description. If you need the model to parse the\ntime and city from the image, you can include that request directly in your\nprompt. Prompt Model response Describe this image. The image shows an airport arrivals and departures board. **Updated prompt** **Improved response** Parse the time and city from the airport board shown in this image into a list. 10:50 Moscow 11:05 Edinburgh 11:05 London 11:10 Bucharest 11:30 Kiev 11:35 Dublin 11:45 East Midlands 12:15 Sofia 12:30 London 12:30 Newcastle 12:40 St Petersburg 12:40 London 12:45 Manchester Add a few examples The Gemini model can accept multiple inputs which it can use as examples to\nunderstand the output you want. Adding these examples can help the model\nidentify the patterns and apply the relationship between the given images and\nresponses to the new example. This is also called \"few-shot\" learning. In the following example, the initial output is written in sentence form,\nand also contains the country (Brazil). Suppose you want the output in a\ndifferent format or style, and you want only the city, not the country. Adding\nfew-shot examples to your prompt can steer the model to respond in the way you\nwant. **Prompt** **Model response** Determine the city along with the landmark. The landmark is the Christ the Redeemer statue in Rio de Janeiro, Brazil. **Updated prompt** **Improved response** Determine the city along with the landmark. city: Rome, landmark: the Colosseum. city: Beijing, landmark: Forbidden City city: Rio de Janeiro, landmark: Christ the Redeemer statue Break it down step-by-step For complex tasks like the ones that require both visual understanding and\nreasoning, it can be helpful to split the task into smaller, more\nstraightforward steps. Alternatively, it could also be effective if you\ndirectly ask the model to \"think step by step\" in your prompt. Prompt Model response When will I run out of toilet paper? Soon, you only have 3 rolls left. **Updated prompt** **Improved response** First, count how many toilet paper rolls are in this picture. Then, determine how much toilet paper a typical person uses per day. Calculate how long these rolls of toilet paper will last. There are 3 rolls of toilet paper in this picture. A typical person uses about 20 sheets of toilet paper per day. If each roll contains 200 sheets, then each roll will last for about 10 days. Therefore, the 3 rolls will last for about a month. Math problems or other types of word problems are great candidates for asking\nthe model to think step-by-step. **Prompt** **Response** What is the 4th term in the sequence? -135\n The response from the model is incorrect. Some ways to improve this is to ask\nthe model to parse the problem before answering the prompt. **Prompt** **Response** Parse the formula in the image first. Then based on the formula, answer \"what's the 4th term in the sequence?\". *Click to expand the result* $$ b(n) = b(n-1) * (-3) $$ $$ b(1) = 15 $$ Substitute n = 4 into the formula:\n$$ b(4) = b(4-1) * (-3) $$ $$ b(4) = b(3) * (-3) $$ We don't know the value of b(3), so substitute n = 3 into the formula:\n$$ b(3) = b(3-1) * (-3) $$ $$ b(3) = b(2) * (-3) $$ We don't know the value of b(2), so substitute n = 2 into the formula:\n$$ b(2) = b(2-1) * (-3) $$ $$ b(2) = b(1) * (-3) $$ We know the value of b(1) is 15, so substitute it into the formula:\n$$ b(2) = 15 * (-3) $$ $$ b(2) = -45 $$ Now that we know the value of b(2), substitute it into the formula for b(3):\n$$ b(3) = b(2) * (-3) $$ $$ b(3) = -45 * (-3) $$ $$ b(3) = 135 $$ Now that we know the value of b(3), substitute it into the formula for b(4):\n$$ b(4) = b(3) * (-3) $$ $$ b(4) = 135 * (-3) $$ $$ b(4) = -405 $$ Therefore, the 4th term in the sequence is -405. This model response is correct - now to make the response even more streamlined,\nyou can ask the model to to think step-by-step. **Updated prompt** **Improved response** What is the 4th term in the sequence? Think step by step. The first term is 15. The second term is b(1) * (-3) = 15 * (-3) = -45. The third term is b(2) * (-3) = -45 * (-3) = 135. The fourth term is b(3) * (-3) = 135 * (-3) = -405. Specify the output format A common problem is the need for model output to be in a certain format\n(e.g. Markdown, JSON, HTML), especially if the model output needs to\nbe ingested by a downstream task. You can try to produce output in that format\nby instructing the model to do so within the prompt. The following are two\nexamples: Prompt Model response Parse the table in this image into Markdown format \n\n```none\n| Subject | Status | Time | Start date | Due on |\n| ------- | ------ | ---- | ---------- | ------ |\n| Math | Done | 1.5 hrs | 11/29/2023 | 12/1/2023 |\n| Geography | Done | 30 min | 12/2/2023 | 12/4/2023 |\n| Physics | In progress | 2 hrs | 12/3/2023 | 12/5/2023 |\n| Biology | Not started | 6 hrs | 11/2/2016 | 12/6/2023 |\n```\n\n **Prompt** **Model response** Provide a list of all the following attributes: ingredients, type of cuisine, vegetarian or not, in JSON format \n\n```json\n{\n\"ingredients\": [\n\"rice\",\n\"shrimp\",\n\"clams\",\n\"mussels\",\n\"peas\",\n\"tomatoes\",\n\"onions\",\n\"garlic\",\n\"olive oil\",\n\"paprika\",\n\"salt\",\n\"pepper\"\n],\n\"type of cuisine\": \"Spanish\",\n\"vegetarian\": false\n}\n```\n\n Put your image first for single-image prompts While Gemini can interpret image and text in any order within a prompt, placing\na single image before the text prompt might lead to better results.\nIn the following samples, you'll notice the image comes first before the text in\neach prompt. Troubleshooting your multimodal prompt You might need to troubleshoot your prompt if you are not getting a helpful\nresponse. Here are a few strategies you could try. If the model is not drawing information from the relevant part of the image To get a more specific response, you can point out which aspects of the image\nyou want the prompt to draw information from to inform its response. Prompt Model response How many days will these diapers last a baby? The diapers will last for 198 days before they run out. **Updated prompt** **Improved response** How long will these diapers last before I run out? Use the weight shown on the box to determine the child's age, and use the total number of diapers in the box. Divide the total number by how many diapers the child goes through per day. The box contains 198 diapers. The box states the diapers are for a child weighing 22-37 lbs. The average child in this weight range is likely between 1 and 2 years old. A 2-year-old typically goes through 6 diapers per day, therefore, the diapers will last around 33 days (198/6). If the model output is too generic and not tailored enough to the image input To help the model tailor its response to the image(s), try asking it to describe\nthe images before performing its reasoning task. Prompt Model response What is in common between these images? All four images are examples of landscape photography. **Updated prompt** **Improved response** First, describe what's in each image in detail. What's in common between these images? The first image shows a person packing a suitcase. The second image shows an empty hallway in a shopping mall. The third image shows a roll of toilet paper. The fourth image shows a dark and stormy sea. The commonality between these images is that they are all examples of liminal spaces. Liminal spaces are places or situations that are in between two other places or situations. They are often characterized by a sense of uncertainty or ambiguity. The first image shows the person in between being at home and being on a trip. The second image shows the hallway in between two stores. The third image is of toilet paper, which can represent a bathroom. A bathroom is a transitional space between private\n and public realms. It's a place where we prepare ourselves to enter or leave the outside world. The fourth image shows the sea in between being calm and being stormy. Liminal spaces can be both exciting and unsettling. They can be a place of new beginning or a place of endings. They can be a place of reflection or a place of action. You can also try explicitly asking the model to refer to what's in the image. **Updated prompt** **Improved response** What is in common between these images? Refer to what's in the images in your response. All of the images are related to travel. The first image shows a person packing a suitcase, the second image shows\n an empty hallway in a shopping mall, the third image shows a stack of toilet paper, and the fourth image shows a\n dark and stormy sea. These images are all related to travel because they are all things that people need or use when\n they travel. The first image shows a person packing a suitcase, which is\n something that people do when they are going on a trip. The second image\n shows an empty hallway in a shopping mall, which is a place where people\n often go to buy things for their trips. The third image shows a stack of\n toilet paper, which is something that people often use when they are\n traveling. The fourth image shows a dark and stormy sea, which is\n something that people often encounter when they are traveling. The same tips work for creative output from images. In the following example with\nthe rabbit, explicitly asking the model to include aspects from the image can\nimprove the output. Prompt Model response Can you write me a poem about this image? Little bunny, so soft and brown,\n\n Hopping through the field, up and down.\n\n Your ears so long, your tail so small,\n\n You're the cutest creature of them all. You nibble on the grass, so green and sweet,\n\n And hop away when you see me.\n\n But I'll always be your friend,\n\n Little bunny, until the very end. **Updated prompt** **Improved response** Can you write me a descriptive and dramatic poem about this image and include the location? Little bunny on the green,\n\n Ears so long, so keen.\n\n What do you see out there,\n\n In the distance, where you stare? Is it the ocean blue,\n\n Sparkling in the sun's hue?\n\n Or the waves that crash and roar,\n\n A rhythm that you adore? Little bunny, tell me true,\n\n What captures your attention so?\n\n Is it the salty breeze,\n\n Or the seagulls' cries that please? Perhaps it's the vastness of it all,\n\n A world so big and small.\n\n A place where dreams can roam,\n\n And adventures can be sown. Little bunny, I wonder what you dream,\n\n As you sit on the grass, so serene.\n\n Do you yearn to explore the deep,\n\n Or stay on land, where you can leap? Whatever it may be, little bunny,\n\n Keep that spark of wonder burning brightly.\n\n For in your dreams and aspirations,\n\n Lies a world waiting for your creation. Troubleshooting which part of the prompt failed It can be hard to know whether a prompt failed because the model\ndidn't **understand the image** to begin with, or if it did understand the image\nbut did not perform the correct **reasoning steps** afterward.\nTo disambiguate between those reasons, ask the model to describe what's in the image. In the following example, if the model responds with a snack that seems surprising\nwhen paired with tea (e.g. popcorn), you can first troubleshoot to determine\nwhether the model correctly recognized that the image contains tea. Prompt Prompt for troubleshooting What's a snack I can make in 1 minute that would go well with this? Describe what's in this image. Another strategy is to ask the model to explain its reasoning. That can help you\nnarrow down which part of the reasoning broke down, if any. Prompt Prompt for troubleshooting What's a snack I can make in 1 minute that would go well with this? What's a snack I can make in 1 minute that would go well with this? Please explain why. What's next Try writing your own multimodal prompts using [Google AI\nStudio](http://aistudio.google.com). For information on using the Gemini Files API for\nuploading media files and including them in your prompts, see the\n[Vision](/gemini-api/docs/vision), [Audio](/gemini-api/docs/audio), and\n[Document processing](/gemini-api/docs/document-processing) guides. For more guidance on prompt design, like tuning sampling parameters, see the\n[Prompt strategies](/gemini-api/docs/prompting-strategies) page. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 24973, "slov": 3941, "odkazu": 132, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 20:12:35", "sha256": "8226ae919ddc62a586690e5c33bb10eb581ed6422a3bd9fc8c8fc88f50fdb16a", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "http://aistudio.google.com/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/flex-inference", "titulek": "Flex inference | Gemini API | Google AI for Developers", "h1": "Flex inference", "popis": "Learn how to optimize costs with the Flex inference tier in the Interactions API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/flex-inference", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Flex inference  |  Gemini API  |  Google AI for Developers", "og:description": "Learn how to optimize costs with the Flex inference tier in the Interactions API", "og:url": "https://ai.google.dev/gemini-api/docs/flex-inference", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Flex inference"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Flex inference", "item": "https://ai.google.dev/gemini-api/docs/flex-inference"}]}], "drobecky": ["Gemini API", "Flex inference"], "osnova": [{"uroven": 1, "text": "Flex inference"}, {"uroven": 2, "text": "How to use Flex"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How Flex inference works"}, {"uroven": 3, "text": "Key benefits"}, {"uroven": 3, "text": "Use cases"}, {"uroven": 3, "text": "Rate limits"}, {"uroven": 3, "text": "Sheddable capacity"}, {"uroven": 3, "text": "Error codes"}, {"uroven": 3, "text": "Client responsibility"}, {"uroven": 2, "text": "Adjust timeout windows"}, {"uroven": 3, "text": "Per-request timeouts"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Implement retries"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "Supported models"}, {"uroven": 2, "text": "What's next"}], "markdown": "Flex inference The Gemini Flex API is an inference tier that offers a 50% cost reduction\ncompared to standard rates, in exchange for variable latency and best-effort\navailability. It's designed for latency-tolerant workloads that require\nsynchronous processing but don't need the real-time performance of the standard\nAPI. How to use Flex To use the Flex tier, specify the `service_tier` as `flex` in your request. By default, requests use the standard tier if this field is omitted. Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Analyze this dataset for trends...\", service_tier='flex' ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); async function main() { const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Analyze this dataset for trends...', service_tier: 'flex' }); console.log(interaction.output_text); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.ServiceTier; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Process this batch job using Flex Tier.\")) .serviceTier(ServiceTier.FLEX) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Analyze this dataset for trends...\", \"service_tier\": \"flex\" }'` How Flex inference works Gemini Flex inference bridges the gap between the standard API and the 24-hour\nturnaround of the [Batch API](/gemini-api/docs/batch-api). It utilizes off-peak,\n\"sheddable\" compute capacity to provide a cost-effective solution for background\ntasks and sequential workflows. Feature Flex Priority Standard Batch **Pricing** 50% discount 75-100% more than Standard Full price 50% discount **Latency** Minutes (1–15 min target) Low (Seconds) Seconds to minutes Up to 24 hours **Reliability** Best-effort (Sheddable) High (Non-sheddable) High / Medium-high High (for throughput) **Interface** Synchronous Synchronous Synchronous Asynchronous Key benefits **Cost efficiency**: Substantial savings for non-production evals, background agents, and data enrichment. **Low friction**: Simply add a single parameter to your existing requests. **Synchronous workflows**: Ideal for sequential API chains where the next request depends on the output of the previous one, making it more flexible than Batch for agentic workflows. Use cases **Offline evaluations**: Running \"LLM-as-a-judge\" regression tests or leaderboards. **Background agents**: Sequential tasks like CRM updates, profile building, or content moderation where minutes of delay are acceptable. **Budget-constrained research**: Academic experiments that require high token volume on a limited budget. Rate limits Flex inference traffic counts towards your general [rate limits](https://aistudio.google.com/rate-limit); it doesn't\noffer extended rate limits like the [Batch API](/gemini-api/docs/batch-api). Sheddable capacity Flex traffic is treated with lower priority. If there is a spike in\nstandard traffic, Flex requests may be preempted or evicted to ensure capacity\nfor high-priority users. If you're looking for high-priority inference, check\n[Priority inference](/gemini-api/docs/priority-inference) Error codes When Flex capacity is unavailable or the system is congested, the API will\nreturn standard error codes: **503 Service Unavailable**: The system is currently at capacity. **429 Too Many Requests**: Rate limits or resource exhaustion. Client responsibility **No server-side fallback**: To prevent unexpected charges, the system won't\nautomatically upgrade a Flex request to the Standard tier if Flex capacity is\nfull. **Retries**: You must implement your own client-side retry logic with\nexponential backoff. **Timeouts**: Because Flex requests may sit in a queue, we recommend\nincreasing client-side timeouts to 10 minutes or more to avoid premature\nconnection closure. Adjust timeout windows You can configure per-request timeouts for the REST API and client libraries.\nAlways ensure your client-side timeout covers the intended server patience\nwindow (e.g., 600s+ for Flex wait queues). The SDKs expect timeout values in\nmilliseconds. Per-request timeouts Python`from google import genai client = genai.Client(http_options={\"timeout\": 900000}) interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"why is the sky blue?\", service_tier=\"flex\", )` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); async function main() { const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", input: \"why is the sky blue?\", service_tier: \"flex\", }, {timeout: 900000}); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.ServiceTier; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Process this batch job using Flex Tier.\")) .serviceTier(ServiceTier.FLEX) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Implement retries Because Flex is sheddable and fails with 503 errors, here is an example of\noptionally implementing retry logic to continue with failed requests: Python`import time from google import genai client = genai.Client() def call_with_retry(max_retries=3, base_delay=5): for attempt in range(max_retries): try: return client.interactions.create( model=\"gemini-3.8-flash\", input=\"Analyze this batch statement.\", service_tier=\"flex\", ) except Exception as e: if attempt < max_retries - 1: delay = base_delay * (2 ** attempt) # Exponential Backoff print(f\"Flex busy, retrying in {delay}s...\") time.sleep(delay) else: print(\"Flex exhausted, falling back to Standard...\") return client.interactions.create( model=\"gemini-3.8-flash\", input=\"Analyze this batch statement.\" ) interaction = call_with_retry() print(interaction.output_text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); async function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function callWithRetry(maxRetries = 3, baseDelay = 5) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { console.log(`Attempt ${attempt + 1}: Calling Flex tier...`); const interaction = await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Analyze this batch statement.\", service_tier: 'flex', }); return interaction; } catch (e) { if (attempt < maxRetries - 1) { const delay = baseDelay * (2 ** attempt); console.log(`Flex busy, retrying in ${delay}s...`); await sleep(delay * 1000); } else { console.log(\"Flex exhausted, falling back to Standard...\"); return await ai.interactions.create({ model: \"gemini-3.8-flash\", input: \"Analyze this batch statement.\", }); } } } } async function main() { const interaction = await callWithRetry(); console.log(interaction.output_text); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.ServiceTier; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; Client client = new Client(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"Process this batch job using Flex Tier.\")) .serviceTier(ServiceTier.FLEX) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` Pricing Flex inference is priced at 50% of the [standard API](/gemini-api/docs/pricing)\nand billed per token. Supported models The following models support Flex inference: Model Flex inference [Gemini 3.8 Flash](/gemini-api/docs/models/gemini-3.8-flash) ✔️ [Gemini 3.7 Flash](/gemini-api/docs/models/gemini-3.7-flash) ✔️ [Gemini 3.6 Flash](/gemini-api/docs/models/gemini-3.6-flash) ✔️ [Gemini 3.5 Flash-Lite](/gemini-api/docs/models/gemini-3.5-flash-lite) ✔️ [Gemini 3.5 Flash](/gemini-api/docs/models/gemini-3.5-flash) ✔️ [Gemini 3.1 Flash-Lite](/gemini-api/docs/models/gemini-3.1-flash-lite) ✔️ [Gemini 3.1 Pro Preview](/gemini-api/docs/models/gemini-3.1-pro-preview) ✔️ [Gemini 3 Flash Preview](/gemini-api/docs/models/gemini-3-flash-preview) ✔️ [Gemini 2.5 Pro](/gemini-api/docs/models/gemini-2.5-pro) ✔️ [Gemini 2.5 Flash](/gemini-api/docs/models/gemini-2.5-flash) ✔️ [Gemini 2.5 Flash-Lite](/gemini-api/docs/models/gemini-2.5-flash-lite) ✔️ What's next [Priority inference](/gemini-api/docs/priority-inference) for ultra-low latency. [Tokens](/gemini-api/docs/tokens): Understand tokens. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 10571, "slov": 1189, "odkazu": 140, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:58", "sha256": "2a96ec13c25d059636ded7ab0507baa093041a813f286e72a5c336ec13df4162", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://cloud.google.com/products", "https://aistudio.google.com/rate-limit", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/function-calling", "titulek": "Function calling with the Gemini API | Google AI for Developers", "h1": "Function calling with the Gemini API", "popis": "Get started using Function Calling with the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/function-calling", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Function calling with the Gemini API  |  Google AI for Developers", "og:description": "Get started using Function Calling with the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/function-calling", "og:image": "https://ai.google.dev/static/site-assets/images/function-calling.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Function calling with the Gemini API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Function calling with the Gemini API", "item": "https://ai.google.dev/gemini-api/docs/function-calling"}]}], "drobecky": ["Gemini API", "Function calling with the Gemini API"], "osnova": [{"uroven": 1, "text": "Function calling with the Gemini API"}, {"uroven": 3, "text": "Schedule Meeting"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Get Weather"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Create Chart"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How function calling works"}, {"uroven": 3, "text": "Step 1: Define a function declaration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 2: Call the model with function declarations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 3: Execute the function"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 4: Send result back to model"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Stateless function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function declarations"}, {"uroven": 2, "text": "Function calling with thinking models"}, {"uroven": 2, "text": "Parallel function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Compositional function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function calling modes"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multi-tool use"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multimodal function responses"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function calling with Structured output"}, {"uroven": 2, "text": "Remote MCP (Model Context Protocol)"}, {"uroven": 3, "text": "Example"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Stream tool calls"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Workarounds for pre-tool text requirements"}, {"uroven": 3, "text": "Preferred workaround: Wrap working notes in a dedicated function call"}, {"uroven": 2, "text": "Notes and limitations"}], "markdown": "Function calling with the Gemini API Function calling lets you connect models to external tools and APIs.\nInstead of generating text responses, the model determines when to call specific\nfunctions and provides the necessary parameters to execute real-world actions.\nThis allows the model to act as a bridge between natural language and real-world\nactions and data. Function calling has 3 primary use cases: **Take Actions:** Interact with external systems using APIs, such as\nscheduling appointments, creating invoices, sending emails, or controlling\nsmart home devices. **Augment Knowledge:** Access information from external sources like\ndatabases, APIs, and knowledge bases. **Extend Capabilities:** Use external tools to perform computations and\nextend the limitations of the model, such as using a calculator or creating\ncharts. You can browse examples of these use cases below: Schedule Meeting This example shows how to define a function that schedules a meeting with attendees at a specific time, allowing the model to parse user requests and return structured arguments to trigger actions in external systems. Python`from google import genai schedule_meeting_function = { \"type\": \"function\", \"name\": \"schedule_meeting\", \"description\": \"Schedules a meeting with specified attendees at a given time and date.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"attendees\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"date\": {\"type\": \"string\", \"description\": \"Date (e.g., '2024-07-29')\"}, \"time\": {\"type\": \"string\", \"description\": \"Time (e.g., '15:00')\"}, \"topic\": {\"type\": \"string\", \"description\": \"The meeting topic.\"}, }, \"required\": [\"attendees\", \"date\", \"time\", \"topic\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning.\", tools=[{\"type\": \"function\", **schedule_meeting_function}], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const scheduleMeetingFunction = { type: 'function', name: 'schedule_meeting', description: 'Schedules a meeting with specified attendees at a given time and date.', parameters: { type: 'object', properties: { attendees: { type: 'array', items: { type: 'string' } }, date: { type: 'string', description: 'Date (e.g., \"2024-07-29\")' }, time: { type: 'string', description: 'Time (e.g., \"15:00\")' }, topic: { type: 'string', description: 'The meeting topic.' }, }, required: ['attendees', 'date', 'time', 'topic'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.', tools: [scheduleMeetingFunction], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map attendeesProp = new HashMap<>(); attendeesProp.put(\"type\", \"array\"); Map itemsMap = new HashMap<>(); itemsMap.put(\"type\", \"string\"); attendeesProp.put(\"items\", itemsMap); Map dateProp = new HashMap<>(); dateProp.put(\"type\", \"string\"); dateProp.put(\"description\", \"Date (e.g., \\\"2024-07-29\\\")\"); Map timeProp = new HashMap<>(); timeProp.put(\"type\", \"string\"); timeProp.put(\"description\", \"Time (e.g., \\\"15:00\\\")\"); Map topicProp = new HashMap<>(); topicProp.put(\"type\", \"string\"); topicProp.put(\"description\", \"The meeting topic.\"); Map properties = new HashMap<>(); properties.put(\"attendees\", attendeesProp); properties.put(\"date\", dateProp); properties.put(\"time\", timeProp); properties.put(\"topic\", topicProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"attendees\", \"date\", \"time\", \"topic\")); Function scheduleMeetingFunction = Function.builder() .name(\"schedule_meeting\") .description(\"Schedules a meeting with specified attendees at a given time and date.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.\")) .tools(Arrays.asList(scheduleMeetingFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(\"Function to call: \" + functionCall.name().orElse(\"\")); System.out.println(\"Arguments: \" + functionCall.arguments().orElse(null)); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.\", \"tools\": [{ \"type\": \"function\", \"name\": \"schedule_meeting\", \"description\": \"Schedules a meeting with specified attendees at a given time and date.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"attendees\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"date\": {\"type\": \"string\"}, \"time\": {\"type\": \"string\"}, \"topic\": {\"type\": \"string\"} }, \"required\": [\"attendees\", \"date\", \"time\", \"topic\"] } }] }'` Get Weather This example shows how to define a function that retrieves temperature data for a location, enabling the model to call external APIs to answer queries requiring real-time or external information. Python`from google import genai weather_function = { \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": { \"type\": \"string\", \"description\": \"The city name, e.g. San Francisco\", }, }, \"required\": [\"location\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What's the temperature in London?\", tools=[weather_function], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherFunctionDeclaration = { type: 'function', name: 'get_current_temperature', description: 'Gets the current temperature for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city name, e.g. San Francisco', }, }, required: ['location'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"What's the temperature in London?\", tools: [weatherFunctionDeclaration], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map locationProp = new HashMap<>(); locationProp.put(\"type\", \"string\"); locationProp.put(\"description\", \"The city name, e.g. San Francisco\"); Map properties = new HashMap<>(); properties.put(\"location\", locationProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"location\")); Function weatherFunction = Function.builder() .name(\"get_current_temperature\") .description(\"Gets the current temperature for a given location.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"What's the temperature in London?\")) .tools(Arrays.asList(weatherFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(\"Function to call: \" + functionCall.name().orElse(\"\")); System.out.println(\"Arguments: \" + functionCall.arguments().orElse(null)); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What'\\''s the temperature in London?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city name\"} }, \"required\": [\"location\"] } }] }'` Create Chart This example shows how to define a function that generates a bar chart from structured data, demonstrating how the model can use external tools to perform computations or create visual assets: Python`from google import genai create_chart_function = { \"type\": \"function\", \"name\": \"create_bar_chart\", \"description\": \"Creates a bar chart given a title, labels, and values.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"title\": {\"type\": \"string\", \"description\": \"The title for the chart.\"}, \"labels\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"values\": {\"type\": \"array\", \"items\": {\"type\": \"number\"}}, }, \"required\": [\"title\", \"labels\", \"values\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\", tools=[create_chart_function], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const createChartFunctionDeclaration = { type: 'function', name: 'create_bar_chart', description: 'Creates a bar chart given a title, labels, and values.', parameters: { type: 'object', properties: { title: { type: 'string', description: 'The title for the chart.' }, labels: { type: 'array', items: { type: 'string' } }, values: { type: 'array', items: { type: 'number' } }, }, required: ['title', 'labels', 'values'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\", tools: [createChartFunctionDeclaration], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`${step.name}(${JSON.stringify(step.arguments)})`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map properties = new HashMap<>(); Map titleMap = new HashMap<>(); titleMap.put(\"type\", \"string\"); titleMap.put(\"description\", \"The title for the chart.\"); properties.put(\"title\", titleMap); Map labelsMap = new HashMap<>(); labelsMap.put(\"type\", \"array\"); labelsMap.put(\"items\", Collections.singletonMap(\"type\", \"string\")); properties.put(\"labels\", labelsMap); Map valuesMap = new HashMap<>(); valuesMap.put(\"type\", \"array\"); valuesMap.put(\"items\", Collections.singletonMap(\"type\", \"number\")); properties.put(\"values\", valuesMap); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"title\", \"labels\", \"values\")); Function createChartFunction = Function.builder() .name(\"create_bar_chart\") .description(\"Creates a bar chart given a title, labels, and values.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\")) .tools(Arrays.asList(createChartFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(functionCall.name().orElse(\"\") + \"(\" + functionCall.arguments().orElse(null) + \")\"); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Create a bar chart titled '\\''Quarterly Sales'\\'' with Q1: 50000, Q2: 75000, Q3: 60000.\", \"tools\": [{ \"type\": \"function\", \"name\": \"create_bar_chart\", \"description\": \"Creates a bar chart given a title, labels, and values.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"title\": {\"type\": \"string\"}, \"labels\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"values\": {\"type\": \"array\", \"items\": {\"type\": \"number\"}} }, \"required\": [\"title\", \"labels\", \"values\"] } }] }'` How function calling works Function calling involves a structured interaction between your application, the\nmodel, and external functions: **Define Function Declaration:** Define the function's name, parameters, and\npurpose to the model. **Call LLM with function declarations:** Send user prompt along with the\nfunction declaration(s) to the model. **Execute Function Code (Your Responsibility):** The model *doesn't*\nexecute the function itself. Extract the name and args and execute in\nyour application. **Create User friendly response:** Send the result back to the model for a\nfinal, user-friendly response. This process can be repeated over multiple turns. The model supports calling\nmultiple functions in a single turn (parallel function calling) and in sequence (compositional function calling). Step 1: Define a function declaration Python`set_light_values_declaration = { \"type\": \"function\", \"name\": \"set_light_values\", \"description\": \"Sets the brightness and color temperature of a light.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": { \"type\": \"integer\", \"description\": \"Light level from 0 to 100\", }, \"color_temp\": { \"type\": \"string\", \"enum\": [\"daylight\", \"cool\", \"warm\"], \"description\": \"Color temperature\", }, }, \"required\": [\"brightness\", \"color_temp\"], }, } def set_light_values(brightness: int, color_temp: str) -> dict: \"\"\"Set the brightness and color temperature of a room light.\"\"\" return {\"brightness\": brightness, \"colorTemperature\": color_temp}` JavaScript`const setLightValuesTool = { type: 'function', name: 'set_light_values', description: 'Sets the brightness and color temperature of a light.', parameters: { type: 'object', properties: { brightness: { type: 'number', description: 'Light level from 0 to 100' }, color_temp: { type: 'string', enum: ['daylight', 'cool', 'warm'] }, }, required: ['brightness', 'color_temp'], }, }; function setLightValues(brightness, color_temp) { return { brightness: brightness, colorTemperature: color_temp }; }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Step 2: Call the model with function declarations Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Turn the lights down to a romantic level\", tools=[set_light_values_declaration], ) fc_step = next(s for s in interaction.steps if s.type == \"function_call\") print(fc_step)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Turn the lights down to a romantic level', tools: [setLightValuesTool], }); const fcStep = interaction.steps.find(s => s.type === 'function_call'); console.log(fcStep);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` The model returns a `function_call` step with `type`, `name`, and `arguments`: `type='function_call' name='set_light_values' arguments={'color_temp': 'warm', 'brightness': 25}` Step 3: Execute the function Python`fc_step = next(s for s in interaction.steps if s.type == \"function_call\") if fc_step.name == \"set_light_values\": result = set_light_values(**fc_step.arguments) print(f\"Function execution result: {result}\")` JavaScript`const fcStep = interaction.steps.find(s => s.type === 'function_call'); let result; if (fcStep.name === 'set_light_values') { result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp); console.log(`Function execution result: ${JSON.stringify(result)}`); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Step 4: Send result back to model Python`final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ { \"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}], } ], tools=[set_light_values_declaration], previous_interaction_id=interaction.id, ) print(final_interaction.output_text)` JavaScript`const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', input: [{ type: 'function_result', name: fcStep.name, call_id: fcStep.id, result: [{ type: 'text', text: JSON.stringify(result) }] }], tools: [setLightValuesTool], previous_interaction_id: interaction.id, }); console.log(finalInteraction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Stateless function calling You can also use function calling in stateless mode by managing the conversation history on the client side and setting `store=false`. In stateless mode, you must pass the full history of the conversation in the `input` field of each subsequent request. This history must include:\n1. The initial `user_input` step.\n2. All model-generated steps returned in Turn 1 (including `thought` and `function_call` steps) exactly as received.\n3. The `function_result` step containing the output of your executed function. Python`from google import genai import json client = genai.Client() history = [ { \"type\": \"user_input\", \"content\": [{\"type\": \"text\", \"text\": \"Turn the lights down to a romantic level\"}] } ] interaction = client.interactions.create( model=\"gemini-3.8-flash\", store=False, input=history, tools=[set_light_values_declaration], ) for step in interaction.steps: history.append(step.model_dump()) fc_step = next(s for s in interaction.steps if s.type == \"function_call\") if fc_step.name == \"set_light_values\": result = set_light_values(**fc_step.arguments) history.append({ \"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}], }) final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", store=False, input=history, tools=[set_light_values_declaration], ) print(final_interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); async function main() { const history = [ { type: \"user_input\", content: [{ type: \"text\", text: \"Turn the lights down to a romantic level\" }] } ]; const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", store: false, input: history, tools: [setLightValuesTool], }); history.push(...interaction.steps); const fcStep = interaction.steps.find(s => s.type === 'function_call'); let result; if (fcStep.name === 'set_light_values') { result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp); } history.push({ type: 'function_result', name: fcStep.name, call_id: fcStep.id, result: [{ type: 'text', text: JSON.stringify(result) }] }); const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', store: false, input: history, tools: [setLightValuesTool], }); console.log(finalInteraction.output_text); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`# Turn 1: Send request with tools and store: false RESPONSE1=$(curl -s -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"store\": false, \"input\": [ { \"type\": \"user_input\", \"content\": \"Turn the lights down to a romantic level\" } ], \"tools\": [{ \"type\": \"function\", \"name\": \"set_light_values\", \"description\": \"Sets the brightness and color temperature of a light.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": {\"type\": \"integer\", \"description\": \"Light level from 0 to 100\"}, \"color_temp\": {\"type\": \"string\", \"enum\": [\"daylight\", \"cool\", \"warm\"]} }, \"required\": [\"brightness\", \"color_temp\"] } }] }') # Extract model steps (thought, function_call) MODEL_STEPS=$(echo \"$RESPONSE1\" | jq '.steps') # Extract function call details to execute FC_NAME=$(echo \"$RESPONSE1\" | jq -r '.steps[] | select(.type==\"function_call\") | .name') FC_ID=$(echo \"$RESPONSE1\" | jq -r '.steps[] | select(.type==\"function_call\") | .id') # Assume local execution returns: {\"brightness\": 25, \"colorTemperature\": \"warm\"} RESULT=\"{\\\"brightness\\\": 25, \\\"colorTemperature\\\": \\\"warm\\\"}\" # Reconstruct history for Turn 2 HISTORY=$(jq -n \\ --argjson first_input '[{\"type\": \"user_input\", \"content\": \"Turn the lights down to a romantic level\"}]' \\ --argjson model_steps \"$MODEL_STEPS\" \\ --arg fc_name \"$FC_NAME\" \\ --arg fc_id \"$FC_ID\" \\ --arg result \"$RESULT\" \\ '$first_input + $model_steps + [{\"type\": \"function_result\", \"name\": $fc_name, \"call_id\": $fc_id, \"result\": [{\"type\": \"text\", \"text\": $result}]}]') # Turn 2: Send the full history\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d \"{ \\\"model\\\": \\\"gemini-3.8-flash\\\", \\\"store\\\": false, \\\"input\\\": $HISTORY, \\\"tools\\\": [{ \\\"type\\\": \\\"function\\\", \\\"name\\\": \\\"set_light_values\\\", \\\"description\\\": \\\"Sets the brightness and color temperature of a light.\\\", \\\"parameters\\\": { \\\"type\\\": \\\"object\\\", \\\"properties\\\": { \\\"brightness\\\": {\\\"type\\\": \\\"integer\\\"}, \\\"color_temp\\\": {\\\"type\\\": \\\"string\\\"} }, \\\"required\\\": [\\\"brightness\\\", \\\"color_temp\\\"] } }] }\"` Function declarations A function declaration is passed as a tool and includes: `type` (string): Must be `\"function\"` for custom functions. `name` (string): Unique function name (use underscores or camelCase). `description` (string): Clear explanation of the function's purpose. `parameters` (object): Input parameters the function expects.\n `type` (string): Overall data type, such as `object`. `properties` (object): Individual parameters with type and description. `required` (array): Mandatory parameter names. Function calling with thinking models Gemini 3 series models use an internal [\"thinking\"](/gemini-api/docs/thinking) process that improves function calling. The SDKs automatically handle [thought signatures](/gemini-api/docs/thought-signatures) for you. Parallel function calling Call multiple functions at once when they are independent: Python`power_disco_ball = {\"type\": \"function\", \"name\": \"power_disco_ball\", \"description\": \"Powers the disco ball.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"power\": {\"type\": \"boolean\"}}, \"required\": [\"power\"]}} start_music = {\"type\": \"function\", \"name\": \"start_music\", \"description\": \"Play music.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"energetic\": {\"type\": \"boolean\"}, \"loud\": {\"type\": \"boolean\"}}, \"required\": [\"energetic\", \"loud\"]}} dim_lights = {\"type\": \"function\", \"name\": \"dim_lights\", \"description\": \"Dim the lights.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"brightness\": {\"type\": \"number\"}}, \"required\": [\"brightness\"]}} client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Turn this place into a party!\", tools=[power_disco_ball, start_music, dim_lights], generation_config={\"tool_choice\": \"any\"}, ) for step in interaction.steps: if step.type == \"function_call\": args = \", \".join(f\"{key}={val}\" for key, val in step.arguments.items()) print(f\"{step.name}({args})\")` JavaScript`const powerDiscoBall = { type: 'function', name: 'power_disco_ball', description: 'Powers the disco ball.', parameters: { type: 'object', properties: { power: { type: 'boolean' } }, required: ['power'] } }; const startMusic = { type: 'function', name: 'start_music', description: 'Play music.', parameters: { type: 'object', properties: { energetic: { type: 'boolean' }, loud: { type: 'boolean' } }, required: ['energetic', 'loud'] } }; const dimLights = { type: 'function', name: 'dim_lights', description: 'Dim the lights.', parameters: { type: 'object', properties: { brightness: { type: 'number' } }, required: ['brightness'] } }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Turn this place into a party!', tools: [powerDiscoBall, startMusic, dimLights], generation_config: { tool_choice: 'any' }, }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`${step.name}(${JSON.stringify(step.arguments)})`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Turn this place into a party!\", \"tools\": [ { \"type\": \"function\", \"name\": \"power_disco_ball\", \"description\": \"Powers the disco ball.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"power\": {\"type\": \"boolean\"} }, \"required\": [\"power\"] } }, { \"type\": \"function\", \"name\": \"start_music\", \"description\": \"Play music.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"energetic\": {\"type\": \"boolean\"}, \"loud\": {\"type\": \"boolean\"} }, \"required\": [\"energetic\", \"loud\"] } }, { \"type\": \"function\", \"name\": \"dim_lights\", \"description\": \"Dim the lights.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": {\"type\": \"number\"} }, \"required\": [\"brightness\"] } } ] }'` Compositional function calling Chain multiple function calls together for complex requests (e.g., get location\nfirst, then get weather for that location). Python`get_weather_forecast_declaration = { \"type\": \"function\", \"name\": \"get_weather_forecast\", \"description\": \"Gets the current weather temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The location\"}, }, \"required\": [\"location\"], }, } set_thermostat_temperature_declaration = { \"type\": \"function\", \"name\": \"set_thermostat_temperature\", \"description\": \"Sets the thermostat to a desired temperature.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"temperature\": { \"type\": \"integer\", \"description\": \"The temperature in Celsius\", }, }, \"required\": [\"temperature\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", tools=[ get_weather_forecast_declaration, set_thermostat_temperature_declaration, ], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\") elif hasattr(step, \"content\") and step.content: for part in step.content: if hasattr(part, \"text\"): print(part.text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const getWeatherForecastTool = { type: 'function', name: 'get_weather_forecast', description: 'Gets the current weather temperature for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The location' }, }, required: ['location'], }, }; const setThermostatTemperatureTool = { type: 'function', name: 'set_thermostat_temperature', description: 'Sets the thermostat to a desired temperature.', parameters: { type: 'object', properties: { temperature: { type: 'integer', description: 'The temperature in Celsius', }, }, required: ['temperature'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", tools: [ getWeatherForecastTool, setThermostatTemperatureTool, ], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } else if (step.content) { for (const part of step.content) { if (part.text) { console.log(part.text); } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"If it'\\''s warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", \"tools\": [ { \"type\": \"function\", \"name\": \"get_weather_forecast\", \"description\": \"Gets the current weather temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\"} }, \"required\": [\"location\"] } }, { \"type\": \"function\", \"name\": \"set_thermostat_temperature\", \"description\": \"Sets the thermostat to a desired temperature.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"temperature\": {\"type\": \"integer\"} }, \"required\": [\"temperature\"] } } ] }'` Function calling modes Control how the model uses tools using `tool_choice` in `generation_config`: `auto` (Default): Model decides whether to call a function or respond directly. `any`: Model is constrained to always predict a function call. `none`: Model is prohibited from making function calls. `validated`: Model ensures function schema adherence. Python`generation_config = { \"tool_choice\": { \"allowed_tools\": { \"mode\": \"any\", \"tools\": [\"get_current_temperature\"] } } }` JavaScript`const generation_config = { tool_choice: { allowed_tools: { mode: 'any', tools: ['get_current_temperature'] } } };` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the temperature in Boston?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\"} }, \"required\": [\"location\"] } }], \"generation_config\": { \"tool_choice\": { \"allowed_tools\": { \"mode\": \"any\", \"tools\": [\"get_current_temperature\"] } } } }'` Multi-tool use You can enable multiple tools, combining built-in tools with function calling in\nthe same request. Gemini 3 models can combine built-in tools with function\ncalling out-of-the-box in Interactions. Passing `previous_interaction_id`\nautomatically circulates the built-in tool context. Python`from google import genai import json client = genai.Client() get_weather = { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a requested city.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"city\": { \"type\": \"string\", \"description\": \"The city and state, e.g. UtqiaÄĄvik, Alaska\", }, }, \"required\": [\"city\"], }, } tools = [ {\"type\": \"google_search\"}, get_weather ] interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What is the northernmost city in the United States? What's the weather like there today?\", tools=tools ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function call: {step.name} (ID: {step.id})\") result = {\"response\": \"Very cold. 22 degrees Fahrenheit.\"} interaction_2 = client.interactions.create( model=\"gemini-3.8-flash\", previous_interaction_id=interaction.id, tools=tools, input=[{ \"type\": \"function_result\", \"name\": step.name, \"call_id\": step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}] }] ) print(interaction_2.output_text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherTool = { type: 'function', name: 'get_weather', description: 'Gets the weather for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA', }, }, required: ['location'], }, }; const tools = [ { type: 'google_search' }, // Built-in tool weatherTool, ]; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"What is the northernmost city in the United States? What's the weather like there today?\", tools: tools, }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function call: ${step.name} (ID: ${step.id})`); const result = { response: 'Very cold. 22 degrees Fahrenheit.' }; const interaction_2 = await client.interactions.create({ model: 'gemini-3.8-flash', previous_interaction_id: interaction.id, tools: tools, input: [ { type: 'function_result', name: step.name, call_id: step.id, result: [{ type: 'text', text: JSON.stringify(result) }], }, ], }); console.log(interaction_2.output_text); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`# Turn 1: Send request with built-in google_search tool and custom weather tool\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the northernmost city in the United States? What'\\''s the weather like there today?\", \"tools\": [ {\"type\": \"google_search\"}, { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state, e.g. San Francisco, CA\"} }, \"required\": [\"location\"] } } ] }' # Turn 2: Provide function result and pass previous_interaction_id\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"previous_interaction_id\": \"INTERACTION_ID\", \"tools\": [ {\"type\": \"google_search\"}, { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state, e.g. San Francisco, CA\"} }, \"required\": [\"location\"] } } ], \"input\": [ { \"type\": \"function_result\", \"name\": \"get_weather\", \"call_id\": \"call_123\", \"result\": [{\"type\": \"text\", \"text\": \"{\\\"response\\\": \\\"Very cold. 22 degrees Fahrenheit.\\\"}\"}] } ] }'` Multimodal function responses For Gemini 3 series models, you can include multimodal content in\nthe function response parts that you send to the model. The model can process\nthis multimodal content in its next turn to produce a more informed response. To include multimodal data in a function response, include it as one or more content blocks in the `result` field of the `function_result` step. Each content block must specify its `type` (e.g., `\"text\"`, `\"image\"`). The following example shows how to send a function response containing image data back to the model in an interaction: Python`import base64 from google import genai import requests client = genai.Client() tool_call = next(s for s in interaction.steps if s.type == \"function_call\") image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content base64_image_data = base64.b64encode(image_bytes).decode(\"utf-8\") final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", previous_interaction_id=interaction.id, input=[ { \"type\": \"function_result\", \"name\": tool_call.name, \"call_id\": tool_call.id, \"result\": [ {\"type\": \"text\", \"text\": \"instrument.jpg\"}, { \"type\": \"image\", \"mime_type\": \"image/jpeg\", \"data\": base64_image_data, }, ], } ], ) print(final_interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const toolCall = interaction.steps.find(s => s.type === 'function_call'); const base64ImageData = \"BASE64_IMAGE_DATA\"; const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', previous_interaction_id: interaction.id, input: [{ type: 'function_result', name: toolCall.name, call_id: toolCall.id, result: [ { type: 'text', text: 'instrument.jpg' }, { type: 'image', mime_type: 'image/jpeg', data: base64ImageData, } ] }] }); console.log(finalInteraction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"previous_interaction_id\": \"INTERACTION_ID\", \"input\": [ { \"type\": \"function_result\", \"name\": \"get_image\", \"call_id\": \"call_123\", \"result\": [ {\"type\": \"text\", \"text\": \"instrument.jpg\"}, { \"type\": \"image\", \"mime_type\": \"image/jpeg\", \"data\": \"BASE64_IMAGE_DATA\" } ] } ] }'` Function calling with Structured output For Gemini 3 series models, combine function calling with\n[structured output](/gemini-api/docs/structured-output) for\nconsistently formatted responses. Remote MCP (Model Context Protocol) Interactions API supports connecting to remote MCP servers to give the model access to external tools and services. You provide the server `name` and `url` in the tools configuration. When using Remote MCP, be aware of the following constraints: **Server types**: Remote MCP only works with Streamable HTTP servers. SSE (Server-Sent Events) servers are not supported. **Naming**: MCP server names should not include the `-` character. Use `snake_case` server names instead. Field Type Required Description `type` `string` Yes Must be `\"mcp_server\"`. `name` `string` No A display name for the MCP server. `url` `string` No The full URL for the MCP server endpoint. `headers` `object` No Key-value pairs sent as HTTP headers with every request to the server (for example, authentication tokens). `allowed_tools` `array` No Restrict which tools from the server the agent may call. Example Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Check the weather in San Francisco.\", tools=[ { \"type\": \"mcp_server\", \"name\": \"weather\", \"url\": \"https://gemini-api-demos.uc.r.appspot.com/mcp\", } ] )` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Check the weather in San Francisco.', tools: [ { type: 'mcp_server', name: 'weather', url: 'https://gemini-api-demos.uc.r.appspot.com/mcp' } ] });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Check the weather in San Francisco.\", \"tools\": [ { \"type\": \"mcp_server\", \"name\": \"weather\", \"url\": \"https://gemini-api-demos.uc.r.appspot.com/mcp\" } ] }'` Stream tool calls When using tools with streaming, the model generates function calls as a\nsequence of `step.delta` events on the stream. Tool arguments can be streamed\nas partial arguments using `arguments`. You must aggregate these deltas to\nreconstruct the complete tool calls before executing them. Python`import json from google import genai client = genai.Client() weather_tool = { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state\"} }, \"required\": [\"location\"] } } stream = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What is the weather in Paris?\", tools=[weather_tool], stream=True ) current_calls = {} tool_calls = [] for event in stream: if event.event_type == \"step.start\": if event.step.type == \"function_call\": current_calls[event.index] = { \"id\": event.step.id, \"name\": event.step.name, \"arguments\": \"\" } if hasattr(event.step, \"arguments\") and event.step.arguments: if isinstance(event.step.arguments, dict): current_calls[event.index][\"arguments\"] = json.dumps(event.step.arguments) else: current_calls[event.index][\"arguments\"] = event.step.arguments elif event.event_type == \"step.delta\": if event.delta.type == \"arguments\": if event.index in current_calls: current_calls[event.index][\"arguments\"] += event.delta.partial_arguments elif event.delta.type == \"text\": print(event.delta.text, end=\"\", flush=True) elif event.event_type == \"interaction.completed\": for index, call in current_calls.items(): args = call[\"arguments\"] if args: args = json.loads(args) else: args = {} tool_calls.append({ \"type\": \"function_call\", \"id\": call[\"id\"], \"name\": call[\"name\"], \"arguments\": args }) print(f\"\\nFinal tool calls ready to execute:\") print(json.dumps(tool_calls, indent=2))` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherTool = { type: 'function', name: 'get_weather', description: 'Gets the weather for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city and state' } }, required: ['location'] } }; const stream = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'What is the weather in Paris?', tools: [weatherTool], stream: true, }); const currentCalls = new Map(); let toolCalls = []; for await (const event of stream) { const evType = event.event_type; if (evType === 'step.start') { if (event.step.type === 'function_call') { currentCalls.set(event.index, { id: event.step.id, name: event.step.name, arguments: '' }); if (event.step.arguments) { if (typeof event.step.arguments === 'object') { currentCalls.get(event.index).arguments = JSON.stringify(event.step.arguments); } else { currentCalls.get(event.index).arguments = event.step.arguments; } } } } else if (evType === 'step.delta') { if (event.delta.type === 'arguments') { if (currentCalls.has(event.index)) { currentCalls.get(event.index).arguments += event.delta.partial_arguments; } } else if (event.delta.type === 'text') { process.stdout.write(event.delta.text); } } else if (evType === 'interaction.completed' || evType === 'interaction.complete') { toolCalls = Array.from(currentCalls.values()).map(call => ({ type: 'function_call', id: call.id, name: call.name, arguments: call.arguments ? JSON.parse(call.arguments) : {} })); console.log('\\nFinal tool calls ready to execute:'); console.log(JSON.stringify(toolCalls, null, 2)); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the weather in Paris?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state\"} }, \"required\": [\"location\"] } }], \"stream\": true }'` Best practices **Function and Parameter Descriptions:** Be clear and specific. **Naming:** Use descriptive names without spaces or special characters. **Strong Typing:** Use specific types (integer, string, enum). **Tool Selection:** Keep active set to 10-20 tools maximum. **Prompt Engineering:** Provide context and instructions. **Validation:** Validate function calls before executing. **Error Handling:** Implement robust error handling. **Security:** Use appropriate authentication for external APIs. Workarounds for pre-tool text requirements **Issue:** If your prompt requires the model to output structured text (XML, YAML, JSON, etc.) (e.g., `...`) immediately before making a tool call, the tool call may occasionally fail with `Malformed_Function_Call`. **Solutions:** The following workarounds resolve this issue: **PREFERRED:** Instruct the model to put its pre-tool notes inside a dedicated `update()` function call instead of raw text (details below). Instruct the model to write notes as Markdown headers (`# UPDATE`, `## PLAN`) instead of structured text. Do not require the model to output text before tool calls. Preferred workaround: Wrap working notes in a dedicated function call Instead of the original instruction: `Before calling a tool, in every response you MUST first output a single `` part as specified, don't skip this part or any of required sub-tags within ``.` Use this updated instruction: `Before calling any other tool, in every response you MUST first call `update` with all required parameters (previous_step, plan, next_step, external).` And update all references to the old `` XML format in the customer request. Then add the corresponding function declaration for the update function: `{ \"name\": \"update\", \"description\": \"Update working notes (previous step analysis, plan, next step, external note).\", \"parameters\": { \"type\": \"OBJECT\", \"properties\": { \"previous_step\": { \"type\": \"STRING\", \"description\": \"Key findings and outcomes since the previous step.\" }, \"plan\": { \"type\": \"STRING\", \"description\": \"The current status of the plan.\" }, \"next_step\": { \"type\": \"STRING\", \"description\": \"Brief explanation of the immediate next action according to the plan.\" }, \"external\": { \"type\": \"STRING\", \"description\": \"A short, plain-language note shown to the User about what you are ABOUT TO DO next.\" } }, \"required\": [ \"previous_step\", \"plan\", \"next_step\", \"external\" ] } }` Then the model will make two calls in the same step: the `update()` call that replaces the structured XML, and the actual function call it wants to make. Notes and limitations Only a [subset of the OpenAPI schema](/api/rest/v1beta/cachedContents#FunctionDeclaration) is supported. For `any` mode, the API may reject very large or deeply nested schemas. Supported parameter types in Python are limited. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-03 UTC.", "znaku_textu": 65538, "slov": 6786, "odkazu": 133, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 20:10:24", "sha256": "ed3658214feff52019888ced48cb2dd0accba781ac2fc00eaabc04e4772bb0e7", "hloubka": 0, "zdroj_objevu": "seed", "ze_seznamu": true, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/function-calling/tutorial", "titulek": "Function calling with the Gemini API | Google AI for Developers", "h1": "Function calling with the Gemini API", "popis": "Get started using Function Calling with the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/function-calling", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Function calling with the Gemini API  |  Google AI for Developers", "og:description": "Get started using Function Calling with the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/function-calling", "og:image": "https://ai.google.dev/static/site-assets/images/function-calling.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Function calling with the Gemini API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Function calling with the Gemini API", "item": "https://ai.google.dev/gemini-api/docs/function-calling"}]}], "drobecky": ["Gemini API", "Function calling with the Gemini API"], "osnova": [{"uroven": 1, "text": "Function calling with the Gemini API"}, {"uroven": 3, "text": "Schedule Meeting"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Get Weather"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Create Chart"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How function calling works"}, {"uroven": 3, "text": "Step 1: Define a function declaration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 2: Call the model with function declarations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 3: Execute the function"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 4: Send result back to model"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Stateless function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function declarations"}, {"uroven": 2, "text": "Function calling with thinking models"}, {"uroven": 2, "text": "Parallel function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Compositional function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function calling modes"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multi-tool use"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multimodal function responses"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function calling with Structured output"}, {"uroven": 2, "text": "Remote MCP (Model Context Protocol)"}, {"uroven": 3, "text": "Example"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Stream tool calls"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Workarounds for pre-tool text requirements"}, {"uroven": 3, "text": "Preferred workaround: Wrap working notes in a dedicated function call"}, {"uroven": 2, "text": "Notes and limitations"}], "markdown": "Function calling with the Gemini API Function calling lets you connect models to external tools and APIs.\nInstead of generating text responses, the model determines when to call specific\nfunctions and provides the necessary parameters to execute real-world actions.\nThis allows the model to act as a bridge between natural language and real-world\nactions and data. Function calling has 3 primary use cases: **Take Actions:** Interact with external systems using APIs, such as\nscheduling appointments, creating invoices, sending emails, or controlling\nsmart home devices. **Augment Knowledge:** Access information from external sources like\ndatabases, APIs, and knowledge bases. **Extend Capabilities:** Use external tools to perform computations and\nextend the limitations of the model, such as using a calculator or creating\ncharts. You can browse examples of these use cases below: Schedule Meeting This example shows how to define a function that schedules a meeting with attendees at a specific time, allowing the model to parse user requests and return structured arguments to trigger actions in external systems. Python`from google import genai schedule_meeting_function = { \"type\": \"function\", \"name\": \"schedule_meeting\", \"description\": \"Schedules a meeting with specified attendees at a given time and date.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"attendees\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"date\": {\"type\": \"string\", \"description\": \"Date (e.g., '2024-07-29')\"}, \"time\": {\"type\": \"string\", \"description\": \"Time (e.g., '15:00')\"}, \"topic\": {\"type\": \"string\", \"description\": \"The meeting topic.\"}, }, \"required\": [\"attendees\", \"date\", \"time\", \"topic\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning.\", tools=[{\"type\": \"function\", **schedule_meeting_function}], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const scheduleMeetingFunction = { type: 'function', name: 'schedule_meeting', description: 'Schedules a meeting with specified attendees at a given time and date.', parameters: { type: 'object', properties: { attendees: { type: 'array', items: { type: 'string' } }, date: { type: 'string', description: 'Date (e.g., \"2024-07-29\")' }, time: { type: 'string', description: 'Time (e.g., \"15:00\")' }, topic: { type: 'string', description: 'The meeting topic.' }, }, required: ['attendees', 'date', 'time', 'topic'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.', tools: [scheduleMeetingFunction], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map attendeesProp = new HashMap<>(); attendeesProp.put(\"type\", \"array\"); Map itemsMap = new HashMap<>(); itemsMap.put(\"type\", \"string\"); attendeesProp.put(\"items\", itemsMap); Map dateProp = new HashMap<>(); dateProp.put(\"type\", \"string\"); dateProp.put(\"description\", \"Date (e.g., \\\"2024-07-29\\\")\"); Map timeProp = new HashMap<>(); timeProp.put(\"type\", \"string\"); timeProp.put(\"description\", \"Time (e.g., \\\"15:00\\\")\"); Map topicProp = new HashMap<>(); topicProp.put(\"type\", \"string\"); topicProp.put(\"description\", \"The meeting topic.\"); Map properties = new HashMap<>(); properties.put(\"attendees\", attendeesProp); properties.put(\"date\", dateProp); properties.put(\"time\", timeProp); properties.put(\"topic\", topicProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"attendees\", \"date\", \"time\", \"topic\")); Function scheduleMeetingFunction = Function.builder() .name(\"schedule_meeting\") .description(\"Schedules a meeting with specified attendees at a given time and date.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.\")) .tools(Arrays.asList(scheduleMeetingFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(\"Function to call: \" + functionCall.name().orElse(\"\")); System.out.println(\"Arguments: \" + functionCall.arguments().orElse(null)); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.\", \"tools\": [{ \"type\": \"function\", \"name\": \"schedule_meeting\", \"description\": \"Schedules a meeting with specified attendees at a given time and date.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"attendees\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"date\": {\"type\": \"string\"}, \"time\": {\"type\": \"string\"}, \"topic\": {\"type\": \"string\"} }, \"required\": [\"attendees\", \"date\", \"time\", \"topic\"] } }] }'` Get Weather This example shows how to define a function that retrieves temperature data for a location, enabling the model to call external APIs to answer queries requiring real-time or external information. Python`from google import genai weather_function = { \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": { \"type\": \"string\", \"description\": \"The city name, e.g. San Francisco\", }, }, \"required\": [\"location\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What's the temperature in London?\", tools=[weather_function], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherFunctionDeclaration = { type: 'function', name: 'get_current_temperature', description: 'Gets the current temperature for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city name, e.g. San Francisco', }, }, required: ['location'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"What's the temperature in London?\", tools: [weatherFunctionDeclaration], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map locationProp = new HashMap<>(); locationProp.put(\"type\", \"string\"); locationProp.put(\"description\", \"The city name, e.g. San Francisco\"); Map properties = new HashMap<>(); properties.put(\"location\", locationProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"location\")); Function weatherFunction = Function.builder() .name(\"get_current_temperature\") .description(\"Gets the current temperature for a given location.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"What's the temperature in London?\")) .tools(Arrays.asList(weatherFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(\"Function to call: \" + functionCall.name().orElse(\"\")); System.out.println(\"Arguments: \" + functionCall.arguments().orElse(null)); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What'\\''s the temperature in London?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city name\"} }, \"required\": [\"location\"] } }] }'` Create Chart This example shows how to define a function that generates a bar chart from structured data, demonstrating how the model can use external tools to perform computations or create visual assets: Python`from google import genai create_chart_function = { \"type\": \"function\", \"name\": \"create_bar_chart\", \"description\": \"Creates a bar chart given a title, labels, and values.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"title\": {\"type\": \"string\", \"description\": \"The title for the chart.\"}, \"labels\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"values\": {\"type\": \"array\", \"items\": {\"type\": \"number\"}}, }, \"required\": [\"title\", \"labels\", \"values\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\", tools=[create_chart_function], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const createChartFunctionDeclaration = { type: 'function', name: 'create_bar_chart', description: 'Creates a bar chart given a title, labels, and values.', parameters: { type: 'object', properties: { title: { type: 'string', description: 'The title for the chart.' }, labels: { type: 'array', items: { type: 'string' } }, values: { type: 'array', items: { type: 'number' } }, }, required: ['title', 'labels', 'values'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\", tools: [createChartFunctionDeclaration], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`${step.name}(${JSON.stringify(step.arguments)})`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map properties = new HashMap<>(); Map titleMap = new HashMap<>(); titleMap.put(\"type\", \"string\"); titleMap.put(\"description\", \"The title for the chart.\"); properties.put(\"title\", titleMap); Map labelsMap = new HashMap<>(); labelsMap.put(\"type\", \"array\"); labelsMap.put(\"items\", Collections.singletonMap(\"type\", \"string\")); properties.put(\"labels\", labelsMap); Map valuesMap = new HashMap<>(); valuesMap.put(\"type\", \"array\"); valuesMap.put(\"items\", Collections.singletonMap(\"type\", \"number\")); properties.put(\"values\", valuesMap); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"title\", \"labels\", \"values\")); Function createChartFunction = Function.builder() .name(\"create_bar_chart\") .description(\"Creates a bar chart given a title, labels, and values.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\")) .tools(Arrays.asList(createChartFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(functionCall.name().orElse(\"\") + \"(\" + functionCall.arguments().orElse(null) + \")\"); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Create a bar chart titled '\\''Quarterly Sales'\\'' with Q1: 50000, Q2: 75000, Q3: 60000.\", \"tools\": [{ \"type\": \"function\", \"name\": \"create_bar_chart\", \"description\": \"Creates a bar chart given a title, labels, and values.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"title\": {\"type\": \"string\"}, \"labels\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"values\": {\"type\": \"array\", \"items\": {\"type\": \"number\"}} }, \"required\": [\"title\", \"labels\", \"values\"] } }] }'` How function calling works Function calling involves a structured interaction between your application, the\nmodel, and external functions: **Define Function Declaration:** Define the function's name, parameters, and\npurpose to the model. **Call LLM with function declarations:** Send user prompt along with the\nfunction declaration(s) to the model. **Execute Function Code (Your Responsibility):** The model *doesn't*\nexecute the function itself. Extract the name and args and execute in\nyour application. **Create User friendly response:** Send the result back to the model for a\nfinal, user-friendly response. This process can be repeated over multiple turns. The model supports calling\nmultiple functions in a single turn (parallel function calling) and in sequence (compositional function calling). Step 1: Define a function declaration Python`set_light_values_declaration = { \"type\": \"function\", \"name\": \"set_light_values\", \"description\": \"Sets the brightness and color temperature of a light.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": { \"type\": \"integer\", \"description\": \"Light level from 0 to 100\", }, \"color_temp\": { \"type\": \"string\", \"enum\": [\"daylight\", \"cool\", \"warm\"], \"description\": \"Color temperature\", }, }, \"required\": [\"brightness\", \"color_temp\"], }, } def set_light_values(brightness: int, color_temp: str) -> dict: \"\"\"Set the brightness and color temperature of a room light.\"\"\" return {\"brightness\": brightness, \"colorTemperature\": color_temp}` JavaScript`const setLightValuesTool = { type: 'function', name: 'set_light_values', description: 'Sets the brightness and color temperature of a light.', parameters: { type: 'object', properties: { brightness: { type: 'number', description: 'Light level from 0 to 100' }, color_temp: { type: 'string', enum: ['daylight', 'cool', 'warm'] }, }, required: ['brightness', 'color_temp'], }, }; function setLightValues(brightness, color_temp) { return { brightness: brightness, colorTemperature: color_temp }; }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Step 2: Call the model with function declarations Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Turn the lights down to a romantic level\", tools=[set_light_values_declaration], ) fc_step = next(s for s in interaction.steps if s.type == \"function_call\") print(fc_step)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Turn the lights down to a romantic level', tools: [setLightValuesTool], }); const fcStep = interaction.steps.find(s => s.type === 'function_call'); console.log(fcStep);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` The model returns a `function_call` step with `type`, `name`, and `arguments`: `type='function_call' name='set_light_values' arguments={'color_temp': 'warm', 'brightness': 25}` Step 3: Execute the function Python`fc_step = next(s for s in interaction.steps if s.type == \"function_call\") if fc_step.name == \"set_light_values\": result = set_light_values(**fc_step.arguments) print(f\"Function execution result: {result}\")` JavaScript`const fcStep = interaction.steps.find(s => s.type === 'function_call'); let result; if (fcStep.name === 'set_light_values') { result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp); console.log(`Function execution result: ${JSON.stringify(result)}`); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Step 4: Send result back to model Python`final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ { \"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}], } ], tools=[set_light_values_declaration], previous_interaction_id=interaction.id, ) print(final_interaction.output_text)` JavaScript`const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', input: [{ type: 'function_result', name: fcStep.name, call_id: fcStep.id, result: [{ type: 'text', text: JSON.stringify(result) }] }], tools: [setLightValuesTool], previous_interaction_id: interaction.id, }); console.log(finalInteraction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Stateless function calling You can also use function calling in stateless mode by managing the conversation history on the client side and setting `store=false`. In stateless mode, you must pass the full history of the conversation in the `input` field of each subsequent request. This history must include:\n1. The initial `user_input` step.\n2. All model-generated steps returned in Turn 1 (including `thought` and `function_call` steps) exactly as received.\n3. The `function_result` step containing the output of your executed function. Python`from google import genai import json client = genai.Client() history = [ { \"type\": \"user_input\", \"content\": [{\"type\": \"text\", \"text\": \"Turn the lights down to a romantic level\"}] } ] interaction = client.interactions.create( model=\"gemini-3.8-flash\", store=False, input=history, tools=[set_light_values_declaration], ) for step in interaction.steps: history.append(step.model_dump()) fc_step = next(s for s in interaction.steps if s.type == \"function_call\") if fc_step.name == \"set_light_values\": result = set_light_values(**fc_step.arguments) history.append({ \"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}], }) final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", store=False, input=history, tools=[set_light_values_declaration], ) print(final_interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); async function main() { const history = [ { type: \"user_input\", content: [{ type: \"text\", text: \"Turn the lights down to a romantic level\" }] } ]; const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", store: false, input: history, tools: [setLightValuesTool], }); history.push(...interaction.steps); const fcStep = interaction.steps.find(s => s.type === 'function_call'); let result; if (fcStep.name === 'set_light_values') { result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp); } history.push({ type: 'function_result', name: fcStep.name, call_id: fcStep.id, result: [{ type: 'text', text: JSON.stringify(result) }] }); const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', store: false, input: history, tools: [setLightValuesTool], }); console.log(finalInteraction.output_text); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`# Turn 1: Send request with tools and store: false RESPONSE1=$(curl -s -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"store\": false, \"input\": [ { \"type\": \"user_input\", \"content\": \"Turn the lights down to a romantic level\" } ], \"tools\": [{ \"type\": \"function\", \"name\": \"set_light_values\", \"description\": \"Sets the brightness and color temperature of a light.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": {\"type\": \"integer\", \"description\": \"Light level from 0 to 100\"}, \"color_temp\": {\"type\": \"string\", \"enum\": [\"daylight\", \"cool\", \"warm\"]} }, \"required\": [\"brightness\", \"color_temp\"] } }] }') # Extract model steps (thought, function_call) MODEL_STEPS=$(echo \"$RESPONSE1\" | jq '.steps') # Extract function call details to execute FC_NAME=$(echo \"$RESPONSE1\" | jq -r '.steps[] | select(.type==\"function_call\") | .name') FC_ID=$(echo \"$RESPONSE1\" | jq -r '.steps[] | select(.type==\"function_call\") | .id') # Assume local execution returns: {\"brightness\": 25, \"colorTemperature\": \"warm\"} RESULT=\"{\\\"brightness\\\": 25, \\\"colorTemperature\\\": \\\"warm\\\"}\" # Reconstruct history for Turn 2 HISTORY=$(jq -n \\ --argjson first_input '[{\"type\": \"user_input\", \"content\": \"Turn the lights down to a romantic level\"}]' \\ --argjson model_steps \"$MODEL_STEPS\" \\ --arg fc_name \"$FC_NAME\" \\ --arg fc_id \"$FC_ID\" \\ --arg result \"$RESULT\" \\ '$first_input + $model_steps + [{\"type\": \"function_result\", \"name\": $fc_name, \"call_id\": $fc_id, \"result\": [{\"type\": \"text\", \"text\": $result}]}]') # Turn 2: Send the full history\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d \"{ \\\"model\\\": \\\"gemini-3.8-flash\\\", \\\"store\\\": false, \\\"input\\\": $HISTORY, \\\"tools\\\": [{ \\\"type\\\": \\\"function\\\", \\\"name\\\": \\\"set_light_values\\\", \\\"description\\\": \\\"Sets the brightness and color temperature of a light.\\\", \\\"parameters\\\": { \\\"type\\\": \\\"object\\\", \\\"properties\\\": { \\\"brightness\\\": {\\\"type\\\": \\\"integer\\\"}, \\\"color_temp\\\": {\\\"type\\\": \\\"string\\\"} }, \\\"required\\\": [\\\"brightness\\\", \\\"color_temp\\\"] } }] }\"` Function declarations A function declaration is passed as a tool and includes: `type` (string): Must be `\"function\"` for custom functions. `name` (string): Unique function name (use underscores or camelCase). `description` (string): Clear explanation of the function's purpose. `parameters` (object): Input parameters the function expects.\n `type` (string): Overall data type, such as `object`. `properties` (object): Individual parameters with type and description. `required` (array): Mandatory parameter names. Function calling with thinking models Gemini 3 series models use an internal [\"thinking\"](/gemini-api/docs/thinking) process that improves function calling. The SDKs automatically handle [thought signatures](/gemini-api/docs/thought-signatures) for you. Parallel function calling Call multiple functions at once when they are independent: Python`power_disco_ball = {\"type\": \"function\", \"name\": \"power_disco_ball\", \"description\": \"Powers the disco ball.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"power\": {\"type\": \"boolean\"}}, \"required\": [\"power\"]}} start_music = {\"type\": \"function\", \"name\": \"start_music\", \"description\": \"Play music.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"energetic\": {\"type\": \"boolean\"}, \"loud\": {\"type\": \"boolean\"}}, \"required\": [\"energetic\", \"loud\"]}} dim_lights = {\"type\": \"function\", \"name\": \"dim_lights\", \"description\": \"Dim the lights.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"brightness\": {\"type\": \"number\"}}, \"required\": [\"brightness\"]}} client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Turn this place into a party!\", tools=[power_disco_ball, start_music, dim_lights], generation_config={\"tool_choice\": \"any\"}, ) for step in interaction.steps: if step.type == \"function_call\": args = \", \".join(f\"{key}={val}\" for key, val in step.arguments.items()) print(f\"{step.name}({args})\")` JavaScript`const powerDiscoBall = { type: 'function', name: 'power_disco_ball', description: 'Powers the disco ball.', parameters: { type: 'object', properties: { power: { type: 'boolean' } }, required: ['power'] } }; const startMusic = { type: 'function', name: 'start_music', description: 'Play music.', parameters: { type: 'object', properties: { energetic: { type: 'boolean' }, loud: { type: 'boolean' } }, required: ['energetic', 'loud'] } }; const dimLights = { type: 'function', name: 'dim_lights', description: 'Dim the lights.', parameters: { type: 'object', properties: { brightness: { type: 'number' } }, required: ['brightness'] } }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Turn this place into a party!', tools: [powerDiscoBall, startMusic, dimLights], generation_config: { tool_choice: 'any' }, }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`${step.name}(${JSON.stringify(step.arguments)})`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Turn this place into a party!\", \"tools\": [ { \"type\": \"function\", \"name\": \"power_disco_ball\", \"description\": \"Powers the disco ball.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"power\": {\"type\": \"boolean\"} }, \"required\": [\"power\"] } }, { \"type\": \"function\", \"name\": \"start_music\", \"description\": \"Play music.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"energetic\": {\"type\": \"boolean\"}, \"loud\": {\"type\": \"boolean\"} }, \"required\": [\"energetic\", \"loud\"] } }, { \"type\": \"function\", \"name\": \"dim_lights\", \"description\": \"Dim the lights.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": {\"type\": \"number\"} }, \"required\": [\"brightness\"] } } ] }'` Compositional function calling Chain multiple function calls together for complex requests (e.g., get location\nfirst, then get weather for that location). Python`get_weather_forecast_declaration = { \"type\": \"function\", \"name\": \"get_weather_forecast\", \"description\": \"Gets the current weather temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The location\"}, }, \"required\": [\"location\"], }, } set_thermostat_temperature_declaration = { \"type\": \"function\", \"name\": \"set_thermostat_temperature\", \"description\": \"Sets the thermostat to a desired temperature.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"temperature\": { \"type\": \"integer\", \"description\": \"The temperature in Celsius\", }, }, \"required\": [\"temperature\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", tools=[ get_weather_forecast_declaration, set_thermostat_temperature_declaration, ], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\") elif hasattr(step, \"content\") and step.content: for part in step.content: if hasattr(part, \"text\"): print(part.text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const getWeatherForecastTool = { type: 'function', name: 'get_weather_forecast', description: 'Gets the current weather temperature for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The location' }, }, required: ['location'], }, }; const setThermostatTemperatureTool = { type: 'function', name: 'set_thermostat_temperature', description: 'Sets the thermostat to a desired temperature.', parameters: { type: 'object', properties: { temperature: { type: 'integer', description: 'The temperature in Celsius', }, }, required: ['temperature'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", tools: [ getWeatherForecastTool, setThermostatTemperatureTool, ], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } else if (step.content) { for (const part of step.content) { if (part.text) { console.log(part.text); } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"If it'\\''s warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", \"tools\": [ { \"type\": \"function\", \"name\": \"get_weather_forecast\", \"description\": \"Gets the current weather temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\"} }, \"required\": [\"location\"] } }, { \"type\": \"function\", \"name\": \"set_thermostat_temperature\", \"description\": \"Sets the thermostat to a desired temperature.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"temperature\": {\"type\": \"integer\"} }, \"required\": [\"temperature\"] } } ] }'` Function calling modes Control how the model uses tools using `tool_choice` in `generation_config`: `auto` (Default): Model decides whether to call a function or respond directly. `any`: Model is constrained to always predict a function call. `none`: Model is prohibited from making function calls. `validated`: Model ensures function schema adherence. Python`generation_config = { \"tool_choice\": { \"allowed_tools\": { \"mode\": \"any\", \"tools\": [\"get_current_temperature\"] } } }` JavaScript`const generation_config = { tool_choice: { allowed_tools: { mode: 'any', tools: ['get_current_temperature'] } } };` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the temperature in Boston?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\"} }, \"required\": [\"location\"] } }], \"generation_config\": { \"tool_choice\": { \"allowed_tools\": { \"mode\": \"any\", \"tools\": [\"get_current_temperature\"] } } } }'` Multi-tool use You can enable multiple tools, combining built-in tools with function calling in\nthe same request. Gemini 3 models can combine built-in tools with function\ncalling out-of-the-box in Interactions. Passing `previous_interaction_id`\nautomatically circulates the built-in tool context. Python`from google import genai import json client = genai.Client() get_weather = { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a requested city.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"city\": { \"type\": \"string\", \"description\": \"The city and state, e.g. UtqiaÄĄvik, Alaska\", }, }, \"required\": [\"city\"], }, } tools = [ {\"type\": \"google_search\"}, get_weather ] interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What is the northernmost city in the United States? What's the weather like there today?\", tools=tools ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function call: {step.name} (ID: {step.id})\") result = {\"response\": \"Very cold. 22 degrees Fahrenheit.\"} interaction_2 = client.interactions.create( model=\"gemini-3.8-flash\", previous_interaction_id=interaction.id, tools=tools, input=[{ \"type\": \"function_result\", \"name\": step.name, \"call_id\": step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}] }] ) print(interaction_2.output_text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherTool = { type: 'function', name: 'get_weather', description: 'Gets the weather for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA', }, }, required: ['location'], }, }; const tools = [ { type: 'google_search' }, // Built-in tool weatherTool, ]; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"What is the northernmost city in the United States? What's the weather like there today?\", tools: tools, }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function call: ${step.name} (ID: ${step.id})`); const result = { response: 'Very cold. 22 degrees Fahrenheit.' }; const interaction_2 = await client.interactions.create({ model: 'gemini-3.8-flash', previous_interaction_id: interaction.id, tools: tools, input: [ { type: 'function_result', name: step.name, call_id: step.id, result: [{ type: 'text', text: JSON.stringify(result) }], }, ], }); console.log(interaction_2.output_text); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`# Turn 1: Send request with built-in google_search tool and custom weather tool\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the northernmost city in the United States? What'\\''s the weather like there today?\", \"tools\": [ {\"type\": \"google_search\"}, { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state, e.g. San Francisco, CA\"} }, \"required\": [\"location\"] } } ] }' # Turn 2: Provide function result and pass previous_interaction_id\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"previous_interaction_id\": \"INTERACTION_ID\", \"tools\": [ {\"type\": \"google_search\"}, { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state, e.g. San Francisco, CA\"} }, \"required\": [\"location\"] } } ], \"input\": [ { \"type\": \"function_result\", \"name\": \"get_weather\", \"call_id\": \"call_123\", \"result\": [{\"type\": \"text\", \"text\": \"{\\\"response\\\": \\\"Very cold. 22 degrees Fahrenheit.\\\"}\"}] } ] }'` Multimodal function responses For Gemini 3 series models, you can include multimodal content in\nthe function response parts that you send to the model. The model can process\nthis multimodal content in its next turn to produce a more informed response. To include multimodal data in a function response, include it as one or more content blocks in the `result` field of the `function_result` step. Each content block must specify its `type` (e.g., `\"text\"`, `\"image\"`). The following example shows how to send a function response containing image data back to the model in an interaction: Python`import base64 from google import genai import requests client = genai.Client() tool_call = next(s for s in interaction.steps if s.type == \"function_call\") image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content base64_image_data = base64.b64encode(image_bytes).decode(\"utf-8\") final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", previous_interaction_id=interaction.id, input=[ { \"type\": \"function_result\", \"name\": tool_call.name, \"call_id\": tool_call.id, \"result\": [ {\"type\": \"text\", \"text\": \"instrument.jpg\"}, { \"type\": \"image\", \"mime_type\": \"image/jpeg\", \"data\": base64_image_data, }, ], } ], ) print(final_interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const toolCall = interaction.steps.find(s => s.type === 'function_call'); const base64ImageData = \"BASE64_IMAGE_DATA\"; const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', previous_interaction_id: interaction.id, input: [{ type: 'function_result', name: toolCall.name, call_id: toolCall.id, result: [ { type: 'text', text: 'instrument.jpg' }, { type: 'image', mime_type: 'image/jpeg', data: base64ImageData, } ] }] }); console.log(finalInteraction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"previous_interaction_id\": \"INTERACTION_ID\", \"input\": [ { \"type\": \"function_result\", \"name\": \"get_image\", \"call_id\": \"call_123\", \"result\": [ {\"type\": \"text\", \"text\": \"instrument.jpg\"}, { \"type\": \"image\", \"mime_type\": \"image/jpeg\", \"data\": \"BASE64_IMAGE_DATA\" } ] } ] }'` Function calling with Structured output For Gemini 3 series models, combine function calling with\n[structured output](/gemini-api/docs/structured-output) for\nconsistently formatted responses. Remote MCP (Model Context Protocol) Interactions API supports connecting to remote MCP servers to give the model access to external tools and services. You provide the server `name` and `url` in the tools configuration. When using Remote MCP, be aware of the following constraints: **Server types**: Remote MCP only works with Streamable HTTP servers. SSE (Server-Sent Events) servers are not supported. **Naming**: MCP server names should not include the `-` character. Use `snake_case` server names instead. Field Type Required Description `type` `string` Yes Must be `\"mcp_server\"`. `name` `string` No A display name for the MCP server. `url` `string` No The full URL for the MCP server endpoint. `headers` `object` No Key-value pairs sent as HTTP headers with every request to the server (for example, authentication tokens). `allowed_tools` `array` No Restrict which tools from the server the agent may call. Example Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Check the weather in San Francisco.\", tools=[ { \"type\": \"mcp_server\", \"name\": \"weather\", \"url\": \"https://gemini-api-demos.uc.r.appspot.com/mcp\", } ] )` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Check the weather in San Francisco.', tools: [ { type: 'mcp_server', name: 'weather', url: 'https://gemini-api-demos.uc.r.appspot.com/mcp' } ] });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Check the weather in San Francisco.\", \"tools\": [ { \"type\": \"mcp_server\", \"name\": \"weather\", \"url\": \"https://gemini-api-demos.uc.r.appspot.com/mcp\" } ] }'` Stream tool calls When using tools with streaming, the model generates function calls as a\nsequence of `step.delta` events on the stream. Tool arguments can be streamed\nas partial arguments using `arguments`. You must aggregate these deltas to\nreconstruct the complete tool calls before executing them. Python`import json from google import genai client = genai.Client() weather_tool = { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state\"} }, \"required\": [\"location\"] } } stream = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What is the weather in Paris?\", tools=[weather_tool], stream=True ) current_calls = {} tool_calls = [] for event in stream: if event.event_type == \"step.start\": if event.step.type == \"function_call\": current_calls[event.index] = { \"id\": event.step.id, \"name\": event.step.name, \"arguments\": \"\" } if hasattr(event.step, \"arguments\") and event.step.arguments: if isinstance(event.step.arguments, dict): current_calls[event.index][\"arguments\"] = json.dumps(event.step.arguments) else: current_calls[event.index][\"arguments\"] = event.step.arguments elif event.event_type == \"step.delta\": if event.delta.type == \"arguments\": if event.index in current_calls: current_calls[event.index][\"arguments\"] += event.delta.partial_arguments elif event.delta.type == \"text\": print(event.delta.text, end=\"\", flush=True) elif event.event_type == \"interaction.completed\": for index, call in current_calls.items(): args = call[\"arguments\"] if args: args = json.loads(args) else: args = {} tool_calls.append({ \"type\": \"function_call\", \"id\": call[\"id\"], \"name\": call[\"name\"], \"arguments\": args }) print(f\"\\nFinal tool calls ready to execute:\") print(json.dumps(tool_calls, indent=2))` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherTool = { type: 'function', name: 'get_weather', description: 'Gets the weather for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city and state' } }, required: ['location'] } }; const stream = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'What is the weather in Paris?', tools: [weatherTool], stream: true, }); const currentCalls = new Map(); let toolCalls = []; for await (const event of stream) { const evType = event.event_type; if (evType === 'step.start') { if (event.step.type === 'function_call') { currentCalls.set(event.index, { id: event.step.id, name: event.step.name, arguments: '' }); if (event.step.arguments) { if (typeof event.step.arguments === 'object') { currentCalls.get(event.index).arguments = JSON.stringify(event.step.arguments); } else { currentCalls.get(event.index).arguments = event.step.arguments; } } } } else if (evType === 'step.delta') { if (event.delta.type === 'arguments') { if (currentCalls.has(event.index)) { currentCalls.get(event.index).arguments += event.delta.partial_arguments; } } else if (event.delta.type === 'text') { process.stdout.write(event.delta.text); } } else if (evType === 'interaction.completed' || evType === 'interaction.complete') { toolCalls = Array.from(currentCalls.values()).map(call => ({ type: 'function_call', id: call.id, name: call.name, arguments: call.arguments ? JSON.parse(call.arguments) : {} })); console.log('\\nFinal tool calls ready to execute:'); console.log(JSON.stringify(toolCalls, null, 2)); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the weather in Paris?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state\"} }, \"required\": [\"location\"] } }], \"stream\": true }'` Best practices **Function and Parameter Descriptions:** Be clear and specific. **Naming:** Use descriptive names without spaces or special characters. **Strong Typing:** Use specific types (integer, string, enum). **Tool Selection:** Keep active set to 10-20 tools maximum. **Prompt Engineering:** Provide context and instructions. **Validation:** Validate function calls before executing. **Error Handling:** Implement robust error handling. **Security:** Use appropriate authentication for external APIs. Workarounds for pre-tool text requirements **Issue:** If your prompt requires the model to output structured text (XML, YAML, JSON, etc.) (e.g., `...`) immediately before making a tool call, the tool call may occasionally fail with `Malformed_Function_Call`. **Solutions:** The following workarounds resolve this issue: **PREFERRED:** Instruct the model to put its pre-tool notes inside a dedicated `update()` function call instead of raw text (details below). Instruct the model to write notes as Markdown headers (`# UPDATE`, `## PLAN`) instead of structured text. Do not require the model to output text before tool calls. Preferred workaround: Wrap working notes in a dedicated function call Instead of the original instruction: `Before calling a tool, in every response you MUST first output a single `` part as specified, don't skip this part or any of required sub-tags within ``.` Use this updated instruction: `Before calling any other tool, in every response you MUST first call `update` with all required parameters (previous_step, plan, next_step, external).` And update all references to the old `` XML format in the customer request. Then add the corresponding function declaration for the update function: `{ \"name\": \"update\", \"description\": \"Update working notes (previous step analysis, plan, next step, external note).\", \"parameters\": { \"type\": \"OBJECT\", \"properties\": { \"previous_step\": { \"type\": \"STRING\", \"description\": \"Key findings and outcomes since the previous step.\" }, \"plan\": { \"type\": \"STRING\", \"description\": \"The current status of the plan.\" }, \"next_step\": { \"type\": \"STRING\", \"description\": \"Brief explanation of the immediate next action according to the plan.\" }, \"external\": { \"type\": \"STRING\", \"description\": \"A short, plain-language note shown to the User about what you are ABOUT TO DO next.\" } }, \"required\": [ \"previous_step\", \"plan\", \"next_step\", \"external\" ] } }` Then the model will make two calls in the same step: the `update()` call that replaces the structured XML, and the actual function call it wants to make. Notes and limitations Only a [subset of the OpenAPI schema](/api/rest/v1beta/cachedContents#FunctionDeclaration) is supported. For `any` mode, the API may reject very large or deeply nested schemas. Supported parameter types in Python are limited. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-03 UTC.", "znaku_textu": 65538, "slov": 6786, "odkazu": 133, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 08:42:18", "sha256": "03c83872e526df11d6b53728c3c2d8e7d82c4091035a35b676a0e602db1488e0", "hloubka": 2, "zdroj_objevu": "odkaz", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/function-calling?example=meeting", "titulek": "Function calling with the Gemini API | Google AI for Developers", "h1": "Function calling with the Gemini API", "popis": "Get started using Function Calling with the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/function-calling", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Function calling with the Gemini API  |  Google AI for Developers", "og:description": "Get started using Function Calling with the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/function-calling", "og:image": "https://ai.google.dev/static/site-assets/images/function-calling.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Function calling with the Gemini API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Function calling with the Gemini API", "item": "https://ai.google.dev/gemini-api/docs/function-calling"}]}], "drobecky": ["Gemini API", "Function calling with the Gemini API"], "osnova": [{"uroven": 1, "text": "Function calling with the Gemini API"}, {"uroven": 3, "text": "Schedule Meeting"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Get Weather"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Create Chart"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How function calling works"}, {"uroven": 3, "text": "Step 1: Define a function declaration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 2: Call the model with function declarations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 3: Execute the function"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Step 4: Send result back to model"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Stateless function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function declarations"}, {"uroven": 2, "text": "Function calling with thinking models"}, {"uroven": 2, "text": "Parallel function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Compositional function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function calling modes"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multi-tool use"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multimodal function responses"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function calling with Structured output"}, {"uroven": 2, "text": "Remote MCP (Model Context Protocol)"}, {"uroven": 3, "text": "Example"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Stream tool calls"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Workarounds for pre-tool text requirements"}, {"uroven": 3, "text": "Preferred workaround: Wrap working notes in a dedicated function call"}, {"uroven": 2, "text": "Notes and limitations"}], "markdown": "Function calling with the Gemini API Function calling lets you connect models to external tools and APIs.\nInstead of generating text responses, the model determines when to call specific\nfunctions and provides the necessary parameters to execute real-world actions.\nThis allows the model to act as a bridge between natural language and real-world\nactions and data. Function calling has 3 primary use cases: **Take Actions:** Interact with external systems using APIs, such as\nscheduling appointments, creating invoices, sending emails, or controlling\nsmart home devices. **Augment Knowledge:** Access information from external sources like\ndatabases, APIs, and knowledge bases. **Extend Capabilities:** Use external tools to perform computations and\nextend the limitations of the model, such as using a calculator or creating\ncharts. You can browse examples of these use cases below: Schedule Meeting This example shows how to define a function that schedules a meeting with attendees at a specific time, allowing the model to parse user requests and return structured arguments to trigger actions in external systems. Python`from google import genai schedule_meeting_function = { \"type\": \"function\", \"name\": \"schedule_meeting\", \"description\": \"Schedules a meeting with specified attendees at a given time and date.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"attendees\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"date\": {\"type\": \"string\", \"description\": \"Date (e.g., '2024-07-29')\"}, \"time\": {\"type\": \"string\", \"description\": \"Time (e.g., '15:00')\"}, \"topic\": {\"type\": \"string\", \"description\": \"The meeting topic.\"}, }, \"required\": [\"attendees\", \"date\", \"time\", \"topic\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning.\", tools=[{\"type\": \"function\", **schedule_meeting_function}], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const scheduleMeetingFunction = { type: 'function', name: 'schedule_meeting', description: 'Schedules a meeting with specified attendees at a given time and date.', parameters: { type: 'object', properties: { attendees: { type: 'array', items: { type: 'string' } }, date: { type: 'string', description: 'Date (e.g., \"2024-07-29\")' }, time: { type: 'string', description: 'Time (e.g., \"15:00\")' }, topic: { type: 'string', description: 'The meeting topic.' }, }, required: ['attendees', 'date', 'time', 'topic'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.', tools: [scheduleMeetingFunction], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map attendeesProp = new HashMap<>(); attendeesProp.put(\"type\", \"array\"); Map itemsMap = new HashMap<>(); itemsMap.put(\"type\", \"string\"); attendeesProp.put(\"items\", itemsMap); Map dateProp = new HashMap<>(); dateProp.put(\"type\", \"string\"); dateProp.put(\"description\", \"Date (e.g., \\\"2024-07-29\\\")\"); Map timeProp = new HashMap<>(); timeProp.put(\"type\", \"string\"); timeProp.put(\"description\", \"Time (e.g., \\\"15:00\\\")\"); Map topicProp = new HashMap<>(); topicProp.put(\"type\", \"string\"); topicProp.put(\"description\", \"The meeting topic.\"); Map properties = new HashMap<>(); properties.put(\"attendees\", attendeesProp); properties.put(\"date\", dateProp); properties.put(\"time\", timeProp); properties.put(\"topic\", topicProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"attendees\", \"date\", \"time\", \"topic\")); Function scheduleMeetingFunction = Function.builder() .name(\"schedule_meeting\") .description(\"Schedules a meeting with specified attendees at a given time and date.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.\")) .tools(Arrays.asList(scheduleMeetingFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(\"Function to call: \" + functionCall.name().orElse(\"\")); System.out.println(\"Arguments: \" + functionCall.arguments().orElse(null)); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.\", \"tools\": [{ \"type\": \"function\", \"name\": \"schedule_meeting\", \"description\": \"Schedules a meeting with specified attendees at a given time and date.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"attendees\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"date\": {\"type\": \"string\"}, \"time\": {\"type\": \"string\"}, \"topic\": {\"type\": \"string\"} }, \"required\": [\"attendees\", \"date\", \"time\", \"topic\"] } }] }'` Get Weather This example shows how to define a function that retrieves temperature data for a location, enabling the model to call external APIs to answer queries requiring real-time or external information. Python`from google import genai weather_function = { \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": { \"type\": \"string\", \"description\": \"The city name, e.g. San Francisco\", }, }, \"required\": [\"location\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What's the temperature in London?\", tools=[weather_function], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherFunctionDeclaration = { type: 'function', name: 'get_current_temperature', description: 'Gets the current temperature for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city name, e.g. San Francisco', }, }, required: ['location'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"What's the temperature in London?\", tools: [weatherFunctionDeclaration], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map locationProp = new HashMap<>(); locationProp.put(\"type\", \"string\"); locationProp.put(\"description\", \"The city name, e.g. San Francisco\"); Map properties = new HashMap<>(); properties.put(\"location\", locationProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"location\")); Function weatherFunction = Function.builder() .name(\"get_current_temperature\") .description(\"Gets the current temperature for a given location.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"What's the temperature in London?\")) .tools(Arrays.asList(weatherFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(\"Function to call: \" + functionCall.name().orElse(\"\")); System.out.println(\"Arguments: \" + functionCall.arguments().orElse(null)); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What'\\''s the temperature in London?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city name\"} }, \"required\": [\"location\"] } }] }'` Create Chart This example shows how to define a function that generates a bar chart from structured data, demonstrating how the model can use external tools to perform computations or create visual assets: Python`from google import genai create_chart_function = { \"type\": \"function\", \"name\": \"create_bar_chart\", \"description\": \"Creates a bar chart given a title, labels, and values.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"title\": {\"type\": \"string\", \"description\": \"The title for the chart.\"}, \"labels\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"values\": {\"type\": \"array\", \"items\": {\"type\": \"number\"}}, }, \"required\": [\"title\", \"labels\", \"values\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\", tools=[create_chart_function], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const createChartFunctionDeclaration = { type: 'function', name: 'create_bar_chart', description: 'Creates a bar chart given a title, labels, and values.', parameters: { type: 'object', properties: { title: { type: 'string', description: 'The title for the chart.' }, labels: { type: 'array', items: { type: 'string' } }, values: { type: 'array', items: { type: 'number' } }, }, required: ['title', 'labels', 'values'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\", tools: [createChartFunctionDeclaration], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`${step.name}(${JSON.stringify(step.arguments)})`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map properties = new HashMap<>(); Map titleMap = new HashMap<>(); titleMap.put(\"type\", \"string\"); titleMap.put(\"description\", \"The title for the chart.\"); properties.put(\"title\", titleMap); Map labelsMap = new HashMap<>(); labelsMap.put(\"type\", \"array\"); labelsMap.put(\"items\", Collections.singletonMap(\"type\", \"string\")); properties.put(\"labels\", labelsMap); Map valuesMap = new HashMap<>(); valuesMap.put(\"type\", \"array\"); valuesMap.put(\"items\", Collections.singletonMap(\"type\", \"number\")); properties.put(\"values\", valuesMap); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"title\", \"labels\", \"values\")); Function createChartFunction = Function.builder() .name(\"create_bar_chart\") .description(\"Creates a bar chart given a title, labels, and values.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.\")) .tools(Arrays.asList(createChartFunction)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep functionCall = (FunctionCallStep) step; System.out.println(functionCall.name().orElse(\"\") + \"(\" + functionCall.arguments().orElse(null) + \")\"); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Create a bar chart titled '\\''Quarterly Sales'\\'' with Q1: 50000, Q2: 75000, Q3: 60000.\", \"tools\": [{ \"type\": \"function\", \"name\": \"create_bar_chart\", \"description\": \"Creates a bar chart given a title, labels, and values.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"title\": {\"type\": \"string\"}, \"labels\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"values\": {\"type\": \"array\", \"items\": {\"type\": \"number\"}} }, \"required\": [\"title\", \"labels\", \"values\"] } }] }'` How function calling works Function calling involves a structured interaction between your application, the\nmodel, and external functions: **Define Function Declaration:** Define the function's name, parameters, and\npurpose to the model. **Call LLM with function declarations:** Send user prompt along with the\nfunction declaration(s) to the model. **Execute Function Code (Your Responsibility):** The model *doesn't*\nexecute the function itself. Extract the name and args and execute in\nyour application. **Create User friendly response:** Send the result back to the model for a\nfinal, user-friendly response. This process can be repeated over multiple turns. The model supports calling\nmultiple functions in a single turn (parallel function calling) and in sequence (compositional function calling). Step 1: Define a function declaration Python`set_light_values_declaration = { \"type\": \"function\", \"name\": \"set_light_values\", \"description\": \"Sets the brightness and color temperature of a light.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": { \"type\": \"integer\", \"description\": \"Light level from 0 to 100\", }, \"color_temp\": { \"type\": \"string\", \"enum\": [\"daylight\", \"cool\", \"warm\"], \"description\": \"Color temperature\", }, }, \"required\": [\"brightness\", \"color_temp\"], }, } def set_light_values(brightness: int, color_temp: str) -> dict: \"\"\"Set the brightness and color temperature of a room light.\"\"\" return {\"brightness\": brightness, \"colorTemperature\": color_temp}` JavaScript`const setLightValuesTool = { type: 'function', name: 'set_light_values', description: 'Sets the brightness and color temperature of a light.', parameters: { type: 'object', properties: { brightness: { type: 'number', description: 'Light level from 0 to 100' }, color_temp: { type: 'string', enum: ['daylight', 'cool', 'warm'] }, }, required: ['brightness', 'color_temp'], }, }; function setLightValues(brightness, color_temp) { return { brightness: brightness, colorTemperature: color_temp }; }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Step 2: Call the model with function declarations Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Turn the lights down to a romantic level\", tools=[set_light_values_declaration], ) fc_step = next(s for s in interaction.steps if s.type == \"function_call\") print(fc_step)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Turn the lights down to a romantic level', tools: [setLightValuesTool], }); const fcStep = interaction.steps.find(s => s.type === 'function_call'); console.log(fcStep);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` The model returns a `function_call` step with `type`, `name`, and `arguments`: `type='function_call' name='set_light_values' arguments={'color_temp': 'warm', 'brightness': 25}` Step 3: Execute the function Python`fc_step = next(s for s in interaction.steps if s.type == \"function_call\") if fc_step.name == \"set_light_values\": result = set_light_values(**fc_step.arguments) print(f\"Function execution result: {result}\")` JavaScript`const fcStep = interaction.steps.find(s => s.type === 'function_call'); let result; if (fcStep.name === 'set_light_values') { result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp); console.log(`Function execution result: ${JSON.stringify(result)}`); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Step 4: Send result back to model Python`final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=[ { \"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}], } ], tools=[set_light_values_declaration], previous_interaction_id=interaction.id, ) print(final_interaction.output_text)` JavaScript`const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', input: [{ type: 'function_result', name: fcStep.name, call_id: fcStep.id, result: [{ type: 'text', text: JSON.stringify(result) }] }], tools: [setLightValuesTool], previous_interaction_id: interaction.id, }); console.log(finalInteraction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` Stateless function calling You can also use function calling in stateless mode by managing the conversation history on the client side and setting `store=false`. In stateless mode, you must pass the full history of the conversation in the `input` field of each subsequent request. This history must include:\n1. The initial `user_input` step.\n2. All model-generated steps returned in Turn 1 (including `thought` and `function_call` steps) exactly as received.\n3. The `function_result` step containing the output of your executed function. Python`from google import genai import json client = genai.Client() history = [ { \"type\": \"user_input\", \"content\": [{\"type\": \"text\", \"text\": \"Turn the lights down to a romantic level\"}] } ] interaction = client.interactions.create( model=\"gemini-3.8-flash\", store=False, input=history, tools=[set_light_values_declaration], ) for step in interaction.steps: history.append(step.model_dump()) fc_step = next(s for s in interaction.steps if s.type == \"function_call\") if fc_step.name == \"set_light_values\": result = set_light_values(**fc_step.arguments) history.append({ \"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}], }) final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", store=False, input=history, tools=[set_light_values_declaration], ) print(final_interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); async function main() { const history = [ { type: \"user_input\", content: [{ type: \"text\", text: \"Turn the lights down to a romantic level\" }] } ]; const interaction = await client.interactions.create({ model: \"gemini-3.8-flash\", store: false, input: history, tools: [setLightValuesTool], }); history.push(...interaction.steps); const fcStep = interaction.steps.find(s => s.type === 'function_call'); let result; if (fcStep.name === 'set_light_values') { result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp); } history.push({ type: 'function_result', name: fcStep.name, call_id: fcStep.id, result: [{ type: 'text', text: JSON.stringify(result) }] }); const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', store: false, input: history, tools: [setLightValuesTool], }); console.log(finalInteraction.output_text); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`# Turn 1: Send request with tools and store: false RESPONSE1=$(curl -s -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"store\": false, \"input\": [ { \"type\": \"user_input\", \"content\": \"Turn the lights down to a romantic level\" } ], \"tools\": [{ \"type\": \"function\", \"name\": \"set_light_values\", \"description\": \"Sets the brightness and color temperature of a light.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": {\"type\": \"integer\", \"description\": \"Light level from 0 to 100\"}, \"color_temp\": {\"type\": \"string\", \"enum\": [\"daylight\", \"cool\", \"warm\"]} }, \"required\": [\"brightness\", \"color_temp\"] } }] }') # Extract model steps (thought, function_call) MODEL_STEPS=$(echo \"$RESPONSE1\" | jq '.steps') # Extract function call details to execute FC_NAME=$(echo \"$RESPONSE1\" | jq -r '.steps[] | select(.type==\"function_call\") | .name') FC_ID=$(echo \"$RESPONSE1\" | jq -r '.steps[] | select(.type==\"function_call\") | .id') # Assume local execution returns: {\"brightness\": 25, \"colorTemperature\": \"warm\"} RESULT=\"{\\\"brightness\\\": 25, \\\"colorTemperature\\\": \\\"warm\\\"}\" # Reconstruct history for Turn 2 HISTORY=$(jq -n \\ --argjson first_input '[{\"type\": \"user_input\", \"content\": \"Turn the lights down to a romantic level\"}]' \\ --argjson model_steps \"$MODEL_STEPS\" \\ --arg fc_name \"$FC_NAME\" \\ --arg fc_id \"$FC_ID\" \\ --arg result \"$RESULT\" \\ '$first_input + $model_steps + [{\"type\": \"function_result\", \"name\": $fc_name, \"call_id\": $fc_id, \"result\": [{\"type\": \"text\", \"text\": $result}]}]') # Turn 2: Send the full history\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d \"{ \\\"model\\\": \\\"gemini-3.8-flash\\\", \\\"store\\\": false, \\\"input\\\": $HISTORY, \\\"tools\\\": [{ \\\"type\\\": \\\"function\\\", \\\"name\\\": \\\"set_light_values\\\", \\\"description\\\": \\\"Sets the brightness and color temperature of a light.\\\", \\\"parameters\\\": { \\\"type\\\": \\\"object\\\", \\\"properties\\\": { \\\"brightness\\\": {\\\"type\\\": \\\"integer\\\"}, \\\"color_temp\\\": {\\\"type\\\": \\\"string\\\"} }, \\\"required\\\": [\\\"brightness\\\", \\\"color_temp\\\"] } }] }\"` Function declarations A function declaration is passed as a tool and includes: `type` (string): Must be `\"function\"` for custom functions. `name` (string): Unique function name (use underscores or camelCase). `description` (string): Clear explanation of the function's purpose. `parameters` (object): Input parameters the function expects.\n `type` (string): Overall data type, such as `object`. `properties` (object): Individual parameters with type and description. `required` (array): Mandatory parameter names. Function calling with thinking models Gemini 3 series models use an internal [\"thinking\"](/gemini-api/docs/thinking) process that improves function calling. The SDKs automatically handle [thought signatures](/gemini-api/docs/thought-signatures) for you. Parallel function calling Call multiple functions at once when they are independent: Python`power_disco_ball = {\"type\": \"function\", \"name\": \"power_disco_ball\", \"description\": \"Powers the disco ball.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"power\": {\"type\": \"boolean\"}}, \"required\": [\"power\"]}} start_music = {\"type\": \"function\", \"name\": \"start_music\", \"description\": \"Play music.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"energetic\": {\"type\": \"boolean\"}, \"loud\": {\"type\": \"boolean\"}}, \"required\": [\"energetic\", \"loud\"]}} dim_lights = {\"type\": \"function\", \"name\": \"dim_lights\", \"description\": \"Dim the lights.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"brightness\": {\"type\": \"number\"}}, \"required\": [\"brightness\"]}} client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Turn this place into a party!\", tools=[power_disco_ball, start_music, dim_lights], generation_config={\"tool_choice\": \"any\"}, ) for step in interaction.steps: if step.type == \"function_call\": args = \", \".join(f\"{key}={val}\" for key, val in step.arguments.items()) print(f\"{step.name}({args})\")` JavaScript`const powerDiscoBall = { type: 'function', name: 'power_disco_ball', description: 'Powers the disco ball.', parameters: { type: 'object', properties: { power: { type: 'boolean' } }, required: ['power'] } }; const startMusic = { type: 'function', name: 'start_music', description: 'Play music.', parameters: { type: 'object', properties: { energetic: { type: 'boolean' }, loud: { type: 'boolean' } }, required: ['energetic', 'loud'] } }; const dimLights = { type: 'function', name: 'dim_lights', description: 'Dim the lights.', parameters: { type: 'object', properties: { brightness: { type: 'number' } }, required: ['brightness'] } }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Turn this place into a party!', tools: [powerDiscoBall, startMusic, dimLights], generation_config: { tool_choice: 'any' }, }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`${step.name}(${JSON.stringify(step.arguments)})`); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Turn this place into a party!\", \"tools\": [ { \"type\": \"function\", \"name\": \"power_disco_ball\", \"description\": \"Powers the disco ball.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"power\": {\"type\": \"boolean\"} }, \"required\": [\"power\"] } }, { \"type\": \"function\", \"name\": \"start_music\", \"description\": \"Play music.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"energetic\": {\"type\": \"boolean\"}, \"loud\": {\"type\": \"boolean\"} }, \"required\": [\"energetic\", \"loud\"] } }, { \"type\": \"function\", \"name\": \"dim_lights\", \"description\": \"Dim the lights.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": {\"type\": \"number\"} }, \"required\": [\"brightness\"] } } ] }'` Compositional function calling Chain multiple function calls together for complex requests (e.g., get location\nfirst, then get weather for that location). Python`get_weather_forecast_declaration = { \"type\": \"function\", \"name\": \"get_weather_forecast\", \"description\": \"Gets the current weather temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The location\"}, }, \"required\": [\"location\"], }, } set_thermostat_temperature_declaration = { \"type\": \"function\", \"name\": \"set_thermostat_temperature\", \"description\": \"Sets the thermostat to a desired temperature.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"temperature\": { \"type\": \"integer\", \"description\": \"The temperature in Celsius\", }, }, \"required\": [\"temperature\"], }, } client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", tools=[ get_weather_forecast_declaration, set_thermostat_temperature_declaration, ], ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function to call: {step.name}\") print(f\"Arguments: {step.arguments}\") elif hasattr(step, \"content\") and step.content: for part in step.content: if hasattr(part, \"text\"): print(part.text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const getWeatherForecastTool = { type: 'function', name: 'get_weather_forecast', description: 'Gets the current weather temperature for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The location' }, }, required: ['location'], }, }; const setThermostatTemperatureTool = { type: 'function', name: 'set_thermostat_temperature', description: 'Sets the thermostat to a desired temperature.', parameters: { type: 'object', properties: { temperature: { type: 'integer', description: 'The temperature in Celsius', }, }, required: ['temperature'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", tools: [ getWeatherForecastTool, setThermostatTemperatureTool, ], }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function to call: ${step.name}`); console.log(`Arguments: ${JSON.stringify(step.arguments)}`); } else if (step.content) { for (const part of step.content) { if (part.text) { console.log(part.text); } } } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"If it'\\''s warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.\", \"tools\": [ { \"type\": \"function\", \"name\": \"get_weather_forecast\", \"description\": \"Gets the current weather temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\"} }, \"required\": [\"location\"] } }, { \"type\": \"function\", \"name\": \"set_thermostat_temperature\", \"description\": \"Sets the thermostat to a desired temperature.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"temperature\": {\"type\": \"integer\"} }, \"required\": [\"temperature\"] } } ] }'` Function calling modes Control how the model uses tools using `tool_choice` in `generation_config`: `auto` (Default): Model decides whether to call a function or respond directly. `any`: Model is constrained to always predict a function call. `none`: Model is prohibited from making function calls. `validated`: Model ensures function schema adherence. Python`generation_config = { \"tool_choice\": { \"allowed_tools\": { \"mode\": \"any\", \"tools\": [\"get_current_temperature\"] } } }` JavaScript`const generation_config = { tool_choice: { allowed_tools: { mode: 'any', tools: ['get_current_temperature'] } } };` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the temperature in Boston?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\"} }, \"required\": [\"location\"] } }], \"generation_config\": { \"tool_choice\": { \"allowed_tools\": { \"mode\": \"any\", \"tools\": [\"get_current_temperature\"] } } } }'` Multi-tool use You can enable multiple tools, combining built-in tools with function calling in\nthe same request. Gemini 3 models can combine built-in tools with function\ncalling out-of-the-box in Interactions. Passing `previous_interaction_id`\nautomatically circulates the built-in tool context. Python`from google import genai import json client = genai.Client() get_weather = { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a requested city.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"city\": { \"type\": \"string\", \"description\": \"The city and state, e.g. UtqiaÄĄvik, Alaska\", }, }, \"required\": [\"city\"], }, } tools = [ {\"type\": \"google_search\"}, get_weather ] interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What is the northernmost city in the United States? What's the weather like there today?\", tools=tools ) for step in interaction.steps: if step.type == \"function_call\": print(f\"Function call: {step.name} (ID: {step.id})\") result = {\"response\": \"Very cold. 22 degrees Fahrenheit.\"} interaction_2 = client.interactions.create( model=\"gemini-3.8-flash\", previous_interaction_id=interaction.id, tools=tools, input=[{ \"type\": \"function_result\", \"name\": step.name, \"call_id\": step.id, \"result\": [{\"type\": \"text\", \"text\": json.dumps(result)}] }] ) print(interaction_2.output_text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherTool = { type: 'function', name: 'get_weather', description: 'Gets the weather for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA', }, }, required: ['location'], }, }; const tools = [ { type: 'google_search' }, // Built-in tool weatherTool, ]; const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: \"What is the northernmost city in the United States? What's the weather like there today?\", tools: tools, }); for (const step of interaction.steps) { if (step.type === 'function_call') { console.log(`Function call: ${step.name} (ID: ${step.id})`); const result = { response: 'Very cold. 22 degrees Fahrenheit.' }; const interaction_2 = await client.interactions.create({ model: 'gemini-3.8-flash', previous_interaction_id: interaction.id, tools: tools, input: [ { type: 'function_result', name: step.name, call_id: step.id, result: [{ type: 'text', text: JSON.stringify(result) }], }, ], }); console.log(interaction_2.output_text); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`# Turn 1: Send request with built-in google_search tool and custom weather tool\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the northernmost city in the United States? What'\\''s the weather like there today?\", \"tools\": [ {\"type\": \"google_search\"}, { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state, e.g. San Francisco, CA\"} }, \"required\": [\"location\"] } } ] }' # Turn 2: Provide function result and pass previous_interaction_id\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"previous_interaction_id\": \"INTERACTION_ID\", \"tools\": [ {\"type\": \"google_search\"}, { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state, e.g. San Francisco, CA\"} }, \"required\": [\"location\"] } } ], \"input\": [ { \"type\": \"function_result\", \"name\": \"get_weather\", \"call_id\": \"call_123\", \"result\": [{\"type\": \"text\", \"text\": \"{\\\"response\\\": \\\"Very cold. 22 degrees Fahrenheit.\\\"}\"}] } ] }'` Multimodal function responses For Gemini 3 series models, you can include multimodal content in\nthe function response parts that you send to the model. The model can process\nthis multimodal content in its next turn to produce a more informed response. To include multimodal data in a function response, include it as one or more content blocks in the `result` field of the `function_result` step. Each content block must specify its `type` (e.g., `\"text\"`, `\"image\"`). The following example shows how to send a function response containing image data back to the model in an interaction: Python`import base64 from google import genai import requests client = genai.Client() tool_call = next(s for s in interaction.steps if s.type == \"function_call\") image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content base64_image_data = base64.b64encode(image_bytes).decode(\"utf-8\") final_interaction = client.interactions.create( model=\"gemini-3.8-flash\", previous_interaction_id=interaction.id, input=[ { \"type\": \"function_result\", \"name\": tool_call.name, \"call_id\": tool_call.id, \"result\": [ {\"type\": \"text\", \"text\": \"instrument.jpg\"}, { \"type\": \"image\", \"mime_type\": \"image/jpeg\", \"data\": base64_image_data, }, ], } ], ) print(final_interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const toolCall = interaction.steps.find(s => s.type === 'function_call'); const base64ImageData = \"BASE64_IMAGE_DATA\"; const finalInteraction = await client.interactions.create({ model: 'gemini-3.8-flash', previous_interaction_id: interaction.id, input: [{ type: 'function_result', name: toolCall.name, call_id: toolCall.id, result: [ { type: 'text', text: 'instrument.jpg' }, { type: 'image', mime_type: 'image/jpeg', data: base64ImageData, } ] }] }); console.log(finalInteraction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.8-flash\", \"previous_interaction_id\": \"INTERACTION_ID\", \"input\": [ { \"type\": \"function_result\", \"name\": \"get_image\", \"call_id\": \"call_123\", \"result\": [ {\"type\": \"text\", \"text\": \"instrument.jpg\"}, { \"type\": \"image\", \"mime_type\": \"image/jpeg\", \"data\": \"BASE64_IMAGE_DATA\" } ] } ] }'` Function calling with Structured output For Gemini 3 series models, combine function calling with\n[structured output](/gemini-api/docs/structured-output) for\nconsistently formatted responses. Remote MCP (Model Context Protocol) Interactions API supports connecting to remote MCP servers to give the model access to external tools and services. You provide the server `name` and `url` in the tools configuration. When using Remote MCP, be aware of the following constraints: **Server types**: Remote MCP only works with Streamable HTTP servers. SSE (Server-Sent Events) servers are not supported. **Naming**: MCP server names should not include the `-` character. Use `snake_case` server names instead. Field Type Required Description `type` `string` Yes Must be `\"mcp_server\"`. `name` `string` No A display name for the MCP server. `url` `string` No The full URL for the MCP server endpoint. `headers` `object` No Key-value pairs sent as HTTP headers with every request to the server (for example, authentication tokens). `allowed_tools` `array` No Restrict which tools from the server the agent may call. Example Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.8-flash\", input=\"Check the weather in San Francisco.\", tools=[ { \"type\": \"mcp_server\", \"name\": \"weather\", \"url\": \"https://gemini-api-demos.uc.r.appspot.com/mcp\", } ] )` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'Check the weather in San Francisco.', tools: [ { type: 'mcp_server', name: 'weather', url: 'https://gemini-api-demos.uc.r.appspot.com/mcp' } ] });` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"Check the weather in San Francisco.\", \"tools\": [ { \"type\": \"mcp_server\", \"name\": \"weather\", \"url\": \"https://gemini-api-demos.uc.r.appspot.com/mcp\" } ] }'` Stream tool calls When using tools with streaming, the model generates function calls as a\nsequence of `step.delta` events on the stream. Tool arguments can be streamed\nas partial arguments using `arguments`. You must aggregate these deltas to\nreconstruct the complete tool calls before executing them. Python`import json from google import genai client = genai.Client() weather_tool = { \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state\"} }, \"required\": [\"location\"] } } stream = client.interactions.create( model=\"gemini-3.8-flash\", input=\"What is the weather in Paris?\", tools=[weather_tool], stream=True ) current_calls = {} tool_calls = [] for event in stream: if event.event_type == \"step.start\": if event.step.type == \"function_call\": current_calls[event.index] = { \"id\": event.step.id, \"name\": event.step.name, \"arguments\": \"\" } if hasattr(event.step, \"arguments\") and event.step.arguments: if isinstance(event.step.arguments, dict): current_calls[event.index][\"arguments\"] = json.dumps(event.step.arguments) else: current_calls[event.index][\"arguments\"] = event.step.arguments elif event.event_type == \"step.delta\": if event.delta.type == \"arguments\": if event.index in current_calls: current_calls[event.index][\"arguments\"] += event.delta.partial_arguments elif event.delta.type == \"text\": print(event.delta.text, end=\"\", flush=True) elif event.event_type == \"interaction.completed\": for index, call in current_calls.items(): args = call[\"arguments\"] if args: args = json.loads(args) else: args = {} tool_calls.append({ \"type\": \"function_call\", \"id\": call[\"id\"], \"name\": call[\"name\"], \"arguments\": args }) print(f\"\\nFinal tool calls ready to execute:\") print(json.dumps(tool_calls, indent=2))` JavaScript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const weatherTool = { type: 'function', name: 'get_weather', description: 'Gets the weather for a given location.', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city and state' } }, required: ['location'] } }; const stream = await client.interactions.create({ model: 'gemini-3.8-flash', input: 'What is the weather in Paris?', tools: [weatherTool], stream: true, }); const currentCalls = new Map(); let toolCalls = []; for await (const event of stream) { const evType = event.event_type; if (evType === 'step.start') { if (event.step.type === 'function_call') { currentCalls.set(event.index, { id: event.step.id, name: event.step.name, arguments: '' }); if (event.step.arguments) { if (typeof event.step.arguments === 'object') { currentCalls.get(event.index).arguments = JSON.stringify(event.step.arguments); } else { currentCalls.get(event.index).arguments = event.step.arguments; } } } } else if (evType === 'step.delta') { if (event.delta.type === 'arguments') { if (currentCalls.has(event.index)) { currentCalls.get(event.index).arguments += event.delta.partial_arguments; } } else if (event.delta.type === 'text') { process.stdout.write(event.delta.text); } } else if (evType === 'interaction.completed' || evType === 'interaction.complete') { toolCalls = Array.from(currentCalls.values()).map(call => ({ type: 'function_call', id: call.id, name: call.name, arguments: call.arguments ? JSON.parse(call.arguments) : {} })); console.log('\\nFinal tool calls ready to execute:'); console.log(JSON.stringify(toolCalls, null, 2)); } }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; Client client = new Client(); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); Function function = Function.builder() .name(\"custom_function\") .description(\"A custom function.\") .parameters(parameters) .build(); CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.6-flash\")) .input(InteractionsInput.of(\"Call the function.\")) .tools(Arrays.asList(function)) .build(); Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get(); if (interaction.steps().isPresent()) { for (Step step : interaction.steps().get()) { if (step instanceof FunctionCallStep) { FunctionCallStep fc = (FunctionCallStep) step; System.out.println(\"Function: \" + fc.name().orElse(\"\")); } } }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse\" \\ -H \"Content-Type: application/json\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"model\": \"gemini-3.8-flash\", \"input\": \"What is the weather in Paris?\", \"tools\": [{ \"type\": \"function\", \"name\": \"get_weather\", \"description\": \"Gets the weather for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": {\"type\": \"string\", \"description\": \"The city and state\"} }, \"required\": [\"location\"] } }], \"stream\": true }'` Best practices **Function and Parameter Descriptions:** Be clear and specific. **Naming:** Use descriptive names without spaces or special characters. **Strong Typing:** Use specific types (integer, string, enum). **Tool Selection:** Keep active set to 10-20 tools maximum. **Prompt Engineering:** Provide context and instructions. **Validation:** Validate function calls before executing. **Error Handling:** Implement robust error handling. **Security:** Use appropriate authentication for external APIs. Workarounds for pre-tool text requirements **Issue:** If your prompt requires the model to output structured text (XML, YAML, JSON, etc.) (e.g., `...`) immediately before making a tool call, the tool call may occasionally fail with `Malformed_Function_Call`. **Solutions:** The following workarounds resolve this issue: **PREFERRED:** Instruct the model to put its pre-tool notes inside a dedicated `update()` function call instead of raw text (details below). Instruct the model to write notes as Markdown headers (`# UPDATE`, `## PLAN`) instead of structured text. Do not require the model to output text before tool calls. Preferred workaround: Wrap working notes in a dedicated function call Instead of the original instruction: `Before calling a tool, in every response you MUST first output a single `` part as specified, don't skip this part or any of required sub-tags within ``.` Use this updated instruction: `Before calling any other tool, in every response you MUST first call `update` with all required parameters (previous_step, plan, next_step, external).` And update all references to the old `` XML format in the customer request. Then add the corresponding function declaration for the update function: `{ \"name\": \"update\", \"description\": \"Update working notes (previous step analysis, plan, next step, external note).\", \"parameters\": { \"type\": \"OBJECT\", \"properties\": { \"previous_step\": { \"type\": \"STRING\", \"description\": \"Key findings and outcomes since the previous step.\" }, \"plan\": { \"type\": \"STRING\", \"description\": \"The current status of the plan.\" }, \"next_step\": { \"type\": \"STRING\", \"description\": \"Brief explanation of the immediate next action according to the plan.\" }, \"external\": { \"type\": \"STRING\", \"description\": \"A short, plain-language note shown to the User about what you are ABOUT TO DO next.\" } }, \"required\": [ \"previous_step\", \"plan\", \"next_step\", \"external\" ] } }` Then the model will make two calls in the same step: the `update()` call that replaces the structured XML, and the actual function call it wants to make. Notes and limitations Only a [subset of the OpenAPI schema](/api/rest/v1beta/cachedContents#FunctionDeclaration) is supported. For `any` mode, the API may reject very large or deeply nested schemas. Supported parameter types in Python are limited. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-03 UTC.", "znaku_textu": 65538, "slov": 6786, "odkazu": 133, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:52:39", "sha256": "ac8a9155b8baec7f8925140afe6f5628a8f01c10d9d5c29a3510459f3b02ed7b", "hloubka": 2, "zdroj_objevu": "odkaz", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/gemini-3", "titulek": "Gemini 3 developer guide | Gemini API | Google AI for Developers", "h1": "Gemini 3 developer guide", "popis": "Learn about the new features of Gemini 3 in the Gemini API.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/gemini-3", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini 3 developer guide  |  Gemini API  |  Google AI for Developers", "og:description": "Learn about the new features of Gemini 3 in the Gemini API.", "og:url": "https://ai.google.dev/gemini-api/docs/gemini-3", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Gemini 3 developer guide"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Gemini 3 developer guide", "item": "https://ai.google.dev/gemini-api/docs/gemini-3"}]}], "drobecky": ["Gemini API", "Gemini 3 developer guide"], "osnova": [{"uroven": 1, "text": "Gemini 3 developer guide"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Meet the Gemini 3 series"}, {"uroven": 2, "text": "New API features in Gemini 3"}, {"uroven": 3, "text": "Level of thinking"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Temperature"}, {"uroven": 3, "text": "Thought signatures"}, {"uroven": 3, "text": "Structured Outputs with tools"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Image generation"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Code Execution with images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Multimodal function responses"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "Combine built-in tools and function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 2, "text": "Migration from Gemini 2.5"}, {"uroven": 2, "text": "OpenAI compatibility"}, {"uroven": 2, "text": "Prompting best practices"}, {"uroven": 2, "text": "FAQ"}], "markdown": "Gemini 3 developer guide Gemini 3 is our most intelligent model family to date, built on a foundation of\nstate-of-the-art reasoning. It is designed to bring any idea to life by\nmastering agentic workflows, autonomous coding, and complex multimodal tasks.\nThis guide covers key features of the Gemini 3 model family and how to get the\nmost out of it. Explore our [collection of Gemini 3 apps](https://aistudio.google.com/app/apps?source=showcase&showcaseTag=gemini-3) to\nsee how the model handles advanced reasoning, autonomous coding, and complex\nmultimodal tasks. Get started with a few lines of code: Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.1-pro-preview\", input=\"Find the race condition in this multi-threaded C++ snippet: [code here]\", ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); async function run() { const interaction = await client.interactions.create({ model: \"gemini-3.1-pro-preview\", input: \"Find the race condition in this multi-threaded C++ snippet: [code here]\", }); console.log(interaction.output_text); } run();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.FunctionResultStep; import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion; import com.google.genai.gaos.models.interactions.FunctionResultSubcontent; import com.google.genai.gaos.models.interactions.ImageContent; import com.google.genai.gaos.models.interactions.ImageContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.interactions.Tool; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; Client client = new Client(); Map itemProp = new HashMap<>(); itemProp.put(\"type\", \"string\"); itemProp.put(\"description\", \"The name or description of the item ordered (e.g., 'instrument').\"); Map properties = new HashMap<>(); properties.put(\"item_name\", itemProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"item_name\")); Function getImageTool = Function.builder() .name(\"get_image\") .description(\"Retrieves the image file reference for a specific order item.\") .parameters(parameters) .build(); CreateModelInteraction req1 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.of(\"Use the get_image tool to show me the instrument I ordered last month.\")) .tools(Arrays.asList(getImageTool)) .build(); Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().get(); FunctionCallStep fcStep = null; for (Step step : interaction1.steps().orElse(Collections.emptyList())) { if (step instanceof FunctionCallStep) { fcStep = (FunctionCallStep) step; break; } } if (fcStep != null) { System.out.println(\"Tool Call: \" + fcStep.name().orElse(\"\")); URL url = new URL(\"https://goo.gle/instrument-img\"); byte[] imageBytes; try (InputStream is = url.openStream()) { imageBytes = is.readAllBytes(); } String base64ImageData = Base64.getEncoder().encodeToString(imageBytes); List subcontents = new ArrayList<>(); subcontents.add(TextContent.builder().text(\"instrument.jpg\").build()); subcontents.add( ImageContent.builder() .mimeType(ImageContentMimeType.IMAGE_JPEG) .data(base64ImageData) .build()); FunctionResultStep funcResult = FunctionResultStep.builder() .name(fcStep.name().orElse(\"\")) .callId(fcStep.id().orElse(\"\")) .result(FunctionResultStepResultUnion.of(subcontents)) .build(); CreateModelInteraction req2 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.ofStep(Arrays.asList(funcResult))) .tools(Arrays.asList(getImageTool)) .previousInteractionId(interaction1.id().orElse(\"\")) .build(); Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().get(); System.out.println(\"Final model response: \" + interaction2.outputText().orElse(\"\")); } ```bash curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.1-pro-preview\", \"input\": \"Find the race condition in this multi-threaded C++ snippet: [code here]\" }'` Meet the Gemini 3 series Gemini 3.1 Pro is best for complex tasks that\nrequire broad world knowledge and advanced reasoning across modalities. Gemini 3 Flash is our latest 3-series model, with Pro-level intelligence at the\nspeed and pricing of Flash. Nano Banana Pro (also known as Gemini 3 Pro Image) is our highest quality image\ngeneration model, and Nano Banana 2 (also known as Gemini 3.1 Flash Image) is\nthe high-volume, high-efficiency, lower price-point equivalent. Gemini 3.1 Flash-Lite is our workhorse model built for cost-efficiency model and\nhigh-volume tasks. All Gemini 3 models are currently in preview. Model ID Context Window (In / Out) Knowledge Cutoff Pricing (Input / Output)* **gemini-3.1-flash-lite** 1M / 64k Jan 2025 $0.25 (text, image, video), $0.50 (audio) / $1.50 **gemini-3.1-flash-image-preview** 128k / 32k Jan 2025 $0.25 (Text Input) / $0.067 (Image Output)** **gemini-3.1-pro-preview** 1M / 64k Jan 2025 $2 / $12 (<200k tokens) \n $4 / $18 (>200k tokens) **gemini-3-flash-preview** 1M / 64k Jan 2025 $0.50 / $3 **gemini-3-pro-image-preview** 65k / 32k Jan 2025 $2 (Text Input) / $0.134 (Image Output)** ** Pricing is per 1 million tokens unless otherwise noted.* *** Image pricing varies by resolution. See the [pricing page](/gemini-api/docs/pricing) for details.* For detailed limits, pricing, and additional information, see the\n[models page](/gemini-api/docs/models/gemini). New API features in Gemini 3 Gemini 3 introduces new parameters designed to give developers more control over\nlatency, cost, and multimodal fidelity. Level of thinking Gemini 3 series models use dynamic thinking by default to reason through\nprompts. You can use the `thinking_level` parameter, which controls the\n**maximum** depth of the model's internal reasoning process before it produces a\nresponse. Gemini 3 treats these levels as relative allowances for thinking\nrather than strict token guarantees. If `thinking_level` is not specified, Gemini 3 will default to `high`. For\nfaster, lower-latency responses when complex reasoning isn't required, you can\nconstrain the model's thinking level to `low`. Thinking Level Gemini 3.1 Pro Gemini 3.1 Flash-Lite Gemini 3 Flash Description **`minimal`** Not supported Supported (Default) Supported Matches the \"no thinking\" setting for most queries. The model may think very minimally for complex coding tasks. Minimizes latency for chat or high throughput applications. Note, `minimal` does not guarantee that thinking is off. **`low`** Supported Supported Supported Minimizes latency and cost. Best for simple instruction following, chat, or high-throughput applications. **`medium`** Supported Supported Supported Balanced thinking for most tasks. **`high`** Supported (Default, Dynamic) Supported (Dynamic) Supported (Default, Dynamic) Maximizes reasoning depth. The model may take significantly longer to\n reach a first (non thinking) output token, but the output will be more carefully reasoned. Python`from google import genai client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.1-pro-preview\", input=\"How does AI work?\", generation_config={\"thinking_level\": \"low\"}, ) print(interaction.output_text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: \"gemini-3.1-pro-preview\", input: \"How does AI work?\", generation_config: { thinking_level: \"low\", }, }); console.log(interaction.output_text);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.FunctionResultStep; import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion; import com.google.genai.gaos.models.interactions.FunctionResultSubcontent; import com.google.genai.gaos.models.interactions.ImageContent; import com.google.genai.gaos.models.interactions.ImageContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.interactions.Tool; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; Client client = new Client(); Map itemProp = new HashMap<>(); itemProp.put(\"type\", \"string\"); itemProp.put(\"description\", \"The name or description of the item ordered (e.g., 'instrument').\"); Map properties = new HashMap<>(); properties.put(\"item_name\", itemProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"item_name\")); Function getImageTool = Function.builder() .name(\"get_image\") .description(\"Retrieves the image file reference for a specific order item.\") .parameters(parameters) .build(); CreateModelInteraction req1 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.of(\"Use the get_image tool to show me the instrument I ordered last month.\")) .tools(Arrays.asList(getImageTool)) .build(); Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().get(); FunctionCallStep fcStep = null; for (Step step : interaction1.steps().orElse(Collections.emptyList())) { if (step instanceof FunctionCallStep) { fcStep = (FunctionCallStep) step; break; } } if (fcStep != null) { System.out.println(\"Tool Call: \" + fcStep.name().orElse(\"\")); URL url = new URL(\"https://goo.gle/instrument-img\"); byte[] imageBytes; try (InputStream is = url.openStream()) { imageBytes = is.readAllBytes(); } String base64ImageData = Base64.getEncoder().encodeToString(imageBytes); List subcontents = new ArrayList<>(); subcontents.add(TextContent.builder().text(\"instrument.jpg\").build()); subcontents.add( ImageContent.builder() .mimeType(ImageContentMimeType.IMAGE_JPEG) .data(base64ImageData) .build()); FunctionResultStep funcResult = FunctionResultStep.builder() .name(fcStep.name().orElse(\"\")) .callId(fcStep.id().orElse(\"\")) .result(FunctionResultStepResultUnion.of(subcontents)) .build(); CreateModelInteraction req2 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.ofStep(Arrays.asList(funcResult))) .tools(Arrays.asList(getImageTool)) .previousInteractionId(interaction1.id().orElse(\"\")) .build(); Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().get(); System.out.println(\"Final model response: \" + interaction2.outputText().orElse(\"\")); } ```bash curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.1-pro-preview\", \"input\": \"How does AI work?\", \"generation_config\": { \"thinking_level\": \"low\" } }'` Temperature For all Gemini 3 models, we strongly recommend keeping the temperature parameter\nat its default value of `1.0`. While previous models often benefited from tuning temperature to control\ncreativity versus determinism, Gemini 3's reasoning capabilities are optimized\nfor the default setting. Changing the temperature (setting it below 1.0) may\nlead to unexpected behavior, such as looping or degraded performance,\nparticularly in complex mathematical or reasoning tasks. Thought signatures Gemini 3 models use thought signatures to maintain reasoning context across API calls. These signatures are encrypted representations of the model's internal thought process. **Stateful Mode (Recommended)**: When using the Interactions API in stateful mode (providing `previous_interaction_id`), the server automatically manages conversation history and thought signatures. **Stateless Mode**: If you are managing conversation history manually, you must include thought blocks with their signatures in subsequent requests to validate authenticity. For detailed information, see the [Thought Signatures](/gemini-api/docs/thinking) page.` Structured Outputs with tools Gemini 3 models allow you to combine [Structured Outputs](/gemini-api/docs/structured-output) with built-in tools, including\n[Grounding with Google Search](/gemini-api/docs/google-search), [URL Context](/gemini-api/docs/url-context), [Code Execution](/gemini-api/docs/code-execution), and [Function Calling](/gemini-api/docs/function-calling). Python`from google import genai from pydantic import BaseModel, Field from typing import List class MatchResult(BaseModel): winner: str = Field(description=\"The name of the winner.\") final_match_score: str = Field(description=\"The final match score.\") scorers: List[str] = Field(description=\"The name of the scorer.\") client = genai.Client() interaction = client.interactions.create( model=\"gemini-3.1-pro-preview\", input=\"Search for all details for the latest Euro.\", tools=[ {\"type\": \"google_search\"}, {\"type\": \"url_context\"} ], response_format={ \"type\": \"text\", \"mime_type\": \"application/json\", \"schema\": MatchResult.model_json_schema() }, ) result = MatchResult.model_validate_json(interaction.output_text) print(result)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as z from \"zod\"; const matchJsonSchema = { type: \"object\", properties: { winner: { type: \"string\", description: \"The name of the winner.\" }, final_match_score: { type: \"string\", description: \"The final score.\" }, scorers: { type: \"array\", items: { type: \"string\" }, description: \"The name of the scorer.\" } }, required: [\"winner\", \"final_match_score\", \"scorers\"] }; const matchSchema = z.fromJSONSchema(matchJsonSchema); const client = new GoogleGenAI({}); async function run() { const interaction = await client.interactions.create({ model: \"gemini-3.1-pro-preview\", input: \"Search for all details for the latest Euro.\", tools: [ { type: \"google_search\" }, { type: \"url_context\" } ], response_format: { type: \"text\", mime_type: \"application/json\", schema: matchJsonSchema }, }); const match = matchSchema.parse(JSON.parse(interaction.output_text)); console.log(match); } run();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.FunctionResultStep; import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion; import com.google.genai.gaos.models.interactions.FunctionResultSubcontent; import com.google.genai.gaos.models.interactions.ImageContent; import com.google.genai.gaos.models.interactions.ImageContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.interactions.Tool; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; Client client = new Client(); Map itemProp = new HashMap<>(); itemProp.put(\"type\", \"string\"); itemProp.put(\"description\", \"The name or description of the item ordered (e.g., 'instrument').\"); Map properties = new HashMap<>(); properties.put(\"item_name\", itemProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"item_name\")); Function getImageTool = Function.builder() .name(\"get_image\") .description(\"Retrieves the image file reference for a specific order item.\") .parameters(parameters) .build(); CreateModelInteraction req1 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.of(\"Use the get_image tool to show me the instrument I ordered last month.\")) .tools(Arrays.asList(getImageTool)) .build(); Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().get(); FunctionCallStep fcStep = null; for (Step step : interaction1.steps().orElse(Collections.emptyList())) { if (step instanceof FunctionCallStep) { fcStep = (FunctionCallStep) step; break; } } if (fcStep != null) { System.out.println(\"Tool Call: \" + fcStep.name().orElse(\"\")); URL url = new URL(\"https://goo.gle/instrument-img\"); byte[] imageBytes; try (InputStream is = url.openStream()) { imageBytes = is.readAllBytes(); } String base64ImageData = Base64.getEncoder().encodeToString(imageBytes); List subcontents = new ArrayList<>(); subcontents.add(TextContent.builder().text(\"instrument.jpg\").build()); subcontents.add( ImageContent.builder() .mimeType(ImageContentMimeType.IMAGE_JPEG) .data(base64ImageData) .build()); FunctionResultStep funcResult = FunctionResultStep.builder() .name(fcStep.name().orElse(\"\")) .callId(fcStep.id().orElse(\"\")) .result(FunctionResultStepResultUnion.of(subcontents)) .build(); CreateModelInteraction req2 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.ofStep(Arrays.asList(funcResult))) .tools(Arrays.asList(getImageTool)) .previousInteractionId(interaction1.id().orElse(\"\")) .build(); Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().get(); System.out.println(\"Final model response: \" + interaction2.outputText().orElse(\"\")); } ```bash curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3.1-pro-preview\", \"input\": \"Search for all details for the latest Euro.\", \"tools\": [ {\"type\": \"google_search\"}, {\"type\": \"url_context\"} ], \"response_format\": { \"type\": \"text\", \"mime_type\": \"application/json\", \"schema\": { \"type\": \"object\", \"properties\": { \"winner\": {\"type\": \"string\", \"description\": \"The name of the winner.\"}, \"final_match_score\": {\"type\": \"string\", \"description\": \"The final score.\"}, \"scorers\": { \"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"The name of the scorer.\" } }, \"required\": [\"winner\", \"final_match_score\", \"scorers\"] } } }'` Image generation Gemini 3.1 Flash Image and Gemini 3 Pro Image let you generate and edit images\nfrom text prompts. It uses\nreasoning to \"think\" through a prompt and can retrieve real-time data—such as\nweather forecasts or stock charts—before using [Google Search](/gemini-api/docs/google-search) grounding before generating high-fidelity\nimages. **New & improved capabilities:** **4K & text rendering:** Generate sharp, legible text and diagrams with up\nto 2K and 4K resolutions. **Grounded generation:** Use the `google_search` tool to verify facts and\ngenerate imagery based on real-world information. Grounding with Google *Image*\nSearch available for Gemini 3.1 Flash Image. **Conversational editing:** Multi-turn image editing by simply asking for\nchanges (e.g., \"Make the background a sunset\"). This workflow relies on\n**Thought Signatures** to preserve visual context between turns. For complete details on aspect ratios, editing workflows, and configuration\noptions, see the [Image Generation guide](/gemini-api/docs/image-generation). Python`from google import genai import base64 client = genai.Client() interaction = client.interactions.create( model=\"gemini-3-pro-image-preview\", input=\"Generate an infographic of the current weather in Tokyo.\", tools=[{\"type\": \"google_search\"}], response_format={ \"type\": \"image\", \"aspect_ratio\": \"16:9\", \"image_size\": \"4K\" } ) from PIL import Image import io generated_image = interaction.output_image if generated_image: image_data = base64.b64decode(generated_image.data) image = Image.open(io.BytesIO(image_data)) image.save('weather_tokyo.png') image.show()` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const client = new GoogleGenAI({}); async function run() { const interaction = await client.interactions.create({ model: \"gemini-3-pro-image-preview\", input: \"Generate a visualization of the current weather in Tokyo.\", tools: [{ type: \"google_search\" }], response_format: { type: \"image\", aspect_ratio: \"16:9\", image_size: \"4K\" } }); const buffer = Buffer.from(interaction.output_image.data, 'base64'); fs.writeFileSync('weather_tokyo.png', buffer); } run();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.FunctionResultStep; import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion; import com.google.genai.gaos.models.interactions.FunctionResultSubcontent; import com.google.genai.gaos.models.interactions.ImageContent; import com.google.genai.gaos.models.interactions.ImageContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.interactions.Tool; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; Client client = new Client(); Map itemProp = new HashMap<>(); itemProp.put(\"type\", \"string\"); itemProp.put(\"description\", \"The name or description of the item ordered (e.g., 'instrument').\"); Map properties = new HashMap<>(); properties.put(\"item_name\", itemProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"item_name\")); Function getImageTool = Function.builder() .name(\"get_image\") .description(\"Retrieves the image file reference for a specific order item.\") .parameters(parameters) .build(); CreateModelInteraction req1 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.of(\"Use the get_image tool to show me the instrument I ordered last month.\")) .tools(Arrays.asList(getImageTool)) .build(); Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().get(); FunctionCallStep fcStep = null; for (Step step : interaction1.steps().orElse(Collections.emptyList())) { if (step instanceof FunctionCallStep) { fcStep = (FunctionCallStep) step; break; } } if (fcStep != null) { System.out.println(\"Tool Call: \" + fcStep.name().orElse(\"\")); URL url = new URL(\"https://goo.gle/instrument-img\"); byte[] imageBytes; try (InputStream is = url.openStream()) { imageBytes = is.readAllBytes(); } String base64ImageData = Base64.getEncoder().encodeToString(imageBytes); List subcontents = new ArrayList<>(); subcontents.add(TextContent.builder().text(\"instrument.jpg\").build()); subcontents.add( ImageContent.builder() .mimeType(ImageContentMimeType.IMAGE_JPEG) .data(base64ImageData) .build()); FunctionResultStep funcResult = FunctionResultStep.builder() .name(fcStep.name().orElse(\"\")) .callId(fcStep.id().orElse(\"\")) .result(FunctionResultStepResultUnion.of(subcontents)) .build(); CreateModelInteraction req2 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.ofStep(Arrays.asList(funcResult))) .tools(Arrays.asList(getImageTool)) .previousInteractionId(interaction1.id().orElse(\"\")) .build(); Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().get(); System.out.println(\"Final model response: \" + interaction2.outputText().orElse(\"\")); } ```bash curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3-pro-image-preview\", \"input\": \"Generate a visualization of the current weather in Tokyo.\", \"tools\": [{\"type\": \"google_search\"}], \"response_format\": { \"type\": \"image\", \"aspect_ratio\": \"16:9\", \"image_size\": \"4K\" } }'` **Example Response** Code Execution with images Gemini 3 Flash can treat vision as an active investigation, not just a static\nglance. By combining reasoning with [code execution](/gemini-api/docs/code-execution), the model formulates a plan, then writes and\nexecutes Python code to zoom in, crop, annotate, or otherwise manipulate images\nstep-by-step to visually ground its answers. **Use cases:** **Zoom and inspect:** The model implicitly detects when details are too\nsmall (e.g., reading a distant gauge or serial number) and writes code to crop\nand re-examine the area at higher resolution. **Visual math and plotting:** The model can run multi-step calculations using\ncode (e.g., summing line items on a receipt, or generating a Matplotlib chart\nfrom extracted data). **Image annotation:** The model can draw arrows, bounding boxes, or other\nannotations directly onto images to answer spatial questions like \"Where should\nthis item go?\". To enable visual thinking, configure [Code Execution](/gemini-api/docs/code-execution) as a tool. The model will automatically use\ncode to manipulate images when needed. Python`from google import genai from google.genai import types import requests from PIL import Image import io import base64 image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content image = types.Part.from_bytes(data=image_bytes, mime_type=\"image/jpeg\") client = genai.Client() interaction = client.interactions.create( model=\"gemini-3-flash-preview\", input=[ image, \"Zoom into the expression pedals and tell me how many pedals are there?\" ], tools=[{\"type\": \"code_execution\"}], ) from IPython.display import display from PIL import Image import io for step in interaction.steps: if step.type == \"model_output\": for content_block in step.content: if content_block.type == \"text\": print(content_block.text) elif content_block.type == \"image\": display(Image.open(io.BytesIO(base64.b64decode(content_block.data)))) elif step.type == \"code_execution_call\": print(step.code) elif step.type == \"code_execution_result\": print(step.output)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const client = 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 interaction = await client.interactions.create({ model: \"gemini-3-flash-preview\", input: [ { type: \"image\", mime_type: \"image/jpeg\", data: base64ImageData, }, { type: \"text\", text: \"Zoom into the expression pedals and tell me how many pedals are there?\", }, ], tools: [{ type: \"code_execution\" }], }); for (const step of interaction.steps) { if (step.type === \"model_output\") { for (const contentBlock of step.content) { if (contentBlock.type === \"text\") { console.log(\"Text:\", contentBlock.text); } } } else if (step.type === \"code_execution_call\") { console.log(\"Code:\", step.code); } else if (step.type === \"code_execution_result\") { console.log(\"Output:\", step.output); } } } main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.FunctionResultStep; import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion; import com.google.genai.gaos.models.interactions.FunctionResultSubcontent; import com.google.genai.gaos.models.interactions.ImageContent; import com.google.genai.gaos.models.interactions.ImageContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.interactions.Tool; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; Client client = new Client(); Map itemProp = new HashMap<>(); itemProp.put(\"type\", \"string\"); itemProp.put(\"description\", \"The name or description of the item ordered (e.g., 'instrument').\"); Map properties = new HashMap<>(); properties.put(\"item_name\", itemProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"item_name\")); Function getImageTool = Function.builder() .name(\"get_image\") .description(\"Retrieves the image file reference for a specific order item.\") .parameters(parameters) .build(); CreateModelInteraction req1 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.of(\"Use the get_image tool to show me the instrument I ordered last month.\")) .tools(Arrays.asList(getImageTool)) .build(); Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().get(); FunctionCallStep fcStep = null; for (Step step : interaction1.steps().orElse(Collections.emptyList())) { if (step instanceof FunctionCallStep) { fcStep = (FunctionCallStep) step; break; } } if (fcStep != null) { System.out.println(\"Tool Call: \" + fcStep.name().orElse(\"\")); URL url = new URL(\"https://goo.gle/instrument-img\"); byte[] imageBytes; try (InputStream is = url.openStream()) { imageBytes = is.readAllBytes(); } String base64ImageData = Base64.getEncoder().encodeToString(imageBytes); List subcontents = new ArrayList<>(); subcontents.add(TextContent.builder().text(\"instrument.jpg\").build()); subcontents.add( ImageContent.builder() .mimeType(ImageContentMimeType.IMAGE_JPEG) .data(base64ImageData) .build()); FunctionResultStep funcResult = FunctionResultStep.builder() .name(fcStep.name().orElse(\"\")) .callId(fcStep.id().orElse(\"\")) .result(FunctionResultStepResultUnion.of(subcontents)) .build(); CreateModelInteraction req2 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.ofStep(Arrays.asList(funcResult))) .tools(Arrays.asList(getImageTool)) .previousInteractionId(interaction1.id().orElse(\"\")) .build(); Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().get(); System.out.println(\"Final model response: \" + interaction2.outputText().orElse(\"\")); } ```bash IMG_URL=\"https://goo.gle/instrument-img\" MODEL=\"gemini-3-flash-preview\" MIME_TYPE=$(curl -sIL \"$IMG_URL\" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\\r$//' | head -n 1) if [[ -z \"$MIME_TYPE\" || ! \"$MIME_TYPE\" == image/* ]]; then MIME_TYPE=\"image/jpeg\" fi if [[ \"$(uname)\" == \"Darwin\" ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -b 0) elif [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64) else IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -w0) fi curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"'$MODEL'\", \"input\": [ { \"type\": \"image\", \"mime_type\":\"'\"$MIME_TYPE\"'\", \"data\": \"'\"$IMAGE_B64\"'\" }, {\"type\": \"text\", \"text\": \"Zoom into the expression pedals and tell me how many pedals are there?\"} ], \"tools\": [{\"type\": \"code_execution\"}] }'` For more details on code execution with images, see [Code Execution](/gemini-api/docs/code-execution#images). Multimodal function responses [Multimodal function calling](/gemini-api/docs/function-calling#multimodal)\nallows users to have function responses containing\nmultimodal objects allowing for improved utilization of function calling\ncapabilities of the model. Standard function calling only supports text-based\nfunction responses: Python `# This will only work for SDK newer than 2.0.0 from google import genai import requests import base64 client = genai.Client() # 1. Define the tool get_image_tool = { \"type\": \"function\", \"name\": \"get_image\", \"description\": \"Retrieves the image file reference for a specific order item.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"item_name\": { \"type\": \"string\", \"description\": \"The name or description of the item ordered (e.g., 'instrument').\" } }, \"required\": [\"item_name\"], }, } # 2. Send the request with tools interaction_1 = client.interactions.create( model=\"gemini-3-flash-preview\", input=\"Show me the instrument I ordered last month.\", tools=[get_image_tool], ) # 3. Find the function call step fc_step = next(s for s in interaction_1.steps if s.type == \"function_call\") print(f\"Tool Call: {fc_step.name}({fc_step.arguments})\") # Execute tool (fetch image) image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content image_b64 = base64.b64encode(image_bytes).decode(\"utf-8\") # 4. Send multimodal function result back interaction_2 = client.interactions.create( model=\"gemini-3-flash-preview\", previous_interaction_id=interaction_1.id, input=[{ \"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": [ {\"type\": \"text\", \"text\": \"instrument.jpg\"}, { \"type\": \"image\", \"mime_type\": \"image/jpeg\", \"data\": image_b64, } ] }], tools=[get_image_tool] ) print(f\"\\nFinal model response: {interaction_2.output_text}\")` JavaScript `import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const getImageTool = { type: 'function', name: 'get_image', description: 'Retrieves the image file reference for a specific order item.', parameters: { type: 'object', properties: { item_name: { type: 'string', description: \"The name or description of the item ordered (e.g., 'instrument').\", }, }, required: ['item_name'], }, }; const interaction1 = await client.interactions.create({ model: 'gemini-3-flash-preview', input: 'Use the get_image tool to show me the instrument I ordered last month.', tools: [getImageTool], }); const fcStep = interaction1.steps.find(s => s.type === 'function_call'); console.log(`Tool Call: ${fcStep.name}(${JSON.stringify(fcStep.arguments)})`); 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 interaction2 = await client.interactions.create({ model: 'gemini-3-flash-preview', previous_interaction_id: interaction1.id, input: [{ type: 'function_result', name: fcStep.name, call_id: fcStep.id, result: [ { type: 'text', text: 'instrument.jpg' }, { type: 'image', mime_type: 'image/jpeg', data: base64ImageData, } ] }], tools: [getImageTool] }); console.log(`\\nFinal model response: ${interaction2.output_text}`);` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.FunctionResultStep; import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion; import com.google.genai.gaos.models.interactions.FunctionResultSubcontent; import com.google.genai.gaos.models.interactions.ImageContent; import com.google.genai.gaos.models.interactions.ImageContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.interactions.Tool; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; Client client = new Client(); Map itemProp = new HashMap<>(); itemProp.put(\"type\", \"string\"); itemProp.put(\"description\", \"The name or description of the item ordered (e.g., 'instrument').\"); Map properties = new HashMap<>(); properties.put(\"item_name\", itemProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"item_name\")); Function getImageTool = Function.builder() .name(\"get_image\") .description(\"Retrieves the image file reference for a specific order item.\") .parameters(parameters) .build(); CreateModelInteraction req1 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.of(\"Use the get_image tool to show me the instrument I ordered last month.\")) .tools(Arrays.asList(getImageTool)) .build(); Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().get(); FunctionCallStep fcStep = null; for (Step step : interaction1.steps().orElse(Collections.emptyList())) { if (step instanceof FunctionCallStep) { fcStep = (FunctionCallStep) step; break; } } if (fcStep != null) { System.out.println(\"Tool Call: \" + fcStep.name().orElse(\"\")); URL url = new URL(\"https://goo.gle/instrument-img\"); byte[] imageBytes; try (InputStream is = url.openStream()) { imageBytes = is.readAllBytes(); } String base64ImageData = Base64.getEncoder().encodeToString(imageBytes); List subcontents = new ArrayList<>(); subcontents.add(TextContent.builder().text(\"instrument.jpg\").build()); subcontents.add( ImageContent.builder() .mimeType(ImageContentMimeType.IMAGE_JPEG) .data(base64ImageData) .build()); FunctionResultStep funcResult = FunctionResultStep.builder() .name(fcStep.name().orElse(\"\")) .callId(fcStep.id().orElse(\"\")) .result(FunctionResultStepResultUnion.of(subcontents)) .build(); CreateModelInteraction req2 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.ofStep(Arrays.asList(funcResult))) .tools(Arrays.asList(getImageTool)) .previousInteractionId(interaction1.id().orElse(\"\")) .build(); Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().get(); System.out.println(\"Final model response: \" + interaction2.outputText().orElse(\"\")); } ```shell IMG_URL=\"https://goo.gle/instrument-img\" MIME_TYPE=$(curl -sIL \"$IMG_URL\" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\\r$//' | head -n 1) if [[ -z \"$MIME_TYPE\" || ! \"$MIME_TYPE\" == image/* ]]; then MIME_TYPE=\"image/jpeg\" fi # Check for macOS if [[ \"$(uname)\" == \"Darwin\" ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -b 0) elif [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64) else IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -w0) fi # 1. First interaction (triggers function call) # curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ # -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ # -H 'Content-Type: application/json' \\ # -d '{ \"model\": \"gemini-3-flash-preview\", \"input\": \"Show me the instrument I ordered last month.\", \"tools\": [...] }' # 2. Send multimodal function result back (Replace INTERACTION_ID and CALL_ID) curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"model\": \"gemini-3-flash-preview\", \"previous_interaction_id\": \"INTERACTION_ID\", \"input\": [{ \"type\": \"function_result\", \"name\": \"get_image\", \"call_id\": \"CALL_ID\", \"result\": [ { \"type\": \"text\", \"text\": \"instrument.jpg\" }, { \"type\": \"image\", \"mime_type\": \"'\"$MIME_TYPE\"'\", \"data\": \"'\"$IMAGE_B64\"'\" } ] }] }'` Combine built-in tools and function calling Gemini 3 allows the use of built-in tools (like Google Search, URL\ncontext, and [more](/gemini-api/docs/tools)) and custom [function calling](/gemini-api/docs/function-calling) tools in the same API call, allowing for\nmore complex workflows. Python`from google import genai from google.genai import types client = genai.Client() getWeather = { \"type\": \"function\", \"name\": \"getWeather\", \"description\": \"Gets the weather for a requested city.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"city\": { \"type\": \"string\", \"description\": \"The city and state, e.g. UtqiaÄĄvik, Alaska\", }, }, \"required\": [\"city\"], }, } interaction = client.interactions.create( model=\"gemini-3-flash-preview\", input=\"What is the northernmost city in the United States? What's the weather like there today?\", tools=[ {\"type\": \"google_search\"}, getWeather ], ) fc_step = next((s for s in interaction.steps if s.type == \"function_call\"), None) if fc_step: result = {\"response\": \"Very cold. 22 degrees Fahrenheit.\"} final_interaction = client.interactions.create( model=\"gemini-3-flash-preview\", input=[ {\"type\": \"function_result\", \"name\": fc_step.name, \"call_id\": fc_step.id, \"result\": result} ], tools=[ {\"type\": \"google_search\"}, getWeather ], previous_interaction_id=interaction.id, ) print(final_interaction.output_text)` JavaScript`import { GoogleGenAI, Type } from '@google/genai'; const client = new GoogleGenAI({}); const getWeatherDeclaration = { type: 'function', name: 'getWeather', description: 'Gets the weather for a requested city.', parameters: { type: Type.OBJECT, properties: { city: { type: Type.STRING, description: 'The city and state, e.g. UtqiaÄĄvik, Alaska', }, }, required: ['city'], }, }; const interaction = await client.interactions.create({ model: 'gemini-3-flash-preview', input: \"What is the northernmost city in the United States? What's the weather like there today?\", tools: [ { type: \"google_search\" }, getWeatherDeclaration ], }); const fcStep = interaction.steps.find(s => s.type === 'function_call'); if (fcStep) { const result = { response: \"Very cold. 22 degrees Fahrenheit.\" }; const finalInteraction = await client.interactions.create({ model: 'gemini-3-flash-preview', input: [ { type: 'function_result', name: fcStep.name, call_id: fcStep.id, result: result } ], tools: [ { type: \"google_search\" }, getWeatherDeclaration ], previous_interaction_id: interaction.id, }); console.log(finalInteraction.output_text); }` Java`import com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Function; import com.google.genai.gaos.models.interactions.FunctionCallStep; import com.google.genai.gaos.models.interactions.FunctionResultStep; import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion; import com.google.genai.gaos.models.interactions.ImageContent; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.interactions.Tool; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; Client client = new Client(); Map itemProp = new HashMap<>(); itemProp.put(\"type\", \"string\"); itemProp.put(\"description\", \"The name or description of the item ordered (e.g., 'instrument').\"); Map properties = new HashMap<>(); properties.put(\"item_name\", itemProp); Map parameters = new HashMap<>(); parameters.put(\"type\", \"object\"); parameters.put(\"properties\", properties); parameters.put(\"required\", Arrays.asList(\"item_name\")); Function getImageTool = Function.builder() .name(\"get_image\") .description(\"Retrieves the image file reference for a specific order item.\") .parameters(parameters) .build(); CreateModelInteraction req1 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.of(\"Use the get_image tool to show me the instrument I ordered last month.\")) .tools(Arrays.asList(Tool.of(getImageTool))) .build(); Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().get(); Optional fcStepOpt = interaction1.steps().orElse(Collections.emptyList()).stream() .filter(Step::isFunctionCall) .map(Step::asFunctionCall) .findFirst(); if (fcStepOpt.isPresent()) { FunctionCallStep fcStep = fcStepOpt.get(); System.out.println(\"Tool Call: \" + fcStep.name().orElse(\"\")); URL url = new URL(\"https://goo.gle/instrument-img\"); byte[] imageBytes; try (InputStream is = url.openStream()) { imageBytes = is.readAllBytes(); } String base64ImageData = Base64.getEncoder().encodeToString(imageBytes); FunctionResultStep funcResult = FunctionResultStep.builder() .name(fcStep.name().orElse(\"\")) .callId(fcStep.id().orElse(\"\")) .result( FunctionResultStepResultUnion.of( Arrays.asList( TextContent.builder().text(\"instrument.jpg\").build(), ImageContent.builder() .mimeType(\"image/jpeg\") .data(base64ImageData) .build()))) .build(); CreateModelInteraction req2 = CreateModelInteraction.builder() .model(Model.of(\"gemini-3-flash-preview\")) .input(InteractionsInput.ofStep(Arrays.asList(funcResult))) .tools(Arrays.asList(Tool.of(getImageTool))) .previousInteractionId(interaction1.id().orElse(\"\")) .build(); Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().get(); System.out.println(\" Final model response: \" + interaction2.outputText().orElse(\"\")); }` Migration from Gemini 2.5 Gemini 3 is our most capable model family to date and offers a stepwise\nimprovement over Gemini 2.5. When migrating, consider the following: **Thinking:** If you were previously using complex prompt engineering (like\nchain of thought) to force Gemini 2.5 to reason, try Gemini 3 with\n`thinking_level: \"high\"` and simplified prompts. **Temperature settings:** If your existing code explicitly sets temperature\n(especially to low values for deterministic outputs), we recommend removing this\nparameter and using the Gemini 3 default of 1.0 to avoid potential looping\nissues or performance degradation on complex tasks. **PDF & document understanding:**\nIf you relied on specific behavior for dense document parsing, test the new\n`media_resolution_high` setting to ensure continued accuracy. **Token consumption:** Migrating to Gemini 3 defaults may **increase** token\nusage for PDFs but **decrease** token usage for video. If requests now exceed\nthe context window due to higher default resolutions, we recommend explicitly\nreducing the media resolution. **Image segmentation:** Image segmentation capabilities (returning pixel-level\nmasks for objects) are not supported in Gemini 3 Pro or Gemini 3 Flash. For\nworkloads requiring built-in image segmentation, we recommend continuing to\nuse Gemini 2.5 Flash with thinking turned off. **Computer Use:** Gemini 3 Pro and Gemini 3 Flash support [Computer\nUse](/gemini-api/docs/computer-use). Unlike the 2.5 series, you don't need to\nuse a separate model to access the Computer Use tool. **Tool support**: [Combining built-in tools with function calling](/gemini-api/docs/tool-combination) is now supported for Gemini 3 models. [Maps\ngrounding](/gemini-api/docs/maps-grounding) is also now supported for Gemini 3\nmodels. OpenAI compatibility For users utilizing the [OpenAI compatibility layer](/gemini-api/docs/openai),\nstandard parameters (OpenAI's `reasoning_effort`) are automatically mapped to\nGemini (`thinking_level`) equivalents. Prompting best practices Gemini 3 is a reasoning model, which changes how you should prompt. **Precise instructions:** Be concise in your input prompts. Gemini 3 responds\nbest to direct, clear instructions. It may over-analyze verbose or overly\ncomplex prompt engineering techniques used for older models. **Output verbosity:** By default, Gemini 3 is less verbose and prefers\nproviding direct, efficient answers. If your use case requires a more\nconversational or \"chatty\" persona, you must explicitly steer the model in the\nprompt (e.g., \"Explain this as a friendly, talkative assistant\"). **Context management:** When working with large datasets (e.g., entire books,\ncodebases, or long videos), place your specific instructions or questions at the\nend of the prompt, after the data context. Anchor the model's reasoning to the\nprovided data by starting your question with a phrase like, \"Based on the\npreceding information...\". Learn more about prompt design strategies in the [prompt engineering guide](/gemini-api/docs/prompting-strategies). FAQ **What is the knowledge cutoff for Gemini 3?** Gemini 3 models have a\nknowledge cutoff of January 2025. For more recent information, use the\n[Search Grounding](/gemini-api/docs/google-search) tool. **What are the context window limits?** Gemini 3 models support a 1 million\ntoken input context window and up to 64k tokens of output. **Is there a free tier for Gemini 3?** Gemini 3 Flash\n`gemini-3-flash-preview` has a free tier in the Gemini API. You can try\nGemini 3.1 Pro and 3 Flash at no cost in Google AI Studio, but there\nis no free tier available for `gemini-3.1-pro-preview` in the Gemini API. **Will my old `thinking_budget` code still work?** Yes, `thinking_budget` is\nstill supported for backward compatibility, but we recommend migrating to\n`thinking_level` for more predictable performance. Don't use both in the same\nrequest. **Does Gemini 3 support the Batch API?** Yes, Gemini 3 supports the\n[Batch API](/gemini-api/docs/batch-api). **Is Context Caching supported?** Yes, [Context Caching](/gemini-api/docs/caching) is supported for Gemini 3. **Which tools are supported in Gemini 3?** Gemini 3 supports\n[Google Search](/gemini-api/docs/google-search),\n[Grounding with Google Maps](/gemini-api/docs/maps-grounding),\n[File Search](/gemini-api/docs/file-search),\n[Code Execution](/gemini-api/docs/code-execution), and\n[URL Context](/gemini-api/docs/url-context). It also supports\nstandard [Function Calling](/gemini-api/docs/function-calling) for\nyour own custom tools, and in\n[combination with built-in tools](/gemini-api/docs/tool-combination). **What is `gemini-3.1-pro-preview-customtools`?** If you are using\n`gemini-3.1-pro-preview` and the model ignores your custom tools in favor of\nbash commands, try the `gemini-3.1-pro-preview-customtools` model instead.\nMore info [here][customtools-model]. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-08-26 UTC.", "znaku_textu": 53497, "slov": 5354, "odkazu": 37, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:40", "sha256": "46503714bb82425c5637c13f4cbbfc3d2f6ae8f28f3691dce6f6361d4b81ab7d", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/app/apps?showcaseTag=gemini-3&source=showcase", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/gemini-for-research", "titulek": "Accelerate discovery with Gemini for Research | Gemini API | Google AI for Developers", "h1": "Accelerate discovery with Gemini for Research", "popis": "Accelerate discovery with Gemini for Research", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/gemini-for-research", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Accelerate discovery with Gemini for Research  |  Gemini API  |  Google AI for Developers", "og:description": "Accelerate discovery with Gemini for Research", "og:url": "https://ai.google.dev/gemini-api/docs/gemini-for-research", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Accelerate discovery with Gemini for Research"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api"}, {"@type": "ListItem", "position": 2, "name": "Accelerate discovery with Gemini for Research", "item": "https://ai.google.dev/gemini-api/docs/gemini-for-research"}]}], "drobecky": ["Gemini API", "Accelerate discovery with Gemini for Research"], "osnova": [{"uroven": 1, "text": "Accelerate discovery with Gemini for Research"}, {"uroven": 2, "text": "Get started with Gemini"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Featured academics"}, {"uroven": 2, "text": "Gemini Academic Program"}, {"uroven": 3, "text": "Start researching with the Gemini API"}], "markdown": "Accelerate discovery with Gemini for Research [Get a Gemini API Key](https://aistudio.google.com/apikey) Gemini models can be used to advance foundational research across disciplines.\nHere are ways that you can explore Gemini for your research: **Analyze and control model outputs**: For further analysis, you can examine a\nresponse candidate generated by the model using tools like\n`CitationMetadata`. You can also configure options for model generation and\noutputs, such as `responseSchema`, `topP`, and `topK`. [Learn more](/api/generate-content). **Multimodal inputs**: Gemini can process images, audio, and videos, enabling a\nmultitude of exciting research directions. [Learn more](/gemini-api/docs/vision). **Long-context capabilities**: Gemini 3.0 Flash and Pro come with a 1-million-token\ncontext window. [Learn more](/gemini-api/docs/long-context). **Grow with Google**: Quickly access Gemini models through the API and Google AI\nStudio for production use cases. If you're looking for a Google Cloud-based\nplatform, Gemini Enterprise Agent Platform can provide additional supporting infrastructure. To support academic research and drive cutting-edge research, Google provides\naccess to Gemini API credits for scientists and academic researchers through the\n[Gemini Academic Program](/gemini-api/docs/gemini-for-research#gemini-academic-program). Get started with Gemini The Gemini API and Google AI Studio help you start working with Google's latest\nmodels and turn your ideas into applications that scale. Python`from google import genai client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"How large is the universe?\", ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"How large is the universe?\", }); console.log(response.text); } await main();` Java`import com.google.genai.Client; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; Client client = new Client(); CreateModelInteraction req = CreateModelInteraction.builder() .model(Model.of(\"gemini-3.8-flash\")) .input(InteractionsInput.of(\"How large is the universe?\")) .build(); var interaction = client.interactions.create(CreateInteractionRequestBody.of(req)).interaction().get(); System.out.println(interaction.outputText().orElse(\"\"));` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-X POST \\\n-d '{ \"contents\": [{ \"parts\":[{\"text\": \"How large is the universe?\"}] }] }'` Featured academics \"Our research investigates Gemini as a visual language model (VLM) and its agentic behaviors in diverse environments from robustness and safety perspectives. So far, we have evaluated Gemini's robustness against distractions such as pop-up windows when VLM agents perform computer tasks, and have leveraged Gemini to analyze social interaction, temporal events as well as risk factors based on video input.\" [Diyi Yang's Website](https://cs.stanford.edu/~diyiy/) \"Gemini Pro and Flash, with their long context window, have been helping us in OK-Robot, our open-vocabulary mobile manipulation project. Gemini enables complex natural language queries and commands over the robot's \"memory\": in this case, previous observations made by the robot over a long operation duration. Mahi Shafiullah and I are also using Gemini to decompose tasks into code that the robot can execute in the real world.\" [Lerrel Pinto's Website](https://www.lerrelpinto.com/) Gemini Academic Program Qualified academic researchers (such as faculty, staff, and PhD students) in [supported\ncountries](/gemini-api/docs/available-regions) can apply to receive Gemini API\ncredits and higher rate limits for research projects. This support enables\nhigher throughput for scientific experiments and advances research. We are particularly interested in the research areas in the following section,\nbut we welcome applications from diverse scientific disciplines: **Evaluations and benchmarks**: Community-endorsed evaluation methods that\ncan provide a strong performance signal in areas such as factuality, safety,\ninstruction following, reasoning, and planning. **Accelerating scientific discovery to benefit humanity**: Potential\napplications of AI in interdisciplinary scientific research, including areas\nsuch as rare and neglected diseases, experimental biology, materials science,\nand sustainability. **Embodiment and interactions**: Utilizing large language models to\ninvestigate novel interactions within the fields of embodied AI, ambient\ninteractions, robotics, and human-computer interaction. **Emergent capabilities**: Exploring new agentic capabilities required to\nenhance reasoning and planning, and how capabilities can be expanded during\ninference (e.g., by utilizing Gemini Flash). **Multimodal interaction and understanding**: Identifying gaps and\nopportunities for multimodal foundational models for analysis, reasoning,\nand planning across a variety of tasks. Eligibility: Only individuals (faculty members, researchers or equivalent)\naffiliated with a valid academic institution, or academic research organization\ncan apply. Note that API access and credits will be granted and removed\nat Google's discretion. We review applications on a monthly basis. Start researching with the Gemini API [Apply now](https://forms.gle/HMviQstU8PxC5iCt5) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 6197, "slov": 774, "odkazu": 23, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:41", "sha256": "16628bf36188c4b250733a69134678909ace6ec3c2673f06bb3d370cd623209d", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://cs.stanford.edu/~diyiy/", "https://www.lerrelpinto.com/", "https://forms.gle/HMviQstU8PxC5iCt5", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content", "titulek": "Gemini API | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Gemini API", "popis": "Gemini API Docs and API Reference", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini API  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Gemini API Docs and API Reference", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Gemini API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Gemini API", "item": "https://ai.google.dev/gemini-api/docs/generate-content"}]}], "drobecky": ["Generate Content API", "Gemini API"], "osnova": [{"uroven": 1, "text": "Gemini API"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Explore Capabilities"}], "markdown": "Gemini API The Gemini API is the fastest path from prompt to production with Gemini, Veo,\nNano Banana, and more. It lets you integrate these generative models into your\napplications to generate text and images, analyze multimodal inputs, and build\nconversational agents. Python`from google import genai client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Explain how AI works in a few words\", ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Explain how AI works in a few words\", }); console.log(response.text); } await main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } result, err := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", genai.Text(\"Explain how AI works in a few words\"), nil, ) if err != nil { log.Fatal(err) } fmt.Println(result.Text()) }` Java`package com.example; import com.google.genai.Client; import com.google.genai.types.GenerateContentResponse; public class GenerateTextFromTextInput { public static void main(String[] args) { Client client = new Client(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.8-flash\", \"Explain how AI works in a few words\", null); System.out.println(response.text()); } }` C#`using System.Threading.Tasks; using Google.GenAI; using Google.GenAI.Types; public class GenerateContentSimpleText { public static async Task main() { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.8-flash\", contents: \"Explain how AI works in a few words\" ); Console.WriteLine(response.Candidates[0].Content.Parts[0].Text); } }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"parts\": [ { \"text\": \"Explain how AI works in a few words\" } ] } ] }'` [Start building](/gemini-api/docs/generate-content/get-started) [auto_awesome\n Gemini 3.1 Pro\n New \n Our most intelligent model, the best in the world for multimodal understanding, all built on state-of-the-art reasoning.](/gemini-api/docs/models/gemini-3.1-pro-preview) [spark\n Gemini 3.6 Flash\n New \n Our latest model that balances speed with intelligence to deliver strong performance in agentic and multimodal tasks.](/gemini-api/docs/models/gemini-3.6-flash) [spark\n Gemini 3.5 Flash\n \n Frontier-class performance rivaling larger models at a fraction of the cost.](/gemini-api/docs/models/gemini-3.5-flash) [spark\n Gemini 3.5 Flash-Lite\n New \n High-volume, cost-sensitive model optimized for low-latency high throughput subagent tasks.](/gemini-api/docs/models/gemini-3.5-flash-lite) [spark\n Gemini 3.1 Flash-Lite\n \n High-volume, cost-sensitive model with the performance and quality of the Gemini 3 series.](/gemini-api/docs/models/gemini-3.1-flash-lite) [spark\n Gemini 3 Flash\n \n Frontier-class performance rivaling larger models at a fraction of the cost.](/gemini-api/docs/models/gemini-3-flash-preview) [🍌\n Nano Banana 2 and Nano Banana Pro\n \n State-of-the-art image generation and editing models.](/gemini-api/docs/image-generation) [video_library\n Veo 3.1\n \n Our state-of-the-art video generation model, with native audio.](/gemini-api/docs/video) [spark\n Gemini Robotics\n \n A vision-language model (VLM) that brings Gemini's agentic capabilities to robotics and enables advanced reasoning in the physical world.](/gemini-api/docs/robotics-overview) Explore Capabilities [imagesmode \n Native Image Generation (Nano Banana)\n \n Generate and edit highly contextual images natively with Gemini 2.5 Flash Image.](/gemini-api/docs/image-generation) [article \n Long Context\n \n Input millions of tokens to Gemini models and derive understanding from unstructured images, videos, and documents.](/gemini-api/docs/long-context) [code \n Structured Outputs\n \n Constrain Gemini to respond with JSON, a structured data format suitable for automated processing.](/gemini-api/docs/structured-output) [functions \n Function Calling\n \n Build agentic workflows by connecting Gemini to external APIs and tools.](/gemini-api/docs/function-calling) [videocam \n Video Generation with Veo 3.1\n \n Create high-quality video content from text or image prompts with our state-of-the-art model.](/gemini-api/docs/video) [android_recorder \n Voice Agents with Live API\n \n Build real-time voice applications and agents with the Live API.](/gemini-api/docs/live-api) [build \n Tools\n \n Connect Gemini to the world through built-in tools like Google Search, URL Context, Google Maps, Code Execution and Computer Use.](/gemini-api/docs/tools) [stacks \n Document Understanding\n \n Process up to 1000 pages of PDF files with full multimodal understanding or other text-based file types.](/gemini-api/docs/document-processing) [cognition_2 \n Thinking\n \n Explore how thinking capabilities improve reasoning for complex tasks and agents.](/gemini-api/docs/thinking) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-10 UTC.", "znaku_textu": 5698, "slov": 728, "odkazu": 136, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:25", "sha256": "05b59d1c0d6f3a7b099ec3163eb8f414d36f1f32759876619e6d01ddc400db08", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/", "https://discuss.ai.google.dev/c/gemini-api/4", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/api-errors", "titulek": "API errors | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "API errors", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/api-errors", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "API errors  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/api-errors", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "API errors"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "API errors", "item": "https://ai.google.dev/gemini-api/docs/generate-content/api-errors"}]}], "drobecky": ["Generate Content API", "API errors"], "osnova": [{"uroven": 1, "text": "API errors"}, {"uroven": 2, "text": "HTTP error codes"}, {"uroven": 2, "text": "Error response format"}, {"uroven": 2, "text": "What's next"}], "markdown": "API errors This page provides a reference for backend error codes returned by the `GenerateContent` API, describes the gRPC error response format, and provides troubleshooting steps. HTTP error codes The following table lists common backend error codes, explanations for their causes, and recommended solutions: **HTTP Code** **Status** **Description** **Example** **Solution** \n 400\n INVALID_ARGUMENT The request body is malformed. There is a typo, or a missing required field in your request. Check the [API reference](/api) for request format, examples, and supported versions. Using features from a newer API version with an older endpoint can cause errors. \n 400\n FAILED_PRECONDITION Gemini API free tier is not available in your country. Please enable billing on your project in Google AI Studio. You are making a request in a region where the free tier is not supported, and you have not enabled billing on your project in Google AI Studio. To use the Gemini API, you will need to setup a paid plan using [Google AI Studio](https://aistudio.google.com/apikey). \n 403\n PERMISSION_DENIED Your API key doesn't have the required permissions. You are using the wrong API key; you are trying to use a tuned model without going through [proper authentication](/gemini-api/docs/model-tuning). Check that your API key is set and has the right access. And make sure to go through proper authentication to use tuned models. \n 404\n NOT_FOUND The requested resource wasn't found. An image, audio, or video file referenced in your request was not found. Check if all parameters in your request are valid for your API version. \n 429\n RESOURCE_EXHAUSTED You've exceeded one of the API's rate limits (RPM, TPM, RPD, spend, etc.). You are sending too many requests, using too many tokens, or exceeding spend-based limits for your account's billing history and tier. Verify that you're within the model's [rate limits](/gemini-api/docs/rate-limits). Wait and retry after a short period. Reduce the rate or size of your requests. [Request a rate limit increase](/gemini-api/docs/rate-limits#request-rate-limit-increase) if needed. \n 499\n CANCELLED The operation was cancelled, typically by the caller. The client closed the connection before the API could finish responding. Check if your client or network infrastructure is prematurely closing the connection (e.g., due to a client-side timeout). \n 500\n INTERNAL An unexpected error occurred on Google's side. Your input context is too long. Check the [Gemini API status page](https://aistudio.google.com/status) for any ongoing incidents. Reduce your input context or temporarily switch to another model (e.g. from Gemini 2.5 Pro to Gemini 2.5 Flash) and see if it works. Or wait a bit and retry your request. If the issue persists after retrying, please report it using the **Send feedback** button in Google AI Studio. \n 503\n UNAVAILABLE The service may be temporarily overloaded or down. The service is temporarily running out of capacity. Check the [Gemini API status page](https://aistudio.google.com/status) for any ongoing incidents. Temporarily switch to another model (e.g. from Gemini 2.5 Pro to Gemini 2.5 Flash) and see if it works. Or wait a bit and retry your request. If the issue persists after retrying, please report it using the **Send feedback** button in Google AI Studio. \n 504\n DEADLINE_EXCEEDED The service is unable to finish processing within the deadline. Your prompt (or context) is too large to be processed in time. Set a larger 'timeout' in your client request to avoid this error. Error response format When a `GenerateContent` request fails, the API sets the HTTP status code (such as `400 Bad Request`, `403 Forbidden`, or `429 Too Many Requests`) and returns a JSON response body containing gRPC status details: `{ \"error\": { \"code\": 400, \"message\": \"API key not valid. Please pass a valid API key.\", \"status\": \"INVALID_ARGUMENT\", \"details\": [ { \"@type\": \"type.googleapis.com/google.rpc.ErrorInfo\", \"reason\": \"API_KEY_INVALID\", \"domain\": \"googleapis.com\", \"metadata\": { \"service\": \"generativelanguage.googleapis.com\" } }, { \"@type\": \"type.googleapis.com/google.rpc.LocalizedMessage\", \"locale\": \"en-US\", \"message\": \"API key not valid. Please pass a valid API key.\" } ] } }` Field Type Description `code` integer The HTTP status code. `message` string A human-readable description of the error. `status` string The gRPC status code in `SCREAMING_CASE`. `details` array Additional error context, such as `ErrorInfo` or `LocalizedMessage`. What's next [API troubleshooting](/gemini-api/docs/troubleshooting): Resolve common issues and error scenarios. [Rate limits](/gemini-api/docs/rate-limits): Learn about request limits and quota handling. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-07-30 UTC.", "znaku_textu": 5129, "slov": 757, "odkazu": 124, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:12", "sha256": "38a8d145a46ebb6087cffabcb3b32106bc84bb0753990a667e43df8d0d0036b0", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/api-key", "titulek": "Using Gemini API keys | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Using Gemini API keys", "popis": "Get your Gemini API key and start building in less than 5 minutes.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/api-key", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Using Gemini API keys  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Get your Gemini API key and start building in less than 5 minutes.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/api-key", "og:image": "https://ai.google.dev/static/site-assets/images/api-key.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Using Gemini API keys"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Using Gemini API keys", "item": "https://ai.google.dev/gemini-api/docs/generate-content/api-key"}]}], "drobecky": ["Generate Content API", "Using Gemini API keys"], "osnova": [{"uroven": 1, "text": "Using Gemini API keys"}, {"uroven": 2, "text": "API key types: standard versus authorization"}, {"uroven": 2, "text": "Managing API keys in Google AI Studio"}, {"uroven": 3, "text": "Google Cloud projects"}, {"uroven": 3, "text": "Importing projects"}, {"uroven": 3, "text": "Troubleshooting key creation permissions"}, {"uroven": 2, "text": "Setting up your environment"}, {"uroven": 3, "text": "Use environment variables (recommended)"}, {"uroven": 3, "text": "Linux/macOS - Bash"}, {"uroven": 3, "text": "macOS - Zsh"}, {"uroven": 3, "text": "Windows"}, {"uroven": 3, "text": "Provide the API key explicitly in code"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Security and secret management"}, {"uroven": 3, "text": "Critical security rules"}, {"uroven": 3, "text": "Secret management best practices"}, {"uroven": 3, "text": "Leak response checklist"}, {"uroven": 2, "text": "Restricting and securing your keys"}, {"uroven": 3, "text": "Apply request origin restrictions"}, {"uroven": 3, "text": "Securing unrestricted standard API keys"}, {"uroven": 4, "text": "Restrict the key to the Gemini API only via AI Studio"}, {"uroven": 4, "text": "Restrict the key for other services via Google Cloud Console"}, {"uroven": 3, "text": "Blocked dormant keys"}, {"uroven": 2, "text": "Migrate to an auth key"}, {"uroven": 2, "text": "Limitations"}], "markdown": "Using Gemini API keys To use the Gemini API, you must authenticate your requests. You can\nauthenticate using a standard or authorization API key. [Create or view a Gemini API Key](https://aistudio.google.com/apikey) API key types: standard versus authorization API keys provide access to the Gemini API, but their security characteristics\ndiffer. The Gemini API is transitioning from standard API keys to authorization\nkeys to improve security: **Standard API keys**: Associate requests with a Google Cloud project for\nbilling and quota purposes. Standard keys don't identify a caller, which\nlimits the granularity of permissions and access control they can support. **Authorization (auth) keys**: Bound directly to a Google Cloud service\naccount. When you use an authorization key, your requests are processed\nunder the identity of that bound service account, enabling granular access\ncontrol. Authorization keys are restricted to the Generative Language API\n(Gemini API) by default and provide fast-acting leaked key enforcement that\nquickly stops the usage of leaked keys detected by our systems. To ensure secure usage, Gemini API will move from Standard keys to Auth keys: **Auth keys default**: All new API keys created in Google AI Studio\nare automatically created as auth keys. **Unrestricted keys rejected**: The Gemini API rejects requests\nfrom **unrestricted standard keys**. Standard API keys that have explicit\nrestrictions applied continue to work. This restriction prevents the\nunauthorized use of keys that might be shared publicly or linked to other\nservices. **On September 2026**: the Gemini API will reject requests from **Standard\nkeys**. You must migrate to auth keys\nbefore this date to avoid service interruption. Make sure to migrate to\nauth keys before September 2026. Managing API keys in Google AI Studio You can manage your projects and keys directly in [Google AI Studio](https://aistudio.google.com/apikey). Google Cloud projects Every Gemini API key is associated with a [Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects).\nGoogle Cloud projects manage billing, collaborators, and permissions. Google AI\nStudio provides a lightweight interface to access these projects. **Default project**: If you are a new user, Google AI Studio automatically\ncreates a default Google Cloud project and API key after you accept the\nTerms of Service. You can rename this project by navigating to the\n**Projects** view in your dashboard. **Existing projects**: If you already have a Google Cloud account, AI\nStudio does not create a default project. Instead, you must import your\nexisting projects. Importing projects By default, Google AI Studio does not display all of your Google Cloud\nprojects. You must import the projects you want to use: Go to [Google AI Studio](https://aistudio.google.com). Open the **Dashboard** from the left panel and select **Projects**. Click the **Import projects** button. Search for and select the Google Cloud project you want to import, then\nclick **Import**. Once imported, navigate to the **API Keys** page in the dashboard to\ncreate a key in that project. Troubleshooting key creation permissions If the **Create API key** button is unavailable and displays the message:\n*\"You do not have permission to create a key in this project\"*, you lack the\nrequired IAM permissions. Ask your Google Cloud project or organization administrator to grant you a role\ncontaining the following permissions (such as Project Editor): `resourcemanager.projects.get`: Allows AI Studio to verify the project. `apikeys.keys.create`: Allows key generation. `serviceusage.services.enable`: Ensures the Generative Language API is\nenabled. `iam.serviceAccounts.create`: Required to create the linked service account. `iam.serviceAccountApiKeyBindings.create`: Binds the service account to the\nAPI key. If you cannot get administrative access, you can create a new Google Cloud\nproject that is not associated with an organization to generate your keys. Setting up your environment Once you have a key, configure your environment to use it securely in your\napplications. Use environment variables (recommended) Set the environment variable `GEMINI_API_KEY` or `GOOGLE_API_KEY`. The Gemini\nAPI client libraries automatically detect and use these variables. If both are\nset, `GOOGLE_API_KEY` takes precedence. Select your operating system to set the variable: Linux/macOS - BashVerify if you have a bash configuration file: `~/.bashrc` If not, create one and open it: `touch ~/.bashrc && open ~/.bashrc` Add the export command at the end of the file: `export GEMINI_API_KEY=` Save the file, then apply the changes: `source ~/.bashrc` macOS - ZshVerify if you have a zsh configuration file: `~/.zshrc` If not, create one and open it: `touch ~/.zshrc && open ~/.zshrc` Add the export command: `export GEMINI_API_KEY=` Save the file, then apply the changes: `source ~/.zshrc` Windows Search for \"Environment Variables\" in the Windows search bar. Click **Environment Variables** in the System Properties dialog. Under **User variables** or **System variables**, click **New...**. Set the variable name to `GEMINI_API_KEY` and the value to your API key. Click **OK** to save. Open a new terminal session to load the variable. Provide the API key explicitly in code You can pass the API key explicitly when initializing the client. Only do this\nif you cannot use environment variables. Python`from google import genai client = genai.Client(api_key=\"YOUR_API_KEY\") response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Explain how AI works in a few words\" ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({ apiKey: \"YOUR_API_KEY\" }); async function main() { const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Explain how AI works in a few words\", }); console.log(response.text); } main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: \"YOUR_API_KEY\", Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } result, err := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", genai.Text(\"Explain how AI works in a few words\"), nil, ) if err != nil { log.Fatal(err) } fmt.Println(result.Text()) }` Java`package com.example; import com.google.genai.Client; import com.google.genai.types.GenerateContentResponse; public class GenerateTextFromTextInput { public static void main(String[] args) { Client client = Client.builder().apiKey(\"YOUR_API_KEY\").build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.8-flash\", \"Explain how AI works in a few words\", null); System.out.println(response.text()); } }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" -H 'Content-Type: application/json' -H \"x-goog-api-key: YOUR_API_KEY\" -X POST -d '{ \"contents\": [ { \"parts\": [ { \"text\": \"Explain how AI works in a few words\" } ] } ] }'` Security and secret management Treat your Gemini API key like a password. If compromised, others can consume\nyour project's quota, incur unexpected billing charges, and access private\nresources. Critical security rules **Keep keys confidential**: Never check API keys into source control systems\nlike Git. **Never expose keys client-side in production**: Do not hardcode API keys\ndirectly in web or mobile apps. Keys compiled in client-side code can be\nextracted by users. To secure client-side apps, run a backend proxy\nserver to make the actual API calls. Secret management best practices **Environment variables**: Read keys from environment variables rather than\nconfiguration files. **Secret Manager**: For production, store your keys in a secure secret store\nsuch as [Google Cloud Secret Manager](https://cloud.google.com/secret-manager). **Billing alerts**: Set up billing alerts in the Google Cloud Console to\nnotify you if usage or costs spike. Leak response checklist If you suspect your API key has been leaked: **Generate a new key**: Create a replacement key in Google AI Studio or the\nCloud Console. **Update your application**: Deploy your code using the new key. **Disable or delete the compromised key**: Disable the leaked key in the\nCloud Console once the new key is verified. Do not delete the old key until\nthe new key is fully active to avoid application downtime. **Audit usage**: Check billing logs and API usage in the Google Cloud\nConsole to identify unauthorized activity. Restricting and securing your keys Adding restrictions to your API keys minimizes the potential damage if a key is\ncompromised. Apply request origin restrictions Origin restrictions limit which IP addresses, websites, or applications can use\nyour key. Go to the [Google Cloud Console Credentials page](https://console.cloud.google.com/apis/credentials). Select your project, and click the name of the API key you want to restrict. Under **Application restrictions**, select **IP addresses** (or the\nappropriate restriction type for your environment). Specify the allowed IP addresses or ranges, then click **Save**. Securing unrestricted standard API keys To continue using the Gemini API, you must secure any unrestricted keys. Restrict the key to the Gemini API only via AI Studio If you only use the key for the Gemini API, secure it directly in AI Studio: On the **API Keys** page in [Google AI Studio](https://aistudio.google.com/api-keys), locate keys marked with the\n**Unrestricted** label. Hover over the label and click **Add restrictions** in the dialog. Select **Restrict to Gemini API only**. Click **Restrict key** to confirm. Restrict the key for other services via Google Cloud Console If the key is shared with other Google APIs (not recommended), restrict it in\nthe Cloud Console. **Note: Gemini API requests using this key will fail after\nthese restrictions are applied.** Visit the [Google Cloud Console Credentials page](https://console.cloud.google.com/apis/credentials). Select the project and the API key. Under **API restrictions**, select **Restrict key**. From the drop-down, select the APIs you want this key to access. Do not\nselect the **Generative Language API**. Click **Save**. Create a separate, restricted key in AI Studio to continue\nusing the Gemini API. Blocked dormant keys Starting May 7, 2026, the Gemini API blocks unrestricted API keys that have\nbeen dormant for an extended period. These keys show a **Blocked** tag in AI\nStudio. You must generate a new key or use an existing restricted key to\ncontinue. Migrate to an auth key Follow these steps to create a new auth API key and update your applications: Go to the [AI Studio API Keys page](https://aistudio.google.com/api-keys). Check the **Key Type** column to identify any keys listed as **Standard**. Click **Create API key** to generate a new key. All new keys created in\nAI Studio are automatically created as auth keys. Copy the new auth API key. Update your application code, environment variables, and any deployment\nconfigurations to use the new auth API key. Test your application to confirm it works correctly with the new key. Once verified, delete or revoke your old traffic key to prevent misuse. Limitations Google AI Studio imposes the following project and key management limitations: You can create a maximum of 10 projects at a time from the Google AI Studio\n**Projects** page. The **API keys** and **Projects** pages display a maximum of 100 keys and 50\nprojects. Only API keys that are unrestricted or restricted specifically to the\nGenerative Language API (Gemini API) are displayed. For advanced project management or to modify keys with other restrictions, use\nthe [Google Cloud Console credentials page](https://console.cloud.google.com/apis/credentials). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 12208, "slov": 1831, "odkazu": 129, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:17:13", "sha256": "42ae5e15b57e78601d62c49947a57e7c26d91e281a6b33eca53f862ceb8f9d44", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://cloud.google.com/resource-manager/docs/creating-managing-projects", "https://aistudio.google.com/", "https://cloud.google.com/secret-manager", "https://console.cloud.google.com/apis/credentials", "https://aistudio.google.com/api-keys", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/audio", "titulek": "Audio understanding | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Audio understanding", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/audio", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Audio understanding  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/audio", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Audio understanding"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Audio understanding", "item": "https://ai.google.dev/gemini-api/docs/generate-content/audio"}]}], "drobecky": ["Generate Content API", "Audio understanding"], "osnova": [{"uroven": 1, "text": "Audio understanding"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Overview"}, {"uroven": 2, "text": "Transcribe speech to text"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Input audio"}, {"uroven": 3, "text": "Upload an audio file"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Pass audio data inline"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 2, "text": "Get a transcript"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 2, "text": "Refer to timestamps"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 2, "text": "Count tokens"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 2, "text": "Supported audio formats"}, {"uroven": 2, "text": "Technical details about audio"}, {"uroven": 2, "text": "What's next"}], "markdown": "Audio understanding Gemini can analyze audio input and generate text responses. Python`from google import genai client = genai.Client() myfile = client.files.upload(file=\"path/to/sample.mp3\") response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[\"Describe this audio clip\", myfile] ) print(response.text)` JavaScript`import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const myfile = await ai.files.upload({ file: \"path/to/sample.mp3\", config: { mimeType: \"audio/mp3\" }, }); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: createUserContent([ createPartFromUri(myfile.uri, myfile.mimeType), \"Describe this audio clip\", ]), }); console.log(response.text); } await main();` 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) } localAudioPath := \"/path/to/sample.mp3\" uploadedFile, _ := client.Files.UploadFromPath( ctx, localAudioPath, nil, ) parts := []*genai.Part{ genai.NewPartFromText(\"Describe this audio clip\"), genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` REST`AUDIO_PATH=\"path/to/sample.mp3\" MIME_TYPE=$(file -b --mime-type \"${AUDIO_PATH}\") NUM_BYTES=$(wc -c < \"${AUDIO_PATH}\") DISPLAY_NAME=AUDIO\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${AUDIO_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) echo file_uri=$file_uri # Now generate content using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"text\": \"Describe this audio clip\"}, {\"file_data\":{\"mime_type\": \"${MIME_TYPE}\", \"file_uri\": '$file_uri'}}] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` Overview Gemini can analyze and understand audio input and generate text responses to it,\nenabling use cases like the following: Describe, summarize, or answer questions about audio content. Provide a transcription and translation of the audio (speech to text). Detect emotion in speech and music. Analyze specific segments of the audio, and provide timestamps. As of now the Gemini API doesn't support real-time transcription use cases.\nFor real-time voice and video interactions refer to the [Live API](/gemini-api/docs/live).\nFor dedicated speech to text models with support for real-time transcription,\nuse the [Google Cloud Speech-to-Text API](https://cloud.google.com/speech-to-text). Transcribe speech to text This example application shows how to prompt the Gemini API to transcribe,\ntranslate, and summarize speech, including timestamps and emotion detection\nusing [structured outputs](/gemini-api/docs/structured-output). Python`from google import genai from google.genai import types client = genai.Client() YOUTUBE_URL = \"https://www.youtube.com/watch?v=ku-N-eS1lgM\" def main(): prompt = \"\"\" Process the audio file and generate a detailed transcription. Requirements: 1. Provide accurate timestamps for each segment (Format: MM:SS). 2. Detect the primary language of each segment. 3. If the segment is in a language different than English, also provide the English translation. 4. Identify the primary emotion of the speaker in this segment. You MUST choose exactly one of the following: Happy, Sad, Angry, Neutral. 5. Provide a brief summary of the entire audio at the beginning. \"\"\" response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[ types.Content( parts=[ types.Part( file_data=types.FileData( file_uri=YOUTUBE_URL ) ), types.Part( text=prompt ) ] ) ], config=types.GenerateContentConfig( response_format={\"text\": {\"mime_type\": \"application/json\"}}, response_schema=types.Schema( type=types.Type.OBJECT, properties={ \"summary\": types.Schema( type=types.Type.STRING, description=\"A concise summary of the audio content.\", ), \"segments\": types.Schema( type=types.Type.ARRAY, description=\"List of transcribed segments with timestamp.\", items=types.Schema( type=types.Type.OBJECT, properties={ \"timestamp\": types.Schema(type=types.Type.STRING), \"content\": types.Schema(type=types.Type.STRING), \"language\": types.Schema(type=types.Type.STRING), \"language_code\": types.Schema(type=types.Type.STRING), \"translation\": types.Schema(type=types.Type.STRING), \"emotion\": types.Schema( type=types.Type.STRING, enum=[\"happy\", \"sad\", \"angry\", \"neutral\"] ), }, required=[\"timestamp\", \"content\", \"language\", \"language_code\", \"emotion\"], ), ), }, required=[\"summary\", \"segments\"], ), ), ) print(response.text) if __name__ == \"__main__\": main()` JavaScript`import { GoogleGenAI, Type } from \"@google/genai\"; const ai = new GoogleGenAI({}); const YOUTUBE_URL = \"https://www.youtube.com/watch?v=ku-N-eS1lgM\"; async function main() { const prompt = ` Process the audio file and generate a detailed transcription. Requirements: 1. Provide accurate timestamps for each segment (Format: MM:SS). 2. Detect the primary language of each segment. 3. If the segment is in a language different than English, also provide the English translation. 4. Identify the primary emotion of the speaker in this segment. You MUST choose exactly one of the following: Happy, Sad, Angry, Neutral. 5. Provide a brief summary of the entire audio at the beginning. `; const Emotion = { Happy: 'happy', Sad: 'sad', Angry: 'angry', Neutral: 'neutral' }; const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: { parts: [ { fileData: { fileUri: YOUTUBE_URL, }, }, { text: prompt, }, ], }, config: { responseFormat: { text: { mimeType: \"application/json\" } }, responseSchema: { type: Type.OBJECT, properties: { summary: { type: Type.STRING, description: \"A concise summary of the audio content.\", }, segments: { type: Type.ARRAY, description: \"List of transcribed segments with timestamp.\", items: { type: Type.OBJECT, properties: { timestamp: { type: Type.STRING }, content: { type: Type.STRING }, language: { type: Type.STRING }, language_code: { type: Type.STRING }, translation: { type: Type.STRING }, emotion: { type: Type.STRING, enum: Object.values(Emotion) }, }, required: [\"timestamp\", \"content\", \"language\", \"language_code\", \"emotion\"], }, }, }, required: [\"summary\", \"segments\"], }, }, }); const json = JSON.parse(response.text); console.log(json); } await main();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"parts\": [ { \"file_data\": { \"file_uri\": \"https://www.youtube.com/watch?v=ku-N-eS1lgM\", \"mime_type\": \"video/mp4\" } }, { \"text\": \"Process the audio file and generate a detailed transcription.\\n\\nRequirements:\\n1. Provide accurate timestamps for each segment (Format: MM:SS).\\n2. Detect the primary language of each segment.\\n3. If the segment is in a language different than English, also provide the English translation.\\n4. Identify the primary emotion of the speaker in this segment. You MUST choose exactly one of the following: Happy, Sad, Angry, Neutral.\\n5. Provide a brief summary of the entire audio at the beginning.\" } ] } ], \"generation_config\": { \"response_format\": {\"text\": {\"mime_type\": \"application/json\"}}, \"response_schema\": { \"type\": \"OBJECT\", \"properties\": { \"summary\": { \"type\": \"STRING\", \"description\": \"A concise summary of the audio content.\" }, \"segments\": { \"type\": \"ARRAY\", \"description\": \"List of transcribed segments with timestamp.\", \"items\": { \"type\": \"OBJECT\", \"properties\": { \"timestamp\": { \"type\": \"STRING\" }, \"content\": { \"type\": \"STRING\" }, \"language\": { \"type\": \"STRING\" }, \"language_code\": { \"type\": \"STRING\" }, \"translation\": { \"type\": \"STRING\" }, \"emotion\": { \"type\": \"STRING\", \"enum\": [\"happy\", \"sad\", \"angry\", \"neutral\"] } }, \"required\": [\"timestamp\", \"content\", \"language\", \"language_code\", \"emotion\"] } } }, \"required\": [\"summary\", \"segments\"] } } }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` You can prompt [AI Studio Build](https://aistudio.google.com/apps?e=0) to create\nan app just like\n[this example transcription app](https://aistudio.google.com/apps/bundled/echoscript)\n, with the click of a button. Input audio You can provide audio data to Gemini in the following ways: Upload an audio file before making a request to\n`generateContent`. Pass inline audio data with the request to\n`generateContent`. To learn about other file input methods, see the\n[File input methods](/gemini-api/docs/file-input-methods) guide. Upload an audio file You can use the [Files API](/gemini-api/docs/files) to upload an audio file.\nAlways use the Files API when the total request size (including the files, text\nprompt, system instructions, etc.) is larger than 20 MB. The following code uploads an audio file and then uses the file in a call to\n`generateContent`. Python`from google import genai client = genai.Client() myfile = client.files.upload(file=\"path/to/sample.mp3\") response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[\"Describe this audio clip\", myfile] ) print(response.text)` JavaScript`import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const myfile = await ai.files.upload({ file: \"path/to/sample.mp3\", config: { mimeType: \"audio/mp3\" }, }); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: createUserContent([ createPartFromUri(myfile.uri, myfile.mimeType), \"Describe this audio clip\", ]), }); console.log(response.text); } await main();` 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) } localAudioPath := \"/path/to/sample.mp3\" uploadedFile, _ := client.Files.UploadFromPath( ctx, localAudioPath, nil, ) parts := []*genai.Part{ genai.NewPartFromText(\"Describe this audio clip\"), genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` REST`AUDIO_PATH=\"path/to/sample.mp3\" MIME_TYPE=$(file -b --mime-type \"${AUDIO_PATH}\") NUM_BYTES=$(wc -c < \"${AUDIO_PATH}\") DISPLAY_NAME=AUDIO\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${AUDIO_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) echo file_uri=$file_uri # Now generate content using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"text\": \"Describe this audio clip\"}, {\"file_data\":{\"mime_type\": \"${MIME_TYPE}\", \"file_uri\": '$file_uri'}}] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` To learn more about working with media files, see\n[Files API](/gemini-api/docs/files). Pass audio data inline Instead of uploading an audio file, you can pass inline audio data in the\nrequest to `generateContent`: Python`from google import genai from google.genai import types with open('path/to/small-sample.mp3', 'rb') as f: audio_bytes = f.read() client = genai.Client() response = client.models.generate_content( model='gemini-3.8-flash', contents=[ 'Describe this audio clip', types.Part.from_bytes( data=audio_bytes, mime_type='audio/mp3', ) ] ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const ai = new GoogleGenAI({}); const base64AudioFile = fs.readFileSync(\"path/to/small-sample.mp3\", { encoding: \"base64\", }); const contents = [ { text: \"Please summarize the audio.\" }, { inlineData: { mimeType: \"audio/mp3\", data: base64AudioFile, }, }, ]; const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: contents, }); console.log(response.text);` 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) } audioBytes, _ := os.ReadFile(\"/path/to/small-sample.mp3\") parts := []*genai.Part{ genai.NewPartFromText(\"Describe this audio clip\"), &genai.Part{ InlineData: &genai.Blob{ MIMEType: \"audio/mp3\", Data: audioBytes, }, }, } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` A few things to keep in mind about inline audio data: The maximum request size is 20 MB, which includes text prompts,\nsystem instructions, and files provided inline. If your file's\nsize will make the *total request size* exceed 20 MB, then\nuse the Files API to upload an audio file for use in\nthe request. If you're using an audio sample multiple times, it's more efficient\nto upload an audio file. Get a transcript To get a transcript of audio data, just ask for it in the prompt: Python`from google import genai client = genai.Client() myfile = client.files.upload(file='path/to/sample.mp3') prompt = 'Generate a transcript of the speech.' response = client.models.generate_content( model='gemini-3.8-flash', contents=[prompt, myfile] ) print(response.text)` JavaScript`import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; const ai = new GoogleGenAI({}); const myfile = await ai.files.upload({ file: \"path/to/sample.mp3\", config: { mimeType: \"audio/mpeg\" }, }); const result = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: createUserContent([ createPartFromUri(myfile.uri, myfile.mimeType), \"Generate a transcript of the speech.\", ]), }); console.log(\"result.text=\", result.text);` 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) } localAudioPath := \"/path/to/sample.mp3\" uploadedFile, _ := client.Files.UploadFromPath( ctx, localAudioPath, nil, ) parts := []*genai.Part{ genai.NewPartFromText(\"Generate a transcript of the speech.\"), genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` Refer to timestamps You can refer to specific sections of an audio file using timestamps of the form\n`MM:SS`. For example, the following prompt requests a transcript that Starts at 2 minutes 30 seconds from the beginning of the file. Ends at 3 minutes 29 seconds from the beginning of the file. Python`# Create a prompt containing timestamps. prompt = \"Provide a transcript of the speech from 02:30 to 03:29.\"` JavaScript`// Create a prompt containing timestamps. const prompt = \"Provide a transcript of the speech from 02:30 to 03:29.\"` 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) } localAudioPath := \"/path/to/sample.mp3\" uploadedFile, _ := client.Files.UploadFromPath( ctx, localAudioPath, nil, ) parts := []*genai.Part{ genai.NewPartFromText(\"Provide a transcript of the speech \" + \"between the timestamps 02:30 and 03:29.\"), genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` Count tokens Call the `countTokens` method to get a count of the number of tokens in an\naudio file. For example: Python`from google import genai client = genai.Client() response = client.models.count_tokens( model='gemini-3.8-flash', contents=[myfile] ) print(response)` JavaScript`import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; const ai = new GoogleGenAI({}); const myfile = await ai.files.upload({ file: \"path/to/sample.mp3\", config: { mimeType: \"audio/mpeg\" }, }); const countTokensResponse = await ai.models.countTokens({ model: \"gemini-3.8-flash\", contents: createUserContent([ createPartFromUri(myfile.uri, myfile.mimeType), ]), }); console.log(countTokensResponse.totalTokens);` 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) } localAudioPath := \"/path/to/sample.mp3\" uploadedFile, _ := client.Files.UploadFromPath( ctx, localAudioPath, nil, ) parts := []*genai.Part{ genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } tokens, _ := client.Models.CountTokens( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Printf(\"File %s is %d tokens\\n\", localAudioPath, tokens.TotalTokens) }` Supported audio formats Gemini supports the following audio format MIME types: WAV - `audio/wav` MP3 - `audio/mp3` AIFF - `audio/aiff` AAC - `audio/aac` OGG - `audio/ogg` FLAC - `audio/flac` MPEG - `audio/mpeg` M4A - `audio/m4a` L16 - `audio/l16` Opus - `audio/opus` ALAW - `audio/alaw` MULAW - `audio/mulaw` WebM - `audio/webm` For the complete list of supported MIME types and parameter schemas, see the [Interactions API reference](/api/interactions-api#Resource:Content). Technical details about audio Gemini represents each second of audio as 32 tokens; for example,\none minute of audio is represented as 1,920 tokens. Gemini can \"understand\" non-speech components, such as birdsong or sirens. The maximum supported length of audio data in a single prompt is 9.5 hours.\nGemini doesn't limit the *number* of audio files in a single prompt; however,\nthe total combined length of all audio files in a single prompt can't exceed\n9.5 hours. Gemini downsamples audio files to a 16 Kbps data resolution. If the audio source contains multiple channels, Gemini combines those channels\ninto a single channel. What's next This guide shows how to generate text in response to audio data. To learn more,\nsee the following resources: [File prompting strategies](/gemini-api/docs/files#prompt-guide): The\nGemini API supports prompting with text, image, audio, and video data, also\nknown as multimodal prompting. [System instructions](/gemini-api/docs/text-generation#system-instructions):\nSystem instructions let you steer the behavior of the model based on your\nspecific needs and use cases. [Safety guidance](/gemini-api/docs/safety-guidance): Sometimes generative AI\nmodels produce unexpected outputs, such as outputs that are inaccurate,\nbiased, or offensive. Post-processing and human evaluation are essential to\nlimit the risk of harm from such outputs. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 21406, "slov": 2697, "odkazu": 134, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:27", "sha256": "0a11a8db35da2d0d666cb6b2a3ebef20dc69333653f14afc42d0a201ffe892f4", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://cloud.google.com/speech-to-text", "https://aistudio.google.com/apps?e=0", "https://aistudio.google.com/apps/bundled/echoscript", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/caching", "titulek": "Context caching | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Context caching", "popis": "Learn how to use Context Caching in the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/caching", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Context caching  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Learn how to use Context Caching in the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/caching", "og:image": "https://ai.google.dev/static/site-assets/images/context-caching.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Context caching"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Context caching", "item": "https://ai.google.dev/gemini-api/docs/generate-content/caching"}]}], "drobecky": ["Generate Content API", "Context caching"], "osnova": [{"uroven": 1, "text": "Context caching"}, {"uroven": 2, "text": "Implicit caching"}, {"uroven": 2, "text": "Explicit caching"}, {"uroven": 3, "text": "Generate content using a cache"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Videos"}, {"uroven": 3, "text": "PDFs"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Videos"}, {"uroven": 3, "text": "PDFs"}, {"uroven": 3, "text": "List caches"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Update a cache"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Delete a cache"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Explicit caching using the OpenAI library"}, {"uroven": 2, "text": "When to use explicit caching"}, {"uroven": 3, "text": "How explicit caching reduces costs"}, {"uroven": 3, "text": "Additional considerations"}], "markdown": "Context caching In a typical AI workflow, you might pass the same input tokens over and over to\na model. The Gemini API offers two different caching mechanisms: Implicit caching (automatically enabled on Gemini 2.5 and newer models, no cost saving guarantee) Explicit caching (can be manually enabled on most models, cost saving guarantee) Explicit caching is useful in cases where you want to guarantee cost savings,\nbut with some added developer work. Implicit caching Implicit caching is enabled by default for all Gemini 2.5 and newer models. We automatically\npass on cost savings if your request hits caches. There is nothing you need to do\nin order to enable this. The minimum input\ntoken count for context caching is listed in the following table for each model: Model Min token limit Gemini 3.8 Flash 4,096 Gemini 3.7 Flash 4,096 Gemini 3.6 Flash 4,096 Gemini 3.5 Flash 4,096 Gemini 3.1 Pro Preview 4,096 Gemini 2.5 Flash 2,048 Gemini 2.5 Pro 2,048 To increase the chance of an implicit cache hit: Try putting large and common contents at the beginning of your prompt Try to send requests with similar prefix in a short amount of time You can see the number of tokens which were cache hits in the response object's\n`usage_metadata` field. Explicit caching Using the Gemini API explicit caching feature, you can pass some content\nto the model once, cache the input tokens, and then refer to the cached tokens\nfor subsequent requests. At certain volumes, using cached tokens is lower cost\nthan passing in the same corpus of tokens repeatedly. When you cache a set of tokens, you can choose how long you want the cache to\nexist before the tokens are automatically deleted. This caching duration is\ncalled the *time to live* (TTL). If not set, the TTL defaults to 1 hour. The\ncost for caching depends on the input token size and how long you want the\ntokens to persist. This section assumes that you've installed a Gemini SDK (or have curl installed)\nand that you've configured an API key, as shown in the\n[Get started guide](/gemini-api/docs/generate-content/get-started). Generate content using a cache PythonThe following example shows how to generate content using a cached system\ninstruction and video file. Videos`import os import pathlib import requests import time from google import genai from google.genai import types client = genai.Client() # Download a test video file and save it locally url = 'https://storage.googleapis.com/generativeai-downloads/data/SherlockJr._10min.mp4' path_to_video_file = pathlib.Path('SherlockJr._10min.mp4') if not path_to_video_file.exists(): path_to_video_file.write_bytes(requests.get(url).content) # Upload the video using the Files API video_file = client.files.upload(file=path_to_video_file) # Wait for the file to finish processing while video_file.state.name == 'PROCESSING': time.sleep(2.5) video_file = client.files.get(name=video_file.name) print(f'Video processing complete: {video_file.uri}') model='models/gemini-3.8-flash' # Create a cache with a 5 minute TTL (300 seconds) cache = client.caches.create( model=model, config=types.CreateCachedContentConfig( display_name='sherlock jr movie', # used to identify the cache system_instruction=( 'You are an expert video analyzer, and your job is to answer ' 'the user\\'s query based on the video file you have access to.' ), contents=[video_file], ttl=\"300s\", ) ) response = client.models.generate_content( model = model, contents= ( 'Introduce different characters in the movie by describing ' 'their personality, looks, and names. Also list the timestamps ' 'they were introduced for the first time.'), config=types.GenerateContentConfig(cached_content=cache.name) ) print(response.usage_metadata) print(response.text)` PDFs`from google import genai from google.genai import types import io import httpx client = genai.Client() long_context_pdf_path = \"https://sma.nasa.gov/SignificantIncidents/assets/a11_missionreport.pdf\" # Retrieve and upload the PDF using the File API doc_io = io.BytesIO(httpx.get(long_context_pdf_path).content) document = client.files.upload( file=doc_io, config=dict(mime_type='application/pdf') ) model_name = \"gemini-3.8-flash\" system_instruction = \"You are an expert analyzing transcripts.\" # Create a cached content object cache = client.caches.create( model=model_name, config=types.CreateCachedContentConfig( system_instruction=system_instruction, contents=[document], ) ) print(f'{cache=}') response = client.models.generate_content( model=model_name, contents=\"Please summarize this transcript\", config=types.GenerateContentConfig( cached_content=cache.name )) print(f'{response.usage_metadata=}') print('\\n\\n', response.text)` JavaScriptThe following example shows how to generate content using a cached system\ninstruction and a text file. `import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; const ai = new GoogleGenAI({ apiKey: \"GEMINI_API_KEY\" }); async function main() { const doc = await ai.files.upload({ file: \"path/to/file.txt\", config: { mimeType: \"text/plain\" }, }); console.log(\"Uploaded file name:\", doc.name); const modelName = \"gemini-3.8-flash\"; const cache = await ai.caches.create({ model: modelName, config: { contents: createUserContent(createPartFromUri(doc.uri, doc.mimeType)), systemInstruction: \"You are an expert analyzing transcripts.\", }, }); console.log(\"Cache created:\", cache); const response = await ai.models.generateContent({ model: modelName, contents: \"Please summarize this transcript\", config: { cachedContent: cache.name }, }); console.log(\"Response text:\", response.text); } await main();` GoThe following example shows how to generate content using a cache. `package main import ( \"context\" \"fmt\" \"log\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: \"GOOGLE_API_KEY\", Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } modelName := \"gemini-3.8-flash\" document, err := client.Files.UploadFromPath( ctx, \"media/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) } fmt.Println(\"Cache created:\") fmt.Println(cache) // Use the cache for generating content. response, err := client.Models.GenerateContent( ctx, modelName, genai.Text(\"Please summarize this transcript\"), &genai.GenerateContentConfig{ CachedContent: cache.Name, }, ) if err != nil { log.Fatal(err) } printResponse(response) // helper for printing response parts }` RESTThe following example shows how to create a cache and then use it to\ngenerate content. Videos`wget https://storage.googleapis.com/generativeai-downloads/data/a11.txt\necho '{ \"model\": \"models/gemini-3.8-flash\", \"contents\":[ { \"parts\":[ { \"inline_data\": { \"mime_type\":\"text/plain\", \"data\": \"'$(base64 $B64FLAGS a11.txt)'\" } } ], \"role\": \"user\" } ], \"systemInstruction\": { \"parts\": [ { \"text\": \"You are an expert at analyzing transcripts.\" } ] }, \"ttl\": \"300s\" }' > request.json\n\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d @request.json \\\n> cache.json\n\nCACHE_NAME=$(cat cache.json | grep '\"name\":' | cut -d '\"' -f 4 | head -n 1)\n\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d '{ \"contents\": [ { \"parts\":[{ \"text\": \"Please summarize this transcript\" }], \"role\": \"user\" }, ], \"cachedContent\": \"'$CACHE_NAME'\" }'` PDFs`DOC_URL=\"https://sma.nasa.gov/SignificantIncidents/assets/a11_missionreport.pdf\" DISPLAY_NAME=\"A11_Mission_Report\" SYSTEM_INSTRUCTION=\"You are an expert at analyzing transcripts.\" PROMPT=\"Please summarize this transcript\" MODEL=\"models/gemini-3.8-flash\" TTL=\"300s\" # Download the PDF\nwget -O \"${DISPLAY_NAME}.pdf\" \"${DOC_URL}\" MIME_TYPE=$(file -b --mime-type \"${DISPLAY_NAME}.pdf\") NUM_BYTES=$(wc -c < \"${DISPLAY_NAME}.pdf\") echo \"MIME_TYPE: ${MIME_TYPE}\" echo \"NUM_BYTES: ${NUM_BYTES}\" tmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${DISPLAY_NAME}.pdf\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) echo \"file_uri: ${file_uri}\" # Clean up the downloaded PDF\nrm \"${DISPLAY_NAME}.pdf\" # Create the cached content request echo '{ \"model\": \"'$MODEL'\", \"contents\":[ { \"parts\":[ {\"file_data\": {\"mime_type\": \"'$MIME_TYPE'\", \"file_uri\": '$file_uri'}} ], \"role\": \"user\" } ], \"system_instruction\": { \"parts\": [ { \"text\": \"'$SYSTEM_INSTRUCTION'\" } ], \"role\": \"system\" }, \"ttl\": \"'$TTL'\" }' > request.json\n\n# Send the cached content request\ncurl -X POST \"${BASE_URL}/v1beta/cachedContents?key=$GOOGLE_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d @request.json \\\n> cache.json\n\nCACHE_NAME=$(cat cache.json | grep '\"name\":' | cut -d '\"' -f 4 | head -n 1) echo \"CACHE_NAME: ${CACHE_NAME}\" # Send the generateContent request using the cached content\ncurl -X POST \"${BASE_URL}/${MODEL}:generateContent?key=$GOOGLE_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d '{ \"contents\": [ { \"parts\":[{ \"text\": \"'$PROMPT'\" }], \"role\": \"user\" } ], \"cachedContent\": \"'$CACHE_NAME'\" }' > response.json\n\ncat response.json\n\necho jq \".candidates[].content.parts[].text\" response.json` List caches It's not possible to retrieve or view cached content, but you can retrieve\ncache metadata (`name`, `model`, `display_name`, `usage_metadata`,\n`create_time`, `update_time`, and `expire_time`). PythonTo list metadata for all uploaded caches, use `CachedContent.list()`: `for cache in client.caches.list(): print(cache)` To fetch the metadata for one cache object, if you know its name, use `get`: `client.caches.get(name=name)` JavaScriptTo list metadata for all uploaded caches, use `GoogleGenAI.caches.list()`: `console.log(\"My caches:\"); const pager = await ai.caches.list({ config: { pageSize: 10 } }); let page = pager.page; while (true) { for (const c of page) { console.log(\" \", c.name); } if (!pager.hasNextPage()) break; page = await pager.nextPage(); }` GoThe following example lists all caches. `caches, err := client.Caches.All(ctx) if err != nil { log.Fatal(err) } fmt.Println(\"Listing all caches:\") for _, item := range caches { fmt.Println(\" \", item.Name) }` The following example lists caches using a page size of 2. `page, err := client.Caches.List(ctx, &genai.ListCachedContentsConfig{PageSize: 2}) if err != nil { log.Fatal(err) } pageIndex := 1 for { fmt.Printf(\"Listing caches (page %d):\\n\", pageIndex) for _, item := range page.Items { fmt.Println(\" \", item.Name) } if page.NextPageToken == \"\" { break } page, err = page.Next(ctx) if err == genai.ErrPageDone { break } else if err != nil { return err } pageIndex++ }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GEMINI_API_KEY\"` Update a cache You can set a new `ttl` or `expire_time` for a cache. Changing anything else\nabout the cache isn't supported. PythonThe following example shows how to update the `ttl` of a cache using\n`client.caches.update()`. `from google import genai from google.genai import types client.caches.update( name = cache.name, config = types.UpdateCachedContentConfig( ttl='300s' ) )` To set the expiry time, it will accepts either a `datetime` object\nor an ISO-formatted datetime string (`dt.isoformat()`, like\n`2025-01-27T16:02:36.473528+00:00`). Your time must include a time zone\n(`datetime.utcnow()` doesn't attach a time zone,\n`datetime.now(datetime.timezone.utc)` does attach a time zone). `from google import genai from google.genai import types import datetime # You must use a time zone-aware time. in10min = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=10) client.caches.update( name = cache.name, config = types.UpdateCachedContentConfig( expire_time=in10min ) )` JavaScriptThe following example shows how to update the `ttl` of a cache using\n`GoogleGenAI.caches.update()`. `const ttl = `${2 * 3600}s`; // 2 hours in seconds const updatedCache = await ai.caches.update({ name: cache.name, config: { ttl }, }); console.log(\"After update (TTL):\", updatedCache);` GoThe following example shows how to update the `TTL` of a cache. `// Update the TTL (2 hours). cache, err = client.Caches.Update(ctx, cache.Name, &genai.UpdateCachedContentConfig{ TTL: 7200 * time.Second, }) if err != nil { log.Fatal(err) } fmt.Println(\"After update:\") fmt.Println(cache)` RESTThe following example shows how to update the `ttl` of a cache. `curl -X PATCH \"https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d '{\"ttl\": \"600s\"}'` Delete a cache The caching service provides a delete operation for manually removing content\nfrom the cache. The following example shows how to delete a cache: Python`client.caches.delete(cache.name)` JavaScript`await ai.caches.delete({ name: cache.name });` Go`_, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{}) if err != nil { log.Fatal(err) } fmt.Println(\"Cache deleted:\", cache.Name)` REST`curl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY\"` Explicit caching using the OpenAI library If you're using an [OpenAI library](/gemini-api/docs/openai), you can enable\nexplicit caching using the `cached_content` property on\n[`extra_body`](/gemini-api/docs/openai#extra-body). When to use explicit caching Context caching is particularly well suited to scenarios where a substantial\ninitial context is referenced repeatedly by shorter requests. Consider using\ncontext caching for use cases such as: Chatbots with extensive [system instructions](/gemini-api/docs/system-instructions) Repetitive analysis of lengthy video files Recurring queries against large document sets Frequent code repository analysis or bug fixing How explicit caching reduces costs Context caching is a paid feature designed to reduce cost. Billing is based on\nthe following factors: **Cache token count:** The number of input tokens cached, billed at a\nreduced rate when included in subsequent prompts. **Storage duration:** The amount of time cached tokens are stored (TTL),\nbilled based on the TTL duration of cached token count. There are no minimum\nor maximum bounds on the TTL. **Other factors:** Other charges apply, such as for non-cached input tokens\nand output tokens. For up-to-date pricing details, refer to the Gemini API [pricing\npage](/pricing). To learn how to count tokens, see the [Token\nguide](/gemini-api/docs/tokens). Additional considerations Keep the following considerations in mind when using context caching: The *minimum* input token count for context caching varies by model. The *maximum*\nis the same as the maximum for the given model. (For more on counting tokens,\nsee the [Token guide](/gemini-api/docs/tokens)). The model doesn't make any distinction between cached tokens and regular\ninput tokens. Cached content is a prefix to the prompt. There are no special rate or usage limits on context caching; the standard\nrate limits for `GenerateContent` apply, and token limits include cached\ntokens. The number of cached tokens is returned in the `usage_metadata` from the\ncreate, get, and list operations of the cache service, and also in\n`GenerateContent` when using the cache. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-11 UTC.", "znaku_textu": 16704, "slov": 2167, "odkazu": 126, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:48", "sha256": "e704ddbde73014f504807a367865a50564cc80a302b533a0bcb6c9e6e2e8c47d", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/code-execution", "titulek": "Code execution | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Code execution", "popis": "Learn how to use the Gemini API code execution feature.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/code-execution", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Code execution  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Learn how to use the Gemini API code execution feature.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/code-execution", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Code execution"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Code execution", "item": "https://ai.google.dev/gemini-api/docs/generate-content/code-execution"}]}], "drobecky": ["Generate Content API", "Code execution"], "osnova": [{"uroven": 1, "text": "Code execution"}, {"uroven": 2, "text": "Enable code execution"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Code Execution with images (Gemini 3)"}, {"uroven": 3, "text": "Enable Code Execution with images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Use code execution in chat"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Input/output (I/O)"}, {"uroven": 3, "text": "I/O pricing"}, {"uroven": 3, "text": "I/O details"}, {"uroven": 2, "text": "Billing"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "Supported tools combinations"}, {"uroven": 2, "text": "Supported libraries"}, {"uroven": 2, "text": "What's next"}], "markdown": "Code execution The Gemini API provides a code execution tool that enables the model to\ngenerate and run Python code. The model can then learn iteratively from the\ncode execution results until it arrives at a final output. You can use code\nexecution to build applications that benefit from code-based reasoning. For\nexample, you can use code execution to solve equations or process text. You can\nalso use the libraries included in the code execution\nenvironment to perform more specialized tasks. Gemini is only able to execute code in Python. You can still ask Gemini to\ngenerate code in another language, but the model can't use the code execution\ntool to run it. Enable code execution To enable code execution, configure the code execution tool on the model. This\nallows the model to generate and run code. Python`from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"What is the sum of the first 50 prime numbers? \" \"Generate and run code for the calculation, and make sure you get all 50.\", config=types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution)] ), ) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) if part.executable_code is not None: print(part.executable_code.code) if part.code_execution_result is not None: print(part.code_execution_result.output)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); let response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: [ \"What is the sum of the first 50 prime numbers? \" + \"Generate and run code for the calculation, and make sure you get all 50.\", ], config: { tools: [{ codeExecution: {} }], }, }); const parts = response?.candidates?.[0]?.content?.parts || []; parts.forEach((part) => { if (part.text) { console.log(part.text); } if (part.executableCode && part.executableCode.code) { console.log(part.executableCode.code); } if (part.codeExecutionResult && part.codeExecutionResult.output) { console.log(part.codeExecutionResult.output); } });` 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{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", genai.Text(\"What is the sum of the first 50 prime numbers? \" + \"Generate and run code for the calculation, and make sure you get all 50.\"), config, ) fmt.Println(result.Text()) fmt.Println(result.ExecutableCode()) fmt.Println(result.CodeExecutionResult()) }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d ' {\"tools\": [{\"code_execution\": {}}], \"contents\": { \"parts\": { \"text\": \"What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.\" } }, }'` The output might look something like the following, which has been formatted for\nreadability: `Okay, I need to calculate the sum of the first 50 prime numbers. Here's how I'll\napproach this:\n\n1. **Generate Prime Numbers:** I'll use an iterative method to find prime\n numbers. I'll start with 2 and check if each subsequent number is divisible\n by any number between 2 and its square root. If not, it's a prime.\n2. **Store Primes:** I'll store the prime numbers in a list until I have 50 of\n them.\n3. **Calculate the Sum:** Finally, I'll sum the prime numbers in the list.\n\nHere's the Python code to do this:\n\ndef is_prime(n):\n \"\"\"Efficiently checks if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n\nprimes = []\nnum = 2\nwhile len(primes) < 50:\n if is_prime(num):\n primes.append(num)\n num += 1\n\nsum_of_primes = sum(primes)\nprint(f'{primes=}')\nprint(f'{sum_of_primes=}')\n\nprimes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,\n71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229]\nsum_of_primes=5117\n\nThe sum of the first 50 prime numbers is 5117.` This output combines several content parts that the model returns when using\ncode execution: `text`: Inline text generated by the model `executableCode`: Code generated by the model that is meant to be executed `codeExecutionResult`: Result of the executable code The naming conventions for these parts vary by programming language. Code Execution with images (Gemini 3) The Gemini 3 Flash model can now write and execute Python code to actively\nmanipulate and inspect images. **Use cases** **Zoom and inspect**: The model implicitly detects when details are too small\n(e.g., reading a distant gauge) and writes code to crop and re-examine the area\nat higher resolution. **Visual math**: The model can run multi-step calculations using code (e.g.,\nsumming line items on a receipt). **Image annotation**: The model can annotate images to answer questions, such\nas drawing arrows to show relationships. Enable Code Execution with images Code Execution with images is officially supported in Gemini 3 Flash. You can\nactivate this behavior by enabling both Code Execution as a tool and Thinking. Python`from google import genai from google.genai import types import requests from PIL import Image import io image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content image = types.Part.from_bytes( data=image_bytes, mime_type=\"image/jpeg\" ) # Ensure you have your API key set client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[image, \"Zoom into the expression pedals and tell me how many pedals are there?\"], config=types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution)] ), ) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) if part.executable_code is not None: print(part.executable_code.code) if part.code_execution_result is not None: print(part.code_execution_result.output) if part.as_image() is not None: # display() is a standard function in Jupyter/Colab notebooks display(Image.open(io.BytesIO(part.as_image().image_bytes)))` JavaScript`async function main() { const ai = new GoogleGenAI({ }); // 1. Prepare Image Data const imageUrl = \"https://goo.gle/instrument-img\"; const response = await fetch(imageUrl); const imageArrayBuffer = await response.arrayBuffer(); const base64ImageData = Buffer.from(imageArrayBuffer).toString('base64'); // 2. Call the API with Code Execution enabled const result = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: [ { inlineData: { mimeType: 'image/jpeg', data: base64ImageData, }, }, { text: \"Zoom into the expression pedals and tell me how many pedals are there?\" } ], config: { tools: [{ codeExecution: {} }], }, }); // 3. Process the response (Text, Code, and Execution Results) const candidates = result.candidates; if (candidates && candidates[0].content.parts) { for (const part of candidates[0].content.parts) { if (part.text) { console.log(\"Text:\", part.text); } if (part.executableCode) { console.log(`\\nGenerated Code (${part.executableCode.language}):\\n`, part.executableCode.code); } if (part.codeExecutionResult) { console.log(`\\nExecution Output (${part.codeExecutionResult.outcome}):\\n`, part.codeExecutionResult.output); } } } } main();` Go`package main import ( \"context\" \"fmt\" \"io\" \"log\" \"net/http\" \"os\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() // Initialize Client (Reads GEMINI_API_KEY from env) client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } // 1. Download the image imageResp, err := http.Get(\"https://goo.gle/instrument-img\") if err != nil { log.Fatal(err) } defer imageResp.Body.Close() imageBytes, err := io.ReadAll(imageResp.Body) if err != nil { log.Fatal(err) } // 2. Configure Code Execution Tool config := &genai.GenerateContentConfig{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } // 3. Generate Content result, err := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", []*genai.Content{ { Parts: []*genai.Part{ {InlineData: &genai.Blob{MIMEType: \"image/jpeg\", Data: imageBytes}}, {Text: \"Zoom into the expression pedals and tell me how many pedals are there?\"}, }, Role: \"user\", }, }, config, ) if err != nil { log.Fatal(err) } // 4. Parse Response (Text, Code, Output) for _, cand := range result.Candidates { for _, part := range cand.Content.Parts { if part.Text != \"\" { fmt.Println(\"Text:\", part.Text) } if part.ExecutableCode != nil { fmt.Printf(\"\\nGenerated Code (%s):\\n%s\\n\", part.ExecutableCode.Language, part.ExecutableCode.Code) } if part.CodeExecutionResult != nil { fmt.Printf(\"\\nExecution Output (%s):\\n%s\\n\", part.CodeExecutionResult.Outcome, part.CodeExecutionResult.Output) } } } }` REST`IMG_URL=\"https://goo.gle/instrument-img\" MODEL=\"gemini-3.8-flash\" MIME_TYPE=$(curl -sIL \"$IMG_URL\" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\\r$//' | head -n 1) if [[ -z \"$MIME_TYPE\" || ! \"$MIME_TYPE\" == image/* ]]; then MIME_TYPE=\"image/jpeg\" fi if [[ \"$(uname)\" == \"Darwin\" ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -b 0) elif [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64) else IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -w0) fi\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/$MODEL:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ { \"inline_data\": { \"mime_type\":\"'\"$MIME_TYPE\"'\", \"data\": \"'\"$IMAGE_B64\"'\" } }, {\"text\": \"Zoom into the expression pedals and tell me how many pedals are there?\"} ] }], \"tools\": [ { \"code_execution\": {} } ] }'` Use code execution in chat You can also use code execution as part of a chat. Python`from google import genai from google.genai import types client = genai.Client() chat = client.chats.create( model=\"gemini-3.8-flash\", config=types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution)] ), ) response = chat.send_message(\"I have a math question for you.\") print(response.text) response = chat.send_message( \"What is the sum of the first 50 prime numbers? \" \"Generate and run code for the calculation, and make sure you get all 50.\" ) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) if part.executable_code is not None: print(part.executable_code.code) if part.code_execution_result is not None: print(part.code_execution_result.output)` JavaScript`import {GoogleGenAI} from \"@google/genai\"; const ai = new GoogleGenAI({}); const chat = ai.chats.create({ model: \"gemini-3.8-flash\", history: [ { role: \"user\", parts: [{ text: \"I have a math question for you:\" }], }, { role: \"model\", parts: [{ text: \"Great! I'm ready for your math question. Please ask away.\" }], }, ], config: { tools: [{codeExecution:{}}], } }); const response = await chat.sendMessage({ message: \"What is the sum of the first 50 prime numbers? \" + \"Generate and run code for the calculation, and make sure you get all 50.\" }); console.log(\"Chat response:\", response.text);` 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{ Tools: []*genai.Tool{ {CodeExecution: &genai.ToolCodeExecution{}}, }, } chat, _ := client.Chats.Create( ctx, \"gemini-3.8-flash\", config, nil, ) result, _ := chat.SendMessage( ctx, genai.Part{Text: \"What is the sum of the first 50 prime numbers? \" + \"Generate and run code for the calculation, and \" + \"make sure you get all 50.\", }, ) fmt.Println(result.Text()) fmt.Println(result.ExecutableCode()) fmt.Println(result.CodeExecutionResult()) }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-d '{\"tools\": [{\"code_execution\": {}}], \"contents\": [ { \"role\": \"user\", \"parts\": [{ \"text\": \"Write code to print \\\"Hello world!\\\" and execute it\" }] },{ \"role\": \"model\", \"parts\": [ { \"executable_code\": { \"id\": \"a1b2c3d4\", \"language\": \"PYTHON\", \"code\": \"\\nprint(\\\"hello world!\\\")\\n\" } \"thought_signature\": \"...\" }, { \"code_execution_result\": { \"id\": \"a1b2c3d4\", \"outcome\": \"OUTCOME_OK\", \"output\": \"hello world!\\n\" } }, { \"text\": \"I have printed \\\"hello world!\\\" using the provided python code block. \\n\", \"thought_signature\": \"...\" } ], },{ \"role\": \"user\", \"parts\": [{ \"text\": \"What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.\" }] } ] }'` Input/output (I/O) Code execution supports file input and graph output. Using these input and\noutput capabilities, you can upload CSV and text files, ask questions about the\nfiles, and have [Matplotlib](https://matplotlib.org/) graphs generated as part\nof the response. The output files are returned as inline images in the response. I/O pricing When using code execution I/O, you're charged for input tokens and output\ntokens: **Input tokens:** User prompt **Output tokens:** Code generated by the model Code execution output in the code environment Thinking tokens Summary generated by the model I/O details When you're working with code execution I/O, be aware of the following technical\ndetails: The maximum runtime of the code environment is 30 seconds. If the code environment generates an error, the model may decide to\nregenerate the code output. This can happen up to 5 times. The maximum file input size is limited by the model token window. In\nAI Studio, the maximum input file size is 1 million\ntokens (roughly 2MB for text files of the supported input types). If you\nupload a file that's too large, AI Studio won't let you send it. Code execution works best with text and CSV files. The input file can be passed in `part.inlineData` or `part.fileData` (uploaded\nvia the [Files API](/gemini-api/docs/files)), and the output file is always\nreturned as `part.inlineData`. Billing There's no additional charge for enabling code execution from the Gemini API.\nYou'll be billed at the current rate of input and output tokens based on the\nGemini model you're using. Here are a few other things to know about billing for code execution: You're only billed once for the input tokens you pass to the model, and you're\nbilled for the final output tokens returned to you by the model. Tokens representing generated code are counted as output tokens. Generated\ncode can include text and multimodal output like images. Code execution results are also counted as output tokens. The billing model is shown in the following diagram: You're billed at the current rate of input and output tokens based on the\nGemini model you're using. If Gemini uses code execution when generating your response, the original\nprompt, the generated code, and the result of the executed code are labeled\n*intermediate tokens* and are billed as *input tokens*. Gemini then generates a summary and returns the generated code, the result of\nthe executed code, and the final summary. These are billed as *output tokens*. The Gemini API includes an intermediate token count in the API response, so\nyou know why you're getting additional input tokens beyond your initial\nprompt. Limitations The model can only generate and execute code. It can't return other artifacts\nlike media files. In some cases, enabling code execution can lead to regressions in other areas\nof model output (for example, writing a story). There is some variation in the ability of the different models to use code\nexecution successfully. Supported tools combinations Code execution tool can be combined with\n[Grounding with Google Search](/gemini-api/docs/google-search) to\npower more complex use cases. Gemini 3 models support combining built-in tools (like Code Execution) with\ncustom tools (function calling). You must pass back the `id` and\n`thought_signature` fields for tool combination to work. Learn more on the\n[tool combinations](/gemini-api/docs/tool-combination) page. Supported libraries The code execution environment includes the following libraries: attrs chess contourpy fpdf geopandas imageio jinja2 joblib jsonschema jsonschema-specifications lxml matplotlib mpmath numpy opencv-python openpyxl packaging pandas pillow protobuf pylatex pyparsing PyPDF2 python-dateutil python-docx python-pptx reportlab scikit-learn scipy seaborn six striprtf sympy tabulate tensorflow toolz xlrd You can't install your own libraries. What's next Try the\n[code execution Colab](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Code_Execution.ipynb). Learn about other Gemini API tools:\n [Function calling](/gemini-api/docs/function-calling) [Grounding with Google Search](/gemini-api/docs/grounding) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 17683, "slov": 2509, "odkazu": 130, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:16", "sha256": "c6e7224604081fd832f13420a45fd0f01de02296a825b2e32265552f04c27d0f", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://matplotlib.org/", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Code_Execution.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/computer-use", "titulek": "Computer use | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Computer use", "popis": "Learn how to use the Gemini API computer use feature.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/computer-use", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Computer use  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Learn how to use the Gemini API computer use feature.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/computer-use", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Computer use"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Computer use", "item": "https://ai.google.dev/gemini-api/docs/generate-content/computer-use"}]}], "drobecky": ["Generate Content API", "Computer use"], "osnova": [{"uroven": 1, "text": "Computer use"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "How Computer Use works"}, {"uroven": 2, "text": "How to implement Computer Use"}, {"uroven": 3, "text": "0. Set up Playwright"}, {"uroven": 3, "text": "1. Send a request to the model"}, {"uroven": 3, "text": "Gemini 3.x"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Gemini 2.5 (Legacy)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "2. Receive the model response"}, {"uroven": 3, "text": "Gemini 3.x"}, {"uroven": 3, "text": "Gemini 2.5 (Legacy)"}, {"uroven": 3, "text": "3. Execute the received actions"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "4. Capture the new environment state"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Build an agent loop"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Supported environments (Gemini 3.x)"}, {"uroven": 3, "text": "Browser environment (ENVIRONMENT_BROWSER)"}, {"uroven": 3, "text": "Mobile environment (ENVIRONMENT_MOBILE)"}, {"uroven": 3, "text": "Desktop environment (ENVIRONMENT_DESKTOP)"}, {"uroven": 2, "text": "Legacy Supported UI actions (Gemini 2.5)"}, {"uroven": 2, "text": "Custom user-defined functions"}, {"uroven": 4, "text": "Gemini 3.x Custom Tooling"}, {"uroven": 3, "text": "Python"}, {"uroven": 4, "text": "Gemini 2.5 (Legacy) Custom Tooling"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Managing thinking levels (Gemini 3.x)"}, {"uroven": 2, "text": "Safety and security"}, {"uroven": 3, "text": "Configuring safety policies (Gemini 3.x)"}, {"uroven": 4, "text": "Safety overrides"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Prompt injection detection (Gemini 3.x)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "cURL"}, {"uroven": 3, "text": "Acknowledge safety decision"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Safety best practices"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Model versions"}, {"uroven": 2, "text": "What's next"}], "markdown": "Computer use The Computer Use tool lets you build browser, mobile, and desktop control agents\nthat interact with and automate tasks. Using screenshots, the model can \"see\" a\ncomputer screen, and \"act\" by generating specific UI actions like mouse clicks\nand keyboard inputs. Similar to function calling, you will need to implement the\nclient-side execution environment to receive and execute the Computer Use\nactions. For the list of supported models, see Model versions. The Gemini 3.x models support several advanced capabilities: **Multi-environment support:** build agents for browser, mobile, and desktop environments. **Streamlined actions with intents:** actions include an `intent` field that explains the model's reasoning behind each step. **Configurable safety policies:** fine-tune safety behavior with built-in policy categories and overrides. **Prompt injection detection:** opt-in screenshot scanning to detect hidden adversarial instructions. With Computer Use, you can build agents that: Automate repetitive data entry or form filling on websites. Perform automated testing of web applications and user flows Conduct research across various websites (e.g., gathering product\ninformation, prices, and reviews from ecommerce sites to inform a purchase) Here's a minimal example of enabling the Computer Use tool: Python`from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Search for 'Gemini API' on Google.\", config=types.GenerateContentConfig( tools=[types.Tool( computer_use=types.ComputerUse( environment=types.Environment.ENVIRONMENT_BROWSER, ) )] ) ) print(response.text)` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: \"Search for 'Gemini API' on Google.\", config: { tools: [{ computerUse: { environment: \"ENVIRONMENT_BROWSER\", } }] } }); console.log(response.text);` How Computer Use works To build an agent with the Computer Use model, you need to set up a\ncontinuous loop between your application and the API. Here is what your code\nwill do at each step: **Send a request to the model** Your application sends an API request containing the Computer Use tool,\nyour configuration settings (like the target environment), the user's\nprompt, and a screenshot of the current screen. **Receive the model response** The model analyzes the screen and the prompt, returning a response\nwhich includes a suggested `function_call` representing a UI action (such\nas a click, scroll, or keystroke). For **Gemini 3.x models**, the response also includes a reasoning `intent`\nexplaining why the model chose that action. The response may also include a `safety_decision` from an internal safety\nsystem that classifies the action as regular/allowed,\n`require_confirmation` (requiring user approval), or blocked. **Execute the received action** If the action is allowed (or the user confirms it), your client-side\ncode parses the `function_call`, scales the normalized coordinates to match\nyour viewport, and executes the action in your target environment using\nautomation tools (such as Playwright). If the action is blocked, your\nclient should halt the execution or handle the interruption. **Capture the new environment state** After the action finishes executing, your application captures a new\nscreenshot and sends it back to the model in a `function_result` to\nrequest the next step. This process then repeats from step 2, continually soliciting the next action\nfrom the model until the task is completed or terminated. How to implement Computer Use Before building with the Computer Use tool you will need to set up: **Secure execution environment:** Run your agent in a sandboxed VM or\ncontainer to isolate it from your host system and limit its potential impact.\nThe [reference implementation](https://github.com/google/computer-use-preview/)\nincludes a ready-to-use Docker-based sandbox you can use as a starting point. **Client-side action handler:** Implement client-side logic to execute coordinates, type text, and take screenshots. The examples below use a web browser as the execution environment and\n[Playwright](https://playwright.dev/) as the client-side handler. 0. Set up Playwright First, install the required packages: `pip install google-genai playwright\nplaywright install chromium` Then, initialize a Playwright browser instance to use for execution: `from playwright.sync_api import sync_playwright # 1. Configure screen dimensions for the target environment SCREEN_WIDTH = 1440 SCREEN_HEIGHT = 900 # 2. Start the Playwright browser # In production, utilize a sandboxed environment. playwright = sync_playwright().start() # Set headless=False to see the actions performed on your screen browser = playwright.chromium.launch(headless=False) # 3. Create a context and page with the specified dimensions context = browser.new_context( viewport={\"width\": SCREEN_WIDTH, \"height\": SCREEN_HEIGHT} ) page = context.new_page() # 4. Navigate to an initial page to start the task page.goto(\"https://www.google.com\") # The 'page', 'SCREEN_WIDTH', and 'SCREEN_HEIGHT' variables # will be used in the steps below.` 1. Send a request to the model Initialize the client library and configure the Computer Use tool. Note that there is no need to specify the display size when issuing a request; the model predicts pixel coordinates scaled to the height and width of the screen. Gemini 3.x PythonUse the `google-genai` Python SDK (version `2.7.0` or higher) to configure a request targeting the browser environment: `from google import genai from google.genai.types import ( Content, Part, GenerateContentConfig, Tool, ComputerUse, Environment, ThinkingConfig, ) client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[ Content( role=\"user\", parts=[ Part(text=\"Find a flight from SF to Hawaii on Jun 30th, coming back on Jul 6th\"), ], ) ], config=GenerateContentConfig( tools=[ Tool( computer_use=ComputerUse( environment=Environment.ENVIRONMENT_BROWSER, enable_prompt_injection_detection=True, ), ), ], thinking_config=ThinkingConfig( include_thoughts=True ), ) ) print(response.text)` JavaScriptUse the `@google/genai` Node.js SDK to configure a request targeting the browser environment: `import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: [ { role: 'user', parts: [{ text: \"Find a flight from SF to Hawaii on Jun 30th, coming back on Jul 6th\" }] } ], config: { tools: [{ computerUse: { environment: \"ENVIRONMENT_BROWSER\", enable_prompt_injection_detection: true } }], thinkingConfig: { includeThoughts: true } } }); console.log(response.text);` RESTUse curl to send a request: `curl -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [ { \"role\": \"user\", \"parts\": { \"text\": \"Find me a flight from SF to Hawaii on Jun 30th, coming back on Jul 6th. Start by navigating directly to flights.google.com\" } } ], \"tools\": [ { \"computer_use\": { \"environment\": \"ENVIRONMENT_BROWSER\", \"enable_prompt_injection_detection\": true } } ] }'` Gemini 2.5 (Legacy) Python`from google import genai from google.genai import types from google.genai.types import Content, Part client = genai.Client() # Specify predefined functions to exclude (optional) excluded_functions = [\"drag_and_drop\"] generate_content_config = genai.types.GenerateContentConfig( tools=[ types.Tool( computer_use=types.ComputerUse( environment=types.Environment.ENVIRONMENT_BROWSER, excluded_predefined_functions=excluded_functions ) ), ], ) contents=[ Content( role=\"user\", parts=[ Part(text=\"Search for highly rated smart fridges on Google Shopping.\"), ], ) ] response = client.models.generate_content( model='gemini-2.5-computer-use-preview-10-2025', contents=contents, config=generate_content_config, ) print(response)` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); // Specify predefined functions to exclude (optional) const excludedFunctions = [\"drag_and_drop\"]; const response = await ai.models.generateContent({ model: 'gemini-2.5-computer-use-preview-10-2025', contents: [ { role: 'user', parts: [{ text: \"Search for highly rated smart fridges on Google Shopping.\" }] } ], config: { tools: [{ computerUse: { environment: \"ENVIRONMENT_BROWSER\", excluded_predefined_functions: excludedFunctions } }] } }); console.log(response);` 2. Receive the model response The response model suggests a function call. For **Gemini 3.x models**, the\nresponse contains a tailored reasoning intent alongside coordinates. The\nfollowing shows examples of both responses: Gemini 3.x`{ \"function_call\": { \"name\": \"click\", \"args\": { \"x\": 450, \"y\": 120, \"intent\": \"Click the search box to type the destination.\" } } }` Gemini 2.5 (Legacy)`{ \"content\": { \"parts\": [ { \"text\": \"I will type the search query into the search bar.\" }, { \"function_call\": { \"name\": \"type_text_at\", \"args\": { \"x\": 371, \"y\": 470, \"text\": \"highly rated smart fridges\", \"press_enter\": true } } } ] } }` 3. Execute the received actions Your application code needs to parse the model response, execute the actions,\nand collect the results. The code below handles both legacy tool commands (`click_at`, `type_text_at`) and modern streamlined commands (`click`, `type`). Python`from typing import Any, List, Tuple import time def denormalize_x(x: int, screen_width: int) -> int: \"\"\"Convert normalized x coordinate (0-1000) to actual pixel coordinate.\"\"\" return int(x / 1000 * screen_width) def denormalize_y(y: int, screen_height: int) -> int: \"\"\"Convert normalized y coordinate (0-1000) to actual pixel coordinate.\"\"\" return int(y / 1000 * screen_height) def execute_function_calls(interaction, page, screen_width, screen_height): results = [] function_calls = [] # Parse content parts (Handling legacy and Gemini 3 response structures) parts = candidate.content.parts if hasattr(candidate, 'content') else [] if not parts and hasattr(candidate, 'function_calls'): function_calls = candidate.function_calls else: for part in parts: if part.function_call: function_calls.append(part.function_call) for function_call in function_calls: action_result = {} fname = function_call.name args = function_call.args print(f\" -> Executing: {fname} (Intent: {args.get('intent', 'N/A')})\") try: if fname in (\"open_web_browser\", \"open_app\"): pass # Handled / already open elif fname in (\"click\", \"click_at\", \"double_click\", \"triple_click\", \"middle_click\", \"right_click\", \"move\", \"long_press\"): actual_x = denormalize_x(args[\"x\"], screen_width) actual_y = denormalize_y(args[\"y\"], screen_height) if fname in (\"click\", \"click_at\"): page.mouse.click(actual_x, actual_y) elif fname == \"double_click\": page.mouse.dblclick(actual_x, actual_y) elif fname == \"right_click\": page.mouse.click(actual_x, actual_y, button=\"right\") elif fname == \"middle_click\": page.mouse.click(actual_x, actual_y, button=\"middle\") elif fname == \"move\": page.mouse.move(actual_x, actual_y) elif fname in (\"type\", \"type_text_at\"): actual_x = denormalize_x(args[\"x\"], screen_width) if \"x\" in args else None actual_y = denormalize_y(args[\"y\"], screen_height) if \"y\" in args else None text = args[\"text\"] press_enter = args.get(\"press_enter\", False) if actual_x is not None and actual_y is not None: page.mouse.click(actual_x, actual_y) # Clear field first page.keyboard.press(\"Meta+A\") page.keyboard.press(\"Backspace\") page.keyboard.type(text) if press_enter: page.keyboard.press(\"Enter\") elif fname == \"navigate\": page.goto(args[\"url\"]) elif fname == \"go_back\": page.go_back() elif fname == \"go_forward\": page.go_forward() elif fname == \"wait\": time.sleep(args.get(\"seconds\", 1)) else: print(f\"Warning: Custom or unhandled function {fname}\") page.wait_for_load_state(timeout=5000) time.sleep(1) except Exception as e: print(f\"Error executing {fname}: {e}\") action_result = {\"error\": str(e)} results.append((fname, function_call.id, action_result)) return results` JavaScript`function denormalizeX(x, screenWidth) { // Convert normalized x coordinate (0-1000) to actual pixel coordinate. return Math.floor((x / 1000) * screenWidth); } function denormalizeY(y, screenHeight) { // Convert normalized y coordinate (0-1000) to actual pixel coordinate. return Math.floor((y / 1000) * screenHeight); } async function executeFunctionCalls(candidate, page, screenWidth, screenHeight) { const results = []; let functionCalls = []; // Parse function calls from candidate response const parts = candidate.content?.parts || []; if (parts.length === 0 && candidate.functionCalls) { functionCalls = candidate.functionCalls; } else { for (const part of parts) { if (part.functionCall) { functionCalls.push(part.functionCall); } } } for (const functionCall of functionCalls) { const actionResult = {}; const fname = functionCall.name; const args = functionCall.args; console.log(` -> Executing: ${fname} (Intent: ${args.intent || 'N/A'})`); try { if (fname === \"open_web_browser\" || fname === \"open_app\") { // Handled / already open } else if ([\"click\", \"click_at\", \"double_click\", \"triple_click\", \"middle_click\", \"right_click\", \"move\", \"long_press\"].includes(fname)) { const actualX = denormalizeX(args.x, screenWidth); const actualY = denormalizeY(args.y, screenHeight); if (fname === \"click\" || fname === \"click_at\") { await page.mouse.click(actualX, actualY); } else if (fname === \"double_click\") { await page.mouse.dblclick(actualX, actualY); } else if (fname === \"right_click\") { await page.mouse.click(actualX, actualY, { button: \"right\" }); } else if (fname === \"middle_click\") { await page.mouse.click(actualX, actualY, { button: \"middle\" }); } else if (fname === \"move\") { await page.mouse.move(actualX, actualY); } } else if (fname === \"type\" || fname === \"type_text_at\") { const actualX = args.x !== undefined ? denormalizeX(args.x, screenWidth) : null; const actualY = args.y !== undefined ? denormalizeY(args.y, screenHeight) : null; const text = args.text; const pressEnter = args.press_enter || false; if (actualX !== null && actualY !== null) { await page.mouse.click(actualX, actualY); } // Clear field first await page.keyboard.press(\"Meta+A\"); await page.keyboard.press(\"Backspace\"); await page.keyboard.type(text); if (pressEnter) { await page.keyboard.press(\"Enter\"); } } else if (fname === \"navigate\") { await page.goto(args.url); } else if (fname === \"go_back\") { await page.goBack(); } else if (fname === \"go_forward\") { await page.goForward(); } else if (fname === \"wait\") { await new Promise(resolve => setTimeout(resolve, (args.seconds || 1) * 1000)); } else { console.log(`Warning: Custom or unhandled function ${fname}`); } await page.waitForLoadState('load', { timeout: 5000 }).catch(() => {}); await new Promise(resolve => setTimeout(resolve, 1000)); } catch (e) { console.log(`Error executing ${fname}: ${e}`); actionResult.error = e.message; } results.push([fname, functionCall.id, actionResult]); } return results; }` 4. Capture the new environment state Capture a screen representation and return it to the model. Python`def get_function_responses(page, results): screenshot_bytes = page.screenshot(type=\"png\") current_url = page.url function_responses = [] for name, call_id, result in results: function_responses.append({ \"type\": \"function_result\", \"name\": name, \"call_id\": call_id, \"result\": [ { \"type\": \"text\", \"text\": json.dumps({\"url\": current_url, **result}) }, { \"type\": \"image\", \"data\": base64.b64encode(screenshot_bytes).decode(\"utf-8\"), \"mime_type\": \"image/png\" } ] }) return function_responses` JavaScript`async function getFunctionResponses(page, results) { const screenshotBuffer = await page.screenshot({ type: 'png' }); const screenshotBase64 = screenshotBuffer.toString('base64'); const currentUrl = page.url(); const functionResponses = []; for (const [name, callId, result] of results) { functionResponses.push({ type: \"function_result\", name: name, call_id: callId, result: [ { type: \"text\", text: JSON.stringify({ url: currentUrl, ...result }) }, { type: \"image\", data: screenshotBase64, mime_type: \"image/png\" } ] }); } return functionResponses; }` Once you have defined how to capture and format the environment state, you can combine all these steps into a continuous execution loop. Build an agent loop To enable multi-step interactions, combine the four steps from the How to implement Computer Use section into a single loop. This loop continues requesting actions and feeding the results back to the model until the task is complete. Remember to manage the conversation history correctly by appending both the model responses and your function responses to the history at each step. Python`import time from typing import Any, List, Tuple from playwright.sync_api import sync_playwright from google import genai from google.genai import types client = genai.Client() SCREEN_WIDTH = 1440 SCREEN_HEIGHT = 900 print(\"Initializing browser...\") playwright = sync_playwright().start() browser = playwright.chromium.launch(headless=False) context = browser.new_context(viewport={\"width\": SCREEN_WIDTH, \"height\": SCREEN_HEIGHT}) page = context.new_page() # Paste helper functions execute_function_calls and get_function_responses here try: page.goto(\"https://ai.google.dev/gemini-api/docs\") config = types.GenerateContentConfig( tools=[types.Tool(computer_use=types.ComputerUse( environment=types.Environment.ENVIRONMENT_BROWSER, enable_prompt_injection_detection=True ))], thinking_config=types.ThinkingConfig(include_thoughts=True), ) initial_screenshot = page.screenshot(type=\"png\") USER_PROMPT = \"Go to ai.google.dev/gemini-api/docs and search for pricing.\" print(f\"Goal: {USER_PROMPT}\") contents = [ types.Content(role=\"user\", parts=[ types.Part(text=USER_PROMPT), types.Part.from_bytes(data=initial_screenshot, mime_type='image/png') ]) ] # Agent Loop turn_limit = 5 for i in range(turn_limit): print(f\"\\n--- Turn {i+1} ---\") print(\"Thinking...\") response = client.models.generate_content( model='gemini-3.8-flash', contents=contents, config=config, ) candidate = response.candidates[0] contents.append(candidate.content) has_function_calls = any(part.function_call for part in candidate.content.parts) if not has_function_calls: text_response = \" \".join( part.text for part in candidate.content.parts if hasattr(part, 'text') ) print(\"Agent finished:\", text_response) break print(\"Executing actions...\") results = execute_function_calls(candidate, page, SCREEN_WIDTH, SCREEN_HEIGHT) print(\"Capturing state...\") function_responses = get_function_responses(page, results) contents.append( types.Content(role=\"user\", parts=[types.Part(function_response=fr) for fr in function_responses]) ) finally: print(\"Closing browser...\") browser.close() playwright.stop()` JavaScript`import { chromium } from 'playwright'; import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); // Constants for screen dimensions const SCREEN_WIDTH = 1440; const SCREEN_HEIGHT = 900; console.log(\"Initializing browser...\"); const browser = await chromium.launch({ headless: false }); const context = await browser.newContext({ viewport: { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } }); const page = await context.newPage(); // Define helper functions. Copy/paste from steps 3 and 4: // function denormalizeX(...) // function denormalizeY(...) // async function executeFunctionCalls(...) // async function getFunctionResponses(...) try { await page.goto(\"https://ai.google.dev/gemini-api/docs\"); const config = { tools: [{ computerUse: { environment: \"ENVIRONMENT_BROWSER\", enable_prompt_injection_detection: true } }], thinkingConfig: { includeThoughts: true } }; const initialScreenshotBuffer = await page.screenshot({ type: 'png' }); const initialScreenshotBase64 = initialScreenshotBuffer.toString('base64'); const USER_PROMPT = \"Go to ai.google.dev/gemini-api/docs and search for pricing.\"; console.log(`Goal: ${USER_PROMPT}`); const contents = [ { role: \"user\", parts: [ { text: USER_PROMPT }, { inlineData: { data: initialScreenshotBase64, mimeType: \"image/png\" } } ] } ]; // Agent Loop const turnLimit = 5; for (let i = 0; i < turnLimit; i++) { console.log(`\\n--- Turn ${i + 1} ---`); console.log(\"Thinking...\"); const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: contents, config: config }); const candidate = response.candidates[0]; contents.push(candidate.content); const hasFunctionCalls = candidate.content.parts.some(part => part.functionCall); if (!hasFunctionCalls) { const textResponse = candidate.content.parts .filter(part => part.text) .map(part => part.text) .join(\" \"); console.log(\"Agent finished:\", textResponse); break; } console.log(\"Executing actions...\"); const results = await executeFunctionCalls(candidate, page, SCREEN_WIDTH, SCREEN_HEIGHT); console.log(\"Capturing state...\"); const functionResponses = await getFunctionResponses(page, results); contents.push({ role: \"user\", parts: functionResponses.map(fr => ({ ...fr })) }); } } finally { console.log(\"Closing browser...\"); await browser.close(); }` Supported environments (Gemini 3.x) Gemini 3.x models support three environments specified in the `computer_use` configurations: Browser environment (`ENVIRONMENT_BROWSER`) Action actions under browser tool: Command name Description Arguments (in function call) **click** Left clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **double_click** Double clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **triple_click** Triple clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **middle_click** Middle clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **right_click** Right clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **mouse_down** Presses and holds the mouse button at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **mouse_up** Releases the mouse button at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **move** Moves the cursor to the specified position. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **type** Types text. `text`: str\n`press_enter`: bool (Optional, default `false`)\n`intent`: str **drag_and_drop** Drags an item from the start coordinate to the end coordinate. `start_y`: int (0-999)\n`start_x`: int (0-999)\n`end_y`: int (0-999)\n`end_x`: int (0-999)\n`intent`: str **wait** Pauses execution for a specified number of seconds. `seconds`: int (Optional, default `1`)\n`intent`: str **press_key** Presses the specified key and releases it. `key`: str\n`intent`: str **key_down** Presses and holds the specified key. `key`: str\n`intent`: str **key_up** Releases the specified key. `key`: str\n`intent`: str **hotkey** Presses the specified key combination. `keys`: `List[str]`\n`intent`: `str` **take_screenshot** Returns a screenshot of the current screen. `intent`: str **scroll** Scrolls up, down, left, or right at a coordinate by a pixel distance. `y`: int (0-999)\n`x`: int (0-999)\n`direction`: str (`\"up\"`, `\"down\"`, `\"left\"`, `\"right\"`)\n`magnitude_in_pixels`: int (0-999, Optional, default `300`)\n`intent`: str **go_back** Navigates back to the previous webpage in the browser history. `intent`: str **navigate** Navigates directly to a specified URL. `url`: str\n`intent`: str **go_forward** Navigates forward to the next webpage in the browser history. `intent`: str Mobile environment (`ENVIRONMENT_MOBILE`) Android-optimized environment actions: Command name Description Arguments (in function call) **open_app** Opens an application by its name. `app_name`: str\n`intent`: str **click** Left clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **list_apps** Lists available applications on the device, returning their names and package names. `intent`: str **wait** Pauses execution for a specified number of seconds. `seconds`: int (Optional, default `1`)\n`intent`: str **go_back** Navigates back to the previous screen or webpage. `intent`: str **type** Types text. `text`: str\n`press_enter`: bool (Optional, default `false`)\n`intent`: str **drag_and_drop** Drags an item from the start coordinate to the end coordinate. `start_y`: int (0-999)\n`start_x`: int (0-999)\n`end_y`: int (0-999)\n`end_x`: int (0-999)\n`intent`: str **long_press** Performs a long press at a coordinate on the screen. `y`: int (0-999)\n`x`: int (0-999)\n`seconds`: int (Optional, default `2`)\n`intent`: str **press_key** Presses the specified key and releases it. `key`: str\n`intent`: str **take_screenshot** Returns a screenshot of the current screen. `intent`: str Desktop environment (`ENVIRONMENT_DESKTOP`) Desktop environments OS-level cursor commands: Command name Description Arguments (in function call) **click** Left clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **double_click** Double clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **triple_click** Triple clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **middle_click** Middle clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **right_click** Right clicks at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **mouse_down** Presses and holds the mouse button at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **mouse_up** Releases the mouse button at the coordinate. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **move** Moves the cursor to the specified position. `y`: int (0-999)\n`x`: int (0-999)\n`intent`: str **type** Types text. `text`: str\n`press_enter`: bool (Optional, default `false`)\n`intent`: str **drag_and_drop** Drags an item from the start coordinate to the end coordinate. `start_y`: int (0-999)\n`start_x`: int (0-999)\n`end_y`: int (0-999)\n`end_x`: int (0-999)\n`intent`: str **wait** Pauses execution for a specified number of seconds. `seconds`: int (Optional, default `1`)\n`intent`: str **press_key** Presses the specified key and releases it. `key`: str\n`intent`: str **key_down** Presses and holds the specified key. `key`: str\n`intent`: str **key_up** Releases the specified key. `key`: str\n`intent`: str **hotkey** Presses the specified key combination. `keys`: `List[str]`\n`intent`: `str` **take_screenshot** Returns a screenshot of the current screen. `intent`: str **scroll** Scrolls up, down, left, or right at a coordinate by a pixel distance. `y`: int (0-999)\n`x`: int (0-999)\n`direction`: str (`\"up\"`, `\"down\"`, `\"left\"`, `\"right\"`)\n`magnitude_in_pixels`: int (0-999, Optional, default `300`)\n`intent`: str Legacy Supported UI actions (Gemini 2.5) For legacy models (`gemini-2.5-computer-use-preview-10-2025`), the following actions are supported: Command name Description Arguments (in function call) Example function call **open_web_browser** Opens the web browser. None `{\"name\": \"open_web_browser\", \"args\": {}}` **wait_5_seconds** Pauses execution for 5 seconds. None `{\"name\": \"wait_5_seconds\", \"args\": {}}` **go_back** Navigates to the previous page in history. None `{\"name\": \"go_back\", \"args\": {}}` **go_forward** Navigates to the next page in history. None `{\"name\": \"go_forward\", \"args\": {}}` **search** Navigates to default search engine. None `{\"name\": \"search\", \"args\": {}}` **navigate** Navigates the browser directly to the specified URL. `url`: str `{\"name\": \"navigate\", \"args\": {\"url\": \"https://www.wikipedia.org\"}}` **click_at** Clicks at a specific coordinate. `y`: int (0-999), `x`: int (0-999) `{\"name\": \"click_at\", \"args\": {\"y\": 300, \"x\": 500}}` **hover_at** Hovers mouse at a specific coordinate. `y`: int (0-999), `x`: int (0-999) `{\"name\": \"hover_at\", \"args\": {\"y\": 150, \"x\": 250}}` **type_text_at** Types text at a coordinate. `y`: int (0-999), `x`: int (0-999), `text`: str, `press_enter`: bool (Optional, default True), `clear_before_typing`: bool (Optional, default True) `{\"name\": \"type_text_at\", \"args\": {\"y\": 250, \"x\": 400, \"text\": \"search\", \"press_enter\": false}}` **key_combination** Press keys or combinations. `keys`: str `{\"name\": \"key_combination\", \"args\": {\"keys\": \"Control+A\"}}` **scroll_document** Scrolls the entire webpage. `direction`: str `{\"name\": \"scroll_document\", \"args\": {\"direction\": \"down\"}}` **scroll_at** Scrolls at coordinate (x,y). `y`: int, `x`: int, `direction`: str, `magnitude`: int (Optional, default 800) `{\"name\": \"scroll_at\", \"args\": {\"y\": 500, \"x\": 500, \"direction\": \"down\"}}` **drag_and_drop** Drags between two coordinates. `y`: int, `x`: int, `destination_y`: int, `destination_x`: int `{\"name\": \"drag_and_drop\", \"args\": {\"y\": 100, \"destination_y\": 500, \"destination_x\": 500, \"x\": 100}}` Custom user-defined functions You can extend the functionality of the model by including custom user-defined functions. For example, in human-in-the-loop (HITL) scenarios you can exclude default predefined actions and register custom actions. Gemini 3.x Custom Tooling PythonExclude standard predefined browser actions (such as `click`) and register a custom `yield_to_user` tool: `from google import genai from google.genai import types client = genai.Client() yield_to_user_tool = types.FunctionDeclaration( name=\"yield_to_user\", description=\"Yields control back to the user for assistance or verification when an automated action is unsafe or ambiguous.\", parameters=types.Schema( type=\"OBJECT\", properties={ \"reason\": types.Schema( type=\"STRING\", description=\"The reason why the agent is yielding control to the human.\" ) }, required=[\"reason\"] ) ) response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Click the submit button. If you need a second factor authentication code, ask me.\", config=types.GenerateContentConfig( tools=[ types.Tool( computer_use=types.ComputerUse( environment=\"ENVIRONMENT_MOBILE\", excluded_predefined_functions=[\"click\"] ) ), yield_to_user_tool ] ) )` Gemini 2.5 (Legacy) Custom Tooling Python`from typing import Optional, Dict, Any from google import genai from google.genai import types client = genai.Client() # Define custom tools here custom_functions = [...] # Describe parameters as FunctionDeclaration object def make_generate_content_config(): excluded_functions = [\"open_web_browser\", \"wait_5_seconds\", \"go_back\", \"go_forward\", \"search\", \"navigate\", \"hover_at\", \"scroll_document\", \"key_combination\", \"drag_and_drop\"] generate_content_config = types.GenerateContentConfig( tools=[ types.Tool( computer_use=types.ComputerUse( environment=types.Environment.ENVIRONMENT_BROWSER, excluded_predefined_functions=excluded_functions ) ), types.Tool(function_declarations=custom_functions) ] ) return generate_content_config` Managing thinking levels (Gemini 3.x) For computer use agents, you can configure different thinking levels to balance action quality and execution speed. Lower thinking levels generally achieve a good balance for standard automation tasks. Safety and security Configuring safety policies (Gemini 3.x) Gemini 3.x models include built-in safety service categories that automatically determine if user confirmation is required. Safety policy category Description `FINANCIAL_TRANSACTIONS` Blocks or triggers confirmation for actions involving payments, retail checkout, or regulated goods. `SENSITIVE_DATA_MODIFICATION` Protects health, financial, or government records from unauthorized modification. `COMMUNICATION_TOOL` Restricts the agent from autonomously sending emails, chat messages, or drafts. `ACCOUNT_CREATION` Restricts the agent from autonomously registering new accounts on websites. `DATA_MODIFICATION` Regulates overall file system modifications, data sharing, and storage deletion. `USER_CONSENT_MANAGEMENT` Requires user takeover for cookie consent banners and privacy prompts. `LEGAL_TERMS_AND_AGREEMENTS` Prevents the model from autonomously accepting Terms of Service or legally binding contracts. Safety overrides You can override select policies by passing overrides: Python`from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Clean up the local folder by archiving old logs.\", config=types.GenerateContentConfig( tools=[ types.Tool( computer_use=types.ComputerUse( environment=types.Environment.ENVIRONMENT_DESKTOP, disabled_safety_policies=[ types.SafetyPolicy.DATA_MODIFICATION ] ) ) ] ) )` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: \"Clean up the local folder by archiving old logs.\", config: { tools: [{ computerUse: { environment: \"ENVIRONMENT_DESKTOP\", disabledSafetyPolicies: [ \"DATA_MODIFICATION\" ] } }] } });` Prompt injection detection (Gemini 3.x) Computer Use for Gemini 3.5 Flash or later supports an advanced safety\nmechanism to detect prompt injection attacks. When enabled, this feature\nchecks whether an included screenshot contains hidden adversarial\ninstructions (for example, \"Ignore previous commands\") and blocks\nexecution when detected. Prompt injection detection is an opt-in feature. The default is `false`. The following examples demonstrate how to enable prompt injection detection\nin your Computer Use tool configuration: Python`from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model=\"gemini-3.5-flash\", contents=\"Search for flight deals and summarize top results.\", config=types.GenerateContentConfig( tools=[ types.Tool( computer_use=types.ComputerUse( environment=\"ENVIRONMENT_DESKTOP\", enable_prompt_injection_detection=True, ) ) ] ), )` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const response = await ai.models.generateContent({ model: \"gemini-3.5-flash\", contents: \"Search for flight deals and summarize top results.\", config: { tools: [{ computerUse: { environment: \"ENVIRONMENT_DESKTOP\", enablePromptInjectionDetection: true, } }] } });` cURL`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent?key=${GEMINI_API_KEY}\" \\\n-H 'Content-Type: application/json' \\\n-d '{ \"contents\": [{ \"parts\": [{\"text\": \"Search for flight deals and summarize top results.\"}] }], \"tools\": [{ \"computer_use\": { \"environment\": \"ENVIRONMENT_DESKTOP\", \"enable_prompt_injection_detection\": true } }] }'` Acknowledge safety decision The response may include a `safety_decision` parameter in the function call arguments: `{ \"function_call\": { \"name\": \"click_at\", \"args\": { \"x\": 60, \"y\": 100, \"safety_decision\": { \"explanation\": \"Must check check-box\", \"decision\": \"require_confirmation\" } } } }` If the `safety_decision` is `require_confirmation`, prompt the end user. If the\nuser confirms, set `safety_acknowledgement` in `FunctionResponse`. Python`def get_safety_confirmation(safety_decision): # Prompt user for confirmation print(f\"Safety confirmation required: {safety_decision.get('explanation', '')}\") return \"CONTINUE\" # Or TERMINATE # Inside execute_function_calls, check for safety_decision: if 'safety_decision' in function_call.args: decision = get_safety_confirmation(function_call.args['safety_decision']) if decision == \"TERMINATE\": break # Include safety_acknowledgement inside the action result action_result[\"safety_acknowledgement\"] = True` Safety best practices Computer Use presents unique security and operational risks, as a model acting\non a user's behalf might encounter untrusted content on screens or make errors\nin executing actions. Implement the following best practices to protect user\ndata and systems: **Human-in-the-Loop (HITL):** **Enforce user confirmation:** When the safety response indicates\n`require_confirmation` (or legacy safety decision requires it), prompt the user for approval. **Provide custom safety instructions:** Implement a custom system instruction to define and enforce your own safety boundaries. For example: Python`from google import genai from google.genai import types system_instruction = \"\"\" ## **RULE 1: Seek User Confirmation (USER_CONFIRMATION)** This is your first and most important check. If the next required action falls into any of the following categories, you MUST stop immediately, and seek the user's explicit permission. **Procedure for Seeking Confirmation:** * **For Consequential Actions:** Perform all preparatory steps (e.g., navigating, filling out forms, typing a message). You will ask for confirmation **AFTER** all necessary information is entered on the screen, but **BEFORE** you perform the final, irreversible action (e.g., before clicking \"Send\", \"Submit\", \"Confirm Purchase\", \"Share\"). * **For Prohibited Actions:** If the action is strictly forbidden (e.g., accepting legal terms, solving a CAPTCHA), you must first inform the user about the required action and ask for their confirmation to proceed. **USER_CONFIRMATION Categories:** * **Consent and Agreements:** You are FORBIDDEN from accepting, selecting, or agreeing to any of the following on the user's behalf. You must ask the user to confirm before performing these actions. * Terms of Service * Privacy Policies * Cookie consent banners * End User License Agreements (EULAs) * Any other legally significant contracts or agreements. * **Robot Detection:** You MUST NEVER attempt to solve or bypass the following. You must ask the user to confirm before performing these actions. * CAPTCHAs (of any kind) * Any other anti-robot or human-verification mechanisms, even if you are capable. * **Financial Transactions:** * Completing any purchase. * Managing or moving money (e.g., transfers, payments). * Purchasing regulated goods or participating in gambling. * **Sending Communications:** * Sending emails. * Sending messages on any platform (e.g., social media, chat apps). * Posting content on social media or forums. * **Accessing or Modifying Sensitive Information:** * Health, financial, or government records (e.g., medical history, tax forms, passport status). * Revealing or modifying sensitive personal identifiers (e.g., SSN, bank account number, credit card number). * **User Data Management:** * Accessing, downloading, or saving files from the web. * Sharing or sending files/data to any third party. * Transferring user data between systems. * **Browser Data Usage:** * Accessing or managing Chrome browsing history, bookmarks, autofill data, or saved passwords. * **Security and Identity:** * Logging into any user account. * Any action that involves misrepresentation or impersonation (e.g., creating a fan account, posting as someone else). * **Insurmountable Obstacles:** If you are technically unable to interact with a user interface element or are stuck in a loop you cannot resolve, ask the user to take over. --- ## **RULE 2: Default Behavior (ACTUATE)** If an action does **NOT** fall under the conditions for `USER_CONFIRMATION`, your default behavior is to **Actuate**. **Actuation Means:** You MUST proactively perform all necessary steps to move the user's request forward. Continue to actuate until you either complete the non-consequential task or encounter a condition defined in Rule 1. * **Example 1:** If asked to send money, you will navigate to the payment portal, enter the recipient's details, and enter the amount. You will then **STOP** as per Rule 1 and ask for confirmation before clicking the final \"Send\" button. * **Example 2:** If asked to post a message, you will navigate to the site, open the post composition window, and write the full message. You will then **STOP** as per Rule 1 and ask for confirmation before clicking the final \"Post\" button. After the user has confirmed, remember to get the user's latest screen before continuing to perform actions. # Final Response Guidelines: Write final response to the user in the following cases: - User confirmation - When the task is complete or you have enough information to respond to the user \"\"\" client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Prepare a draft but do not send.\", config=types.GenerateContentConfig( system_instruction=system_instruction, tools=[types.Tool(computer_use=types.ComputerUse(environment=\"ENVIRONMENT_BROWSER\"))] ) )` JavaScript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI(); const systemInstruction = ` ## **RULE 1: Seek User Confirmation (USER_CONFIRMATION)** This is your first and most important check. If the next required action falls into any of the following categories, you MUST stop immediately, and seek the user's explicit permission. **Procedure for Seeking Confirmation:** * **For Consequential Actions:** Perform all preparatory steps (e.g., navigating, filling out forms, typing a message). You will ask for confirmation **AFTER** all necessary information is entered on the screen, but **BEFORE** you perform the final, irreversible action (e.g., before clicking \"Send\", \"Submit\", \"Confirm Purchase\", \"Share\"). * **For Prohibited Actions:** If the action is strictly forbidden (e.g., accepting legal terms, solving a CAPTCHA), you must first inform the user about the required action and ask for their confirmation to proceed. **USER_CONFIRMATION Categories:** * **Consent and Agreements:** You are FORBIDDEN from accepting, selecting, or agreeing to any of the following on the user's behalf. You must ask the user to confirm before performing these actions. * Terms of Service * Privacy Policies * Cookie consent banners * End User License Agreements (EULAs) * Any other legally significant contracts or agreements. * **Robot Detection:** You MUST NEVER attempt to solve or bypass the following. You must ask the user to confirm before performing these actions. * CAPTCHAs (of any kind) * Any other anti-robot or human-verification mechanisms, even if you are capable. * **Financial Transactions:** * Compleying any purchase. * Managing or moving money (e.g., transfers, payments). * Purchasing regulated goods or participating in gambling. * **Sending Communications:** * Sending emails. * Sending messages on any platform (e.g., social media, chat apps). * Posting content on social media or forums. * **Accessing or Modifying Sensitive Information:** * Health, financial, or government records (e.g., medical history, tax forms, passport status). * Revealing or modifying sensitive personal identifiers (e.g., SSN, bank account number, credit card number). * **User Data Management:** * Accessing, downloading, or saving files from the web. * Sharing or sending files/data to any third party. * Transferring user data between systems. * **Browser Data Usage:** * Accessing or managing Chrome browsing history, bookmarks, autofill data, or saved passwords. * **Security and Identity:** * Logging into any user account. * Any action that involves misrepresentation or impersonation (e.g., creating a fan account, posting as someone else). * **Insurmountable Obstacles:** If you are technically unable to interact with a user interface element or are stuck in a loop you cannot resolve, ask the user to take over. --- ## **RULE 2: Default Behavior (ACTUATE)** If an action does **NOT** fall under the conditions for \\`USER_CONFIRMATION\\`, your default behavior is to **Actuate**. **Actuation Means:** You MUST proactively perform all necessary steps to move the user's request forward. Continue to actuate until you either complete the non-consequential task or encounter a condition defined in Rule 1. * **Example 1:** If asked to send money, you will navigate to the payment portal, enter the recipient's details, and enter the amount. You will then **STOP** as per Rule 1 and ask for confirmation before clicking the final \"Send\" button. * **Example 2:** If asked to post a message, you will navigate to the site, open the post composition window, and write the full message. You will then **STOP** as per Rule 1 and ask for confirmation before clicking the final \"Post\" button. After the user has confirmed, remember to get the user's latest screen before continuing to perform actions. # Final Response Guidelines: Write final response to the user in the following cases: - User confirmation - When the task is complete or you have enough information to respond to the user `; const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: \"Prepare a draft but do not send.\", config: { systemInstruction: systemInstruction, tools: [{ computerUse: { environment: \"ENVIRONMENT_BROWSER\" } }] } });` **Secure execution environment:** Run your agent in a secure, sandboxed\nenvironment to limit its potential impact. This can be a sandboxed virtual\nmachine (VM), a container (e.g., Docker), or a dedicated browser profile\nwith limited permissions. See the\n[GitHub reference implementation](https://github.com/google/computer-use-preview/)\nfor sandbox setup guidance using Docker. **Input sanitization:** Sanitize all user-generated text in prompts to\nmitigate the risk of unintended instructions or prompt injection. This is a\nhelpful layer of security, but not a replacement for a secure execution\nenvironment. **Content guardrails:** Use guardrails and content safety APIs to evaluate\nuser inputs, tool inputs and outputs, and the agent's responses for appropriateness,\nprompt injection, and jailbreak detection. **Allowlists and blocklists:** Implement filtering mechanisms to control\nwhere the model can navigate and what it can do. A blocklist of prohibited\nwebsites is a good starting point, while a more restrictive allowlist is\neven more secure. **Observability and logging:** Maintain detailed logs for debugging,\nauditing, and incident response. Your client should log prompts,\nscreenshots, model-suggested actions (`function_call`), safety responses, and\nall actions ultimately executed by the client. **Environment management:** Ensure the GUI environment is consistent.\nUnexpected pop-ups, notifications, or changes in layout can confuse the\nmodel. Start from a known, clean state for each new task if possible. Model versions You can use Computer Use with the following models: [**Gemini 3.8 Flash**](/gemini-api/docs/models/gemini-3.8-flash) (`gemini-3.8-flash`): The recommended model for\ncomputer use, featuring high-accuracy UI interaction and reliable tool calling. [**Gemini 3.7 Flash**](/gemini-api/docs/models/gemini-3.7-flash) (`gemini-3.7-flash`): Previous stable model for\ncomputer use, featuring streamlined actions with intents, support for\nbrowser, mobile, and desktop environments, configurable safety policies, and\nprompt injection detection. [**Gemini 3.5 Flash-Lite**](/gemini-api/docs/models/gemini-3.5-flash-lite) (`gemini-3.5-flash-lite`): A low-latency, cost-effective model supporting\ncomputer use. [**Gemini 3.5 Flash**](/gemini-api/docs/models/gemini-3.5-flash) (`gemini-3.5-flash`): Previous stable model supporting\ncomputer use. [**Gemini 3 Flash Preview**](/gemini-api/docs/models/gemini-3-flash-preview) (`gemini-3-flash-preview`): Preview model\nsupporting computer use. [**Gemini 2.5 (Legacy Preview)**](/gemini-api/docs/models/gemini-2.5-computer-use-preview-10-2025) (`gemini-2.5-computer-use-preview-10-2025`): Legacy preview model optimized for browser-based computer use. What's next Experiment with Computer Use in the [Browserbase demo environment](http://gemini.browserbase.com). Check out the [Reference implementation](https://github.com/google/computer-use-preview) for example code. Learn about other Gemini API tools:\n [Function calling](/gemini-api/docs/function-calling) [Grounding with Google Search](/gemini-api/docs/grounding) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 47174, "slov": 6374, "odkazu": 146, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:54", "sha256": "51a6da231086e3633dfd6d6c4107949c6dda6740ddc1f6dbe6ecc04ce3f86ca5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://policies.google.com/terms/generative-ai/use-policy", "https://github.com/google/computer-use-preview/", "https://playwright.dev/", "http://gemini.browserbase.com/", "https://github.com/google/computer-use-preview", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/document-processing", "titulek": "Document understanding | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Document understanding", "popis": "Learn how to use the Gemini API to process documents like PDFs", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/document-processing", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Document understanding  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Learn how to use the Gemini API to process documents like PDFs", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/document-processing", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Document understanding"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Document understanding", "item": "https://ai.google.dev/gemini-api/docs/generate-content/document-processing"}]}], "drobecky": ["Generate Content API", "Document understanding"], "osnova": [{"uroven": 1, "text": "Document understanding"}, {"uroven": 2, "text": "Passing PDF data inline"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 2, "text": "Uploading PDFs using the Files API"}, {"uroven": 3, "text": "Large PDFs from URLs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Large PDFs stored locally"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Passing multiple PDFs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Technical details"}, {"uroven": 3, "text": "Gemini 3 models"}, {"uroven": 3, "text": "Document types"}, {"uroven": 3, "text": "Best practices"}, {"uroven": 2, "text": "What's next"}], "markdown": "Document understanding Gemini models can process documents in PDF format, using native\nvision to understand entire document contexts. This goes beyond\njust text extraction, allowing Gemini to: Analyze and interpret content, including text, images, diagrams,\ncharts, and tables, even in long documents up to 1000 pages. Extract information into [structured output](/gemini-api/docs/structured-output) formats. Summarize and answer questions based on both the visual and textual elements\nin a document. Transcribe document content (e.g. to HTML), preserving layouts and\nformatting, for use in downstream applications. You can also pass non-PDF documents in the same way but Gemini will see them\nas normal text which will eliminate context like charts or formatting. Passing PDF data inline You can pass PDF data inline in the request to `generateContent`. This is best\nsuited for smaller documents or temporary processing where you don't need to\nreference the file in subsequent requests. We recommend using the [Files API](/gemini-api/docs/document-processing#large-pdfs)\nfor larger documents that you need to refer to in multi-turn interactions to\nimprove request latency and reduce bandwidth usage. The following example shows you how to fetch a PDF from a URL and convert it to\nbytes for processing: Python`from google import genai from google.genai import types import httpx client = genai.Client() doc_url = \"https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf\" # Retrieve and encode the PDF byte doc_data = httpx.get(doc_url).content prompt = \"Summarize this document\" response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[ types.Part.from_bytes( data=doc_data, mime_type='application/pdf', ), prompt ] ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({ apiKey: \"GEMINI_API_KEY\" }); async function main() { const pdfResp = await fetch('https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf') .then((response) => response.arrayBuffer()); const contents = [ { text: \"Summarize this document\" }, { inlineData: { mimeType: 'application/pdf', data: Buffer.from(pdfResp).toString(\"base64\") } } ]; const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: contents }); console.log(response.text); } main();` 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, }) pdfResp, _ := http.Get(\"https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf\") var pdfBytes []byte if pdfResp != nil && pdfResp.Body != nil { pdfBytes, _ = io.ReadAll(pdfResp.Body) pdfResp.Body.Close() } parts := []*genai.Part{ &genai.Part{ InlineData: &genai.Blob{ MIMEType: \"application/pdf\", Data: pdfBytes, }, }, genai.NewPartFromText(\"Summarize this document\"), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` REST`DOC_URL=\"https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf\" PROMPT=\"Summarize this document\" DISPLAY_NAME=\"base64_pdf\" # Download the PDF\nwget -O \"${DISPLAY_NAME}.pdf\" \"${DOC_URL}\" # Check for FreeBSD base64 and set flags accordingly if [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then B64FLAGS=\"--input\" else B64FLAGS=\"-w0\" fi # Base64 encode the PDF ENCODED_PDF=$(base64 $B64FLAGS \"${DISPLAY_NAME}.pdf\") # Generate content using the base64 encoded PDF\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GOOGLE_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"inline_data\": {\"mime_type\": \"application/pdf\", \"data\": \"'\"$ENCODED_PDF\"'\"}}, {\"text\": \"'$PROMPT'\"} ] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json\n\n# Clean up the downloaded PDF\nrm \"${DISPLAY_NAME}.pdf\"` You can also read a PDF from a local file for processing: Python`from google import genai from google.genai import types import pathlib client = genai.Client() # Retrieve and encode the PDF byte filepath = pathlib.Path('file.pdf') prompt = \"Summarize this document\" response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[ types.Part.from_bytes( data=filepath.read_bytes(), mime_type='application/pdf', ), prompt]) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from 'fs'; const ai = new GoogleGenAI({ apiKey: \"GEMINI_API_KEY\" }); async function main() { const contents = [ { text: \"Summarize this document\" }, { inlineData: { mimeType: 'application/pdf', data: Buffer.from(fs.readFileSync(\"content/343019_3_art_0_py4t4l_convrt.pdf\")).toString(\"base64\") } } ]; const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: contents }); console.log(response.text); } main();` Go`package main import ( \"context\" \"fmt\" \"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, }) pdfBytes, _ := os.ReadFile(\"path/to/your/file.pdf\") parts := []*genai.Part{ &genai.Part{ InlineData: &genai.Blob{ MIMEType: \"application/pdf\", Data: pdfBytes, }, }, genai.NewPartFromText(\"Summarize this document\"), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` Uploading PDFs using the Files API We recommend you use Files API for larger files or when you intend to reuse a\ndocument across multiple requests. This improves request latency and reduces\nbandwidth usage by decoupling the file upload from the model requests. Large PDFs from URLs Use the File API to simplify uploading and processing large PDF files from URLs: Python`from google import genai from google.genai import types import io import httpx client = genai.Client() long_context_pdf_path = \"https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf\" # Retrieve and upload the PDF using the File API doc_io = io.BytesIO(httpx.get(long_context_pdf_path).content) sample_doc = client.files.upload( # You can pass a path or a file-like object here file=doc_io, config=dict( mime_type='application/pdf') ) prompt = \"Summarize this document\" response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[sample_doc, prompt]) print(response.text)` JavaScript`import { createPartFromUri, GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({ apiKey: \"GEMINI_API_KEY\" }); async function main() { const pdfBuffer = await fetch(\"https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf\") .then((response) => response.arrayBuffer()); const fileBlob = new Blob([pdfBuffer], { type: 'application/pdf' }); const file = await ai.files.upload({ file: fileBlob, config: { displayName: 'A17_FlightPlan.pdf', }, }); // Wait for the file to be processed. let getFile = await ai.files.get({ name: file.name }); while (getFile.state === 'PROCESSING') { getFile = await ai.files.get({ name: file.name }); console.log(`current file status: ${getFile.state}`); console.log('File is still processing, retrying in 5 seconds'); await new Promise((resolve) => { setTimeout(resolve, 5000); }); } if (file.state === 'FAILED') { throw new Error('File processing failed.'); } // Add the file to the contents. const content = [ 'Summarize this document', ]; if (file.uri && file.mimeType) { const fileContent = createPartFromUri(file.uri, file.mimeType); content.push(fileContent); } const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: content, }); console.log(response.text); } main();` 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.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` REST`PDF_PATH=\"https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf\" DISPLAY_NAME=\"A17_FlightPlan\" PROMPT=\"Summarize this document\" # Download the PDF from the provided URL\nwget -O \"${DISPLAY_NAME}.pdf\" \"${PDF_PATH}\" MIME_TYPE=$(file -b --mime-type \"${DISPLAY_NAME}.pdf\") NUM_BYTES=$(wc -c < \"${DISPLAY_NAME}.pdf\") echo \"MIME_TYPE: ${MIME_TYPE}\" echo \"NUM_BYTES: ${NUM_BYTES}\" tmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${DISPLAY_NAME}.pdf\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) echo \"file_uri: ${file_uri}\" # Now generate content using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GOOGLE_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"text\": \"'$PROMPT'\"}, {\"file_data\":{\"mime_type\": \"application/pdf\", \"file_uri\": '$file_uri'}}] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json\n\n# Clean up the downloaded PDF\nrm \"${DISPLAY_NAME}.pdf\"` Large PDFs stored locally Python`from google import genai from google.genai import types import pathlib import httpx client = genai.Client() # Retrieve and encode the PDF byte file_path = pathlib.Path('large_file.pdf') # Upload the PDF using the File API sample_file = client.files.upload( file=file_path, ) prompt=\"Summarize this document\" response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[sample_file, \"Summarize this document\"]) print(response.text)` JavaScript`import { createPartFromUri, GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({ apiKey: \"GEMINI_API_KEY\" }); async function main() { const file = await ai.files.upload({ file: 'path-to-localfile.pdf' config: { displayName: 'A17_FlightPlan.pdf', }, }); // Wait for the file to be processed. let getFile = await ai.files.get({ name: file.name }); while (getFile.state === 'PROCESSING') { getFile = await ai.files.get({ name: file.name }); console.log(`current file status: ${getFile.state}`); console.log('File is still processing, retrying in 5 seconds'); await new Promise((resolve) => { setTimeout(resolve, 5000); }); } if (file.state === 'FAILED') { throw new Error('File processing failed.'); } // Add the file to the contents. const content = [ 'Summarize this document', ]; if (file.uri && file.mimeType) { const fileContent = createPartFromUri(file.uri, file.mimeType); content.push(fileContent); } const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: content, }); console.log(response.text); } main();` Go`package main import ( \"context\" \"fmt\" \"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, }) localPdfPath := \"/path/to/file.pdf\" uploadConfig := &genai.UploadFileConfig{MIMEType: \"application/pdf\"} uploadedFile, _ := client.Files.UploadFromPath(ctx, localPdfPath, uploadConfig) promptParts := []*genai.Part{ genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), genai.NewPartFromText(\"Give me a summary of this pdf file.\"), } contents := []*genai.Content{ genai.NewContentFromParts(promptParts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` REST`NUM_BYTES=$(wc -c < \"${PDF_PATH}\") DISPLAY_NAME=TEXT\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"${BASE_URL}/upload/v1beta/files?key=${GEMINI_API_KEY}\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: application/pdf\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${PDF_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) echo file_uri=$file_uri # Now generate content using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GOOGLE_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"text\": \"Can you add a few more lines to this poem?\"}, {\"file_data\":{\"mime_type\": \"application/pdf\", \"file_uri\": '$file_uri'}}] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` You can verify the API successfully stored the uploaded file and get its\nmetadata by calling [`files.get`](/api/rest/v1beta/files/get). Only the `name`\n(and by extension, the `uri`) are unique. 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))` REST`name=$(jq \".file.name\" file_info.json) # Get the file of interest to check state\ncurl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json\n# Print some information about the file you got name=$(jq \".file.name\" file_info.json) echo name=$name file_uri=$(jq \".file.uri\" file_info.json) echo file_uri=$file_uri` Passing multiple PDFs The Gemini API is capable of processing multiple PDF documents (up to 1000 pages)\nin a single request, as long as the combined size of the documents and the text\nprompt stays within the model's context window. Python`from google import genai import io import httpx client = genai.Client() doc_url_1 = \"https://arxiv.org/pdf/2312.11805\" doc_url_2 = \"https://arxiv.org/pdf/2403.05530\" # Retrieve and upload both PDFs using the File API doc_data_1 = io.BytesIO(httpx.get(doc_url_1).content) doc_data_2 = io.BytesIO(httpx.get(doc_url_2).content) sample_pdf_1 = client.files.upload( file=doc_data_1, config=dict(mime_type='application/pdf') ) sample_pdf_2 = client.files.upload( file=doc_data_2, config=dict(mime_type='application/pdf') ) prompt = \"What is the difference between each of the main benchmarks between these two papers? Output these in a table.\" response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[sample_pdf_1, sample_pdf_2, prompt] ) print(response.text)` JavaScript`import { createPartFromUri, GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({ apiKey: \"GEMINI_API_KEY\" }); async function uploadRemotePDF(url, displayName) { const pdfBuffer = await fetch(url) .then((response) => response.arrayBuffer()); const fileBlob = new Blob([pdfBuffer], { type: 'application/pdf' }); const file = await ai.files.upload({ file: fileBlob, config: { displayName: displayName, }, }); // Wait for the file to be processed. let getFile = await ai.files.get({ name: file.name }); while (getFile.state === 'PROCESSING') { getFile = await ai.files.get({ name: file.name }); console.log(`current file status: ${getFile.state}`); console.log('File is still processing, retrying in 5 seconds'); await new Promise((resolve) => { setTimeout(resolve, 5000); }); } if (file.state === 'FAILED') { throw new Error('File processing failed.'); } return file; } async function main() { const content = [ 'What is the difference between each of the main benchmarks between these two papers? Output these in a table.', ]; let file1 = await uploadRemotePDF(\"https://arxiv.org/pdf/2312.11805\", \"PDF 1\") if (file1.uri && file1.mimeType) { const fileContent = createPartFromUri(file1.uri, file1.mimeType); content.push(fileContent); } let file2 = await uploadRemotePDF(\"https://arxiv.org/pdf/2403.05530\", \"PDF 2\") if (file2.uri && file2.mimeType) { const fileContent = createPartFromUri(file2.uri, file2.mimeType); content.push(fileContent); } const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: content, }); console.log(response.text); } main();` 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, }) docUrl1 := \"https://arxiv.org/pdf/2312.11805\" docUrl2 := \"https://arxiv.org/pdf/2403.05530\" localPath1 := \"doc1_downloaded.pdf\" localPath2 := \"doc2_downloaded.pdf\" respHttp1, _ := http.Get(docUrl1) defer respHttp1.Body.Close() outFile1, _ := os.Create(localPath1) _, _ = io.Copy(outFile1, respHttp1.Body) outFile1.Close() respHttp2, _ := http.Get(docUrl2) defer respHttp2.Body.Close() outFile2, _ := os.Create(localPath2) _, _ = io.Copy(outFile2, respHttp2.Body) outFile2.Close() uploadConfig1 := &genai.UploadFileConfig{MIMEType: \"application/pdf\"} uploadedFile1, _ := client.Files.UploadFromPath(ctx, localPath1, uploadConfig1) uploadConfig2 := &genai.UploadFileConfig{MIMEType: \"application/pdf\"} uploadedFile2, _ := client.Files.UploadFromPath(ctx, localPath2, uploadConfig2) promptParts := []*genai.Part{ genai.NewPartFromURI(uploadedFile1.URI, uploadedFile1.MIMEType), genai.NewPartFromURI(uploadedFile2.URI, uploadedFile2.MIMEType), genai.NewPartFromText(\"What is the difference between each of the \" + \"main benchmarks between these two papers? \" + \"Output these in a table.\"), } contents := []*genai.Content{ genai.NewContentFromParts(promptParts, genai.RoleUser), } modelName := \"gemini-3.8-flash\" result, _ := client.Models.GenerateContent( ctx, modelName, contents, nil, ) fmt.Println(result.Text()) }` REST`DOC_URL_1=\"https://arxiv.org/pdf/2312.11805\" DOC_URL_2=\"https://arxiv.org/pdf/2403.05530\" DISPLAY_NAME_1=\"Gemini_paper\" DISPLAY_NAME_2=\"Gemini_1.5_paper\" PROMPT=\"What is the difference between each of the main benchmarks between these two papers? Output these in a table.\" # Function to download and upload a PDF\nupload_pdf() { local doc_url=\"$1\" local display_name=\"$2\" # Download the PDF wget -O \"${display_name}.pdf\" \"${doc_url}\" local MIME_TYPE=$(file -b --mime-type \"${display_name}.pdf\") local NUM_BYTES=$(wc -c < \"${display_name}.pdf\") echo \"MIME_TYPE: ${MIME_TYPE}\" echo \"NUM_BYTES: ${NUM_BYTES}\" local tmp_header_file=upload-header.tmp\n\n # Initial resumable request curl \"${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}\" \\ -D \"${tmp_header_file}\" \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${display_name}'}}\" 2> /dev/null\n\n local upload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\") rm \"${tmp_header_file}\" # Upload the PDF curl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${display_name}.pdf\" 2> /dev/null > \"file_info_${display_name}.json\" local file_uri=$(jq \".file.uri\" \"file_info_${display_name}.json\") echo \"file_uri for ${display_name}: ${file_uri}\" # Clean up the downloaded PDF rm \"${display_name}.pdf\" echo \"${file_uri}\" } # Upload the first PDF file_uri_1=$(upload_pdf \"${DOC_URL_1}\" \"${DISPLAY_NAME_1}\") # Upload the second PDF file_uri_2=$(upload_pdf \"${DOC_URL_2}\" \"${DISPLAY_NAME_2}\") # Now generate content using both files\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GOOGLE_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"file_data\": {\"mime_type\": \"application/pdf\", \"file_uri\": '$file_uri_1'}}, {\"file_data\": {\"mime_type\": \"application/pdf\", \"file_uri\": '$file_uri_2'}}, {\"text\": \"'$PROMPT'\"} ] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` Technical details Gemini supports PDF files up to 50MB or 1000 pages. This limit applies\nto both inline data and Files API uploads. Each document page is equivalent to 258\ntokens. While there are no specific limits to the number of pixels in a document besides\nthe model's [context window](/gemini-api/docs/long-context), larger pages are\nscaled down to a maximum resolution of 3072 x 3072 while preserving their original\naspect ratio, while smaller pages are scaled up to 768 x 768 pixels. There is no\ncost reduction for pages at lower sizes, other than bandwidth, or performance\nimprovement for pages at higher resolution. Gemini 3 models Gemini 3 introduces granular control over multimodal vision processing with the\n`media_resolution` parameter. You can now set the resolution to low, medium, or\nhigh per individual media part. With this addition, the processing of PDF\ndocuments has been updated: **Native text inclusion:** Text natively embedded in the PDF is extracted\nand provided to the model. **Billing & token reporting:** You are **not charged** for tokens originating from the extracted\n**native text** in PDFs. In the `usage_metadata` section of the API response, tokens generated\nfrom processing PDF pages (as images) are now counted under the `IMAGE`\nmodality, not a separate `DOCUMENT` modality as in some earlier\nversions. For more details about the media resolution parameter, see the\n[Media resolution](/gemini-api/docs/generate-content/media-resolution) guide. Document types Technically, you can pass other MIME types for document understanding, like\nTXT, Markdown, HTML, XML, etc. However, document vision ***only meaningfully\nunderstands PDFs***. Other types will be extracted as pure text, and the model\nwon't be able to interpret what we see in the rendering of those files. Any\nfile-type specifics like charts, diagrams, HTML tags, Markdown formatting, etc.,\nwill be lost. To learn about other file input methods, see the\n[File input methods](/gemini-api/docs/file-input-methods) guide. Best practices For best results: Rotate pages to the correct orientation before uploading. Avoid blurry pages. If using a single page, place the text prompt after the page. What's next To learn more, see the following resources: [File prompting strategies](/gemini-api/docs/files#prompt-guide): The\nGemini API supports prompting with text, image, audio, and video data, also\nknown as multimodal prompting. [System instructions](/gemini-api/docs/text-generation#system-instructions):\nSystem instructions let you steer the behavior of the model based on your\nspecific needs and use cases. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 24977, "slov": 2939, "odkazu": 128, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:51", "sha256": "6af8a98cfaea27f2b1e91252b55cee8523c08d9567caa284756f0cd46aae4efe", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/file-input-methods", "titulek": "File input methods | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "File input methods", "popis": "Get started building with Gemini's multimodal capabilities in the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/file-input-methods", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "File input methods  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Get started building with Gemini's multimodal capabilities in the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/file-input-methods", "og:image": "https://ai.google.dev/static/site-assets/images/vision.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "File input methods"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "File input methods", "item": "https://ai.google.dev/gemini-api/docs/generate-content/file-input-methods"}]}], "drobecky": ["Generate Content API", "File input methods"], "osnova": [{"uroven": 1, "text": "File input methods"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Input method comparison"}, {"uroven": 2, "text": "Inline data"}, {"uroven": 3, "text": "Fetch from a URL"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Gemini File API"}, {"uroven": 3, "text": "Standard file upload"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Register Google Cloud Storage files"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "CLI"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "CLI"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "CLI"}, {"uroven": 2, "text": "External HTTP / Signed URLs"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Accessibility"}, {"uroven": 3, "text": "Safety checks"}, {"uroven": 3, "text": "Supported content types"}, {"uroven": 4, "text": "Text file types"}, {"uroven": 4, "text": "Application file types"}, {"uroven": 4, "text": "Image file types"}, {"uroven": 4, "text": "Video file types"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "File input methods This guide explains the different ways you can include media files such as\nimages, audio, video, and documents when making requests to the Gemini API.\nThe new methods are supported in all of the Gemini API endpoints, including \nBatch, Interactions and Live API.\nChoosing the right method depends on the size of your file, where your data is\ncurrently stored, and how frequently you plan to use the file. The simplest way to include a file as your input is to read a local file and\ninclude it in a prompt. The following example shows how to read a local PDF\nfile. PDFs are limited to 50MB for this method. See the\nInput method comparison table for a complete list of file\ninput types and limits. Python`from google import genai from google.genai import types import pathlib client = genai.Client() filepath = pathlib.Path('my_local_file.pdf') prompt = \"Summarize this document\" response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[ types.Part.from_bytes( data=filepath.read_bytes(), mime_type='application/pdf', ), prompt ] ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from 'node:fs'; const ai = new GoogleGenAI({}); const prompt = \"Summarize this document\"; async function main() { const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed const contents = [ { text: prompt }, { inlineData: { mimeType: 'application/pdf', data: fs.readFileSync(filePath).toString(\"base64\") } } ]; const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: contents }); console.log(response.text); } main();` REST`# Encode the local file to base64 B64_CONTENT=$(base64 -w 0 my_local_file.pdf)\n\ncurl -X POST \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"contents\": [ { \"parts\": [ {\"text\": \"Summarize this document\"} ] }, { \"parts\": [ { \"inlineData\": { \"mimeType\": \"application/pdf\", \"data\": \"'\"${B64_CONTENT}\"'\" } } ] } ] }'` Input method comparison The following table compares each input method with file limits and best use\ncases. Note that the file size limit may vary depending on the file type and\nmodel/tokenizer used to process the file. Method Best for Max file size Persistence **Inline data** Quick testing, small files, real-time applications. 100 MB per request/payload \n (**50 MB for PDFs**) None (sent with every request) **File API upload** Large files, files used multiple times. 2 GB per file, \n up to 20GB per project 48 Hours **File API GCS URI registration** Large files already in Google Cloud Storage, files used multiple times. 2 GB per file, no overall storage limits None (fetched per request). One time registration can give access for up to 30 days. **External URLs** Public data or data in cloud buckets (AWS, Azure, GCS) without re-uploading. 100 MB per request/payload None (fetched per request) Inline data For smaller files (under 100MB, or 50MB for PDFs), you can pass the data\ndirectly in the request payload. This is the simplest method for quick tests or\napplications handling real-time, transient data. You can provide data as\nbase64 encoded strings or by reading local files directly. For an example of reading from a local file, see the example at the beginning of\nthis page. Fetch from a URL You can also fetch a file from a URL, convert it to bytes, and include it in the\ninput. Python`from google import genai from google.genai import types import httpx client = genai.Client() doc_url = \"https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf\" doc_data = httpx.get(doc_url).content prompt = \"Summarize this document\" response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[ types.Part.from_bytes( data=doc_data, mime_type='application/pdf', ), prompt ] ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); const docUrl = 'https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf'; const prompt = \"Summarize this document\"; async function main() { const pdfResp = await fetch(docUrl) .then((response) => response.arrayBuffer()); const contents = [ { text: prompt }, { inlineData: { mimeType: 'application/pdf', data: Buffer.from(pdfResp).toString(\"base64\") } } ]; const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: contents }); console.log(response.text); } main();` REST`DOC_URL=\"https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf\" PROMPT=\"Summarize this document\" DISPLAY_NAME=\"base64_pdf\" # Download the PDF\nwget -O \"${DISPLAY_NAME}.pdf\" \"${DOC_URL}\" # Check for FreeBSD base64 and set flags accordingly if [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then B64FLAGS=\"--input\" else B64FLAGS=\"-w0\" fi # Base64 encode the PDF ENCODED_PDF=$(base64 $B64FLAGS \"${DISPLAY_NAME}.pdf\") # Generate content using the base64 encoded PDF\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"inline_data\": {\"mime_type\": \"application/pdf\", \"data\": \"'\"$ENCODED_PDF\"'\"}}, {\"text\": \"'$PROMPT'\"} ] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` Gemini File API The File API is designed for larger files (up to 2GB) or files you intend to\nuse in multiple requests. Standard file upload Upload a local file to the Gemini API. Files uploaded this way are stored\ntemporarily (48 hours) and processed for efficient retrieval by the model. Python`from google import genai client = genai.Client() # Upload the file audio_file = client.files.upload(file=\"path/to/your/sample.mp3\") prompt = \"Describe this audio clip\" # Use the uploaded file in a prompt response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[prompt, audio_file] ) print(response.text)` JavaScript`import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; const ai = new GoogleGenAI({}); const prompt = \"Describe this audio clip\"; async function main() { const filePath = \"path/to/your/sample.mp3\"; // Adjust path as needed const myfile = await ai.files.upload({ file: filePath, config: { mimeType: \"audio/mpeg\" }, }); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: createUserContent([ prompt, createPartFromUri(myfile.uri, myfile.mimeType), ]), }); console.log(response.text); } await main();` REST`AUDIO_PATH=\"path/to/sample.mp3\" MIME_TYPE=$(file -b --mime-type \"${AUDIO_PATH}\") NUM_BYTES=$(wc -c < \"${AUDIO_PATH}\") DISPLAY_NAME=AUDIO\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"${BASE_URL}/upload/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -D \"${tmp_header_file}\" \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${AUDIO_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) echo file_uri=$file_uri # Now generate content using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"text\": \"Describe this audio clip\"}, {\"file_data\":{\"mime_type\": \"${MIME_TYPE}\", \"file_uri\": '$file_uri'}}] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` Register Google Cloud Storage files If your data is already in Google Cloud Storage, you don't need to\ndownload and re-upload it. You can register it directly with the File API. Grant **Service Agent** access to each bucket Enable the Gemini API in your Google Cloud project. Create the Service Agent: `gcloud beta services identity create --service=generativelanguage.googleapis.com --project=` **Grant the Gemini API Service Agent permissions** to read your storage\nbuckets. The user needs to assign the `Storage Object Viewer` [IAM role](https://docs.cloud.google.com/storage/docs/access-control/iam-roles#storage.objectViewer)\nto this service agent on the specific storage buckets they intend to use. This access doesn't expire by default, but can be changed at any time. You can\nalso use the\n[Google Cloud Storage IAM SDK](https://cloud.google.com/iam/docs/write-policy-client-libraries)\ncommands to grant permissions. Authenticate your service **Prerequisites** Enable API Create a service account/agent with appropriate permissions. You first need to authenticate as the service that has storage object viewer\npermissions. How this happens depends on the environment in which your file\nmanagement code will be running. **Outside of Google Cloud** If your code is running from outside of Google Cloud, such as your desktop,\ndownload the account credentials from the Google Cloud Console with the\nfollowing steps: Browse to the [Service Account console](https://console.cloud.google.com/iam-admin/serviceaccounts) Select the relevant service account Select the **Keys** tab and choose **Add key, Create new key** Choose the **JSON** key type, and note where the file was downloaded to on\nyour machine. For more details, see the official Google Cloud documentation on [service account key\nmanagement](https://docs.cloud.google.com/iam/docs/keys-create-delete). Then use the following commands to authenticate. These commands assume your\nservice account file is in the current directory, named `service-account.json`. Python`from google.oauth2.service_account import Credentials GCS_READ_SCOPES = [ 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/cloud-platform' ] SERVICE_ACCOUNT_FILE = 'service-account.json' credentials = Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=GCS_READ_SCOPES )` Javascript`const { GoogleAuth } = require('google-auth-library'); const GCS_READ_SCOPES = [ 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/cloud-platform' ]; const SERVICE_ACCOUNT_FILE = 'service-account.json'; const auth = new GoogleAuth({ keyFile: SERVICE_ACCOUNT_FILE, scopes: GCS_READ_SCOPES });` CLI`gcloud auth application-default login \\ --client-id-file=service-account.json \\ --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only'` **On Google Cloud** If you are running directly in Google Cloud, for example by using [Cloud\nRun functions](https://cloud.google.com/functions) or a\n[Compute Engine instance](https://cloud.google.com/products/compute), you will\nhave implicit credentials but will need to re-authenticate to grant the\nappropriate scopes. PythonThis code expects that the service is running in an environment where\n[Application Default Credentials](https://docs.cloud.google.com/docs/authentication/application-default-credentials)\ncan be obtained automatically, such as Cloud Run or Compute Engine. `import google.auth GCS_READ_SCOPES = [ 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/cloud-platform' ] credentials, project = google.auth.default(scopes=GCS_READ_SCOPES)` JavaScriptThis code expects that the service is running in an environment where\n[Application Default Credentials](https://docs.cloud.google.com/docs/authentication/application-default-credentials)\ncan be obtained automatically, such as Cloud Run or Compute Engine. `const { GoogleAuth } = require('google-auth-library'); const auth = new GoogleAuth({ scopes: [ 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/cloud-platform' ] });` CLIThis is an interactive command. For services like Compute Engine you can attach scopes to\nthe running service at the config level. See the [user-managed service\ndocs](https://docs.cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#using)\nfor an example. `gcloud auth application-default login \\\n--scopes=\"https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only\"` File registration (Files API) Use the Files API to register files and produce a Files API path that can\ndirectly be used in the Gemini API. Python`from google import genai from google.genai.types import Part # Note that you must provide an API key in the GEMINI_API_KEY # environment variable, but it is unused for the registration endpoint. client = genai.Client() registered_gcs_files = client.files.register_files( uris=[\"gs://my_bucket/some_object.pdf\", \"gs://bucket2/object2.txt\"], # Use the credentials obtained in the previous step. auth=credentials ) prompt = \"Summarize this file.\" # call generateContent for each file for f in registered_gcs_files.files: print(f.name) response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[Part.from_uri( file_uri=f.uri, mime_type=f.mime_type, ), prompt], ) print(response.text)` CLI`access_token=$(gcloud auth application-default print-access-token) project_id=$(gcloud config get-value project)\ncurl -X POST https://generativelanguage.googleapis.com/v1beta/files:register \\ -H 'Content-Type: application/json' \\ -H \"Authorization: Bearer ${access_token}\" \\ -H \"x-goog-user-project: ${project_id}\" \\ -d '{\"uris\": [\"gs://bucket/object1\", \"gs://bucket/object2\"]}'` External HTTP / Signed URLs You can pass publicly accessible HTTPS URLs or pre-signed URLs (compatible with\n[S3 Presigned\nURLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html)\nand Azure SAS) directly in your generation request. The Gemini API will fetch\nthe content securely during processing. This is ideal for files up to 100MB that\nyou don't want to re-upload. You can use public or signed URLs as input by using the URLs in the\n`[file_uri](/api/caching#FileData)` field. Python`from google import genai from google.genai.types import Part uri = \"https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf\" prompt = \"Summarize this file\" client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[ Part.from_uri( file_uri=uri, mime_type=\"application/pdf\", ), prompt ], ) print(response.text)` Javascript`import { GoogleGenAI, createPartFromUri } from '@google/genai'; const client = new GoogleGenAI({}); const uri = \"https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf\"; async function main() { const response = await client.models.generateContent({ model: 'gemini-3.8-flash', contents: [ // equivalent to Part.from_uri(file_uri=uri, mime_type=\"...\") createPartFromUri(uri, \"application/pdf\"), \"summarize this file\", ], }); console.log(response.text); } main();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent \\ -H 'x-goog-api-key: $GEMINI_API_KEY' \\ -H 'Content-Type: application/json' \\ -d '{ \"contents\":[ { \"parts\":[ {\"text\": \"Summarize this pdf\"}, { \"file_data\": { \"mime_type\":\"application/pdf\", \"file_uri\": \"https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf\" } } ] } ] }'` Accessibility Verify that the URLs you provide don't lead to pages that require a login or\nare behind a paywall. For private databases, ensure you create a signed URL\nwith the correct access permissions and expiry. Safety checks The system performs a content moderation check on the URL to confirm they meet\nsafety and policy standards (e.g. non-opted out & paywalled\ncontent). If the URL you provided fails this check, you will get an\n`url_retrieval_status` of `URL_RETRIEVAL_STATUS_UNSAFE`. Supported content types This list of supported file types and limitations is intended as initial\nguidance and is not comprehensive. The effective\nset of supported types is subject to change and can vary based on the specific\nmodel and tokenizer version in use. Unsupported types will result in an error.\nAdditionally, content retrieval for these file types\ncurrently only supports publicly accessible URLs. Text file types `text/html` `text/css` `text/plain` `text/xml` `text/csv` `text/rtf` `text/javascript` Application file types `application/json` `application/pdf` Image file types `image/bmp` `image/jpeg` `image/png` `image/webp` Video file types `video/mp4` `video/mpeg` `video/quicktime` `video/avi` `video/x-flv` `video/mpg` `video/webm` `video/wmv` `video/3gpp` Best practices **Choose the right method:** Use inline data for small, transient files.\nUse the File API for larger or frequently used files. Use external URLs\nfor data already hosted online. **Specify MIME Types:** Always provide the correct MIME type for the file\ndata to ensure proper processing. **Handle Errors:** Implement error handling in your code to manage\npotential issues like network failures, file access problems, or API\nerrors. **Manage GCS Permissions:** When using GCS registration, grant the Gemini\nAPI Service Agent only the necessary `Storage Object Viewer` role on the\nspecific buckets. **Signed URL Security:** Ensure signed URLs have an appropriate expiration\ntime and limited permissions. Limitations File size limits vary by method (see comparison table)\nand file type. Inline data increases request payload size. File API uploads are temporary and expire after 48 hours. External URL fetching is limited to 100MB per payload and supports specific\ncontent types. Google Cloud Storage registration requires proper IAM setup and OAuth\ntoken management. What's next Try writing your own multimodal prompts using\n[Google AI Studio](http://aistudio.google.com/). For information on including files in your prompts, see the\n[Vision](/gemini-api/docs/vision),\n[Audio](/gemini-api/docs/audio), and\n[Document processing](/gemini-api/docs/document-processing) guides. For more guidance on prompt design, like tuning sampling parameters, see the\n[Prompt strategies](/gemini-api/docs/prompt-strategies) guide. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 18849, "slov": 2390, "odkazu": 138, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:07", "sha256": "6a13faad926dca3c001db689a53ab3b4e5f4ccf1e2e405255e24358cb1293336", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://docs.cloud.google.com/storage/docs/access-control/iam-roles", "https://cloud.google.com/iam/docs/write-policy-client-libraries", "https://console.cloud.google.com/iam-admin/serviceaccounts", "https://docs.cloud.google.com/iam/docs/keys-create-delete", "https://cloud.google.com/functions", "https://cloud.google.com/products/compute", "https://docs.cloud.google.com/docs/authentication/application-default-credentials", "https://docs.cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances", "https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html", "http://aistudio.google.com/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/file-search", "titulek": "File search | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "File search", "popis": "Get started building RAG solutions with the File Search tool in the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/file-search", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "File search  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Get started building RAG solutions with the File Search tool in the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/file-search", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "File search"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "File search", "item": "https://ai.google.dev/gemini-api/docs/generate-content/file-search"}]}], "drobecky": ["Generate Content API", "File search"], "osnova": [{"uroven": 1, "text": "File search"}, {"uroven": 2, "text": "Directly upload to File Search store"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Importing files"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Chunking configuration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "How it works"}, {"uroven": 2, "text": "File Search stores"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "File Search documents"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "File metadata"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multimodal File Search"}, {"uroven": 3, "text": "Configure the embedding model"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Upload images"}, {"uroven": 2, "text": "Citations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Page numbers"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Media citations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Custom metadata in grounding data"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Structured output"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Supported models"}, {"uroven": 2, "text": "Supported tool combinations"}, {"uroven": 2, "text": "Supported file types"}, {"uroven": 3, "text": "Application file types"}, {"uroven": 3, "text": "Text file types"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 3, "text": "Rate limits"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "What's next"}], "markdown": "File search The Gemini API enables Retrieval Augmented Generation (\"RAG\") through the File\nSearch tool. File Search imports, chunks, and indexes your data to\nenable fast retrieval of relevant information based on a provided prompt. This\nretrieved information is then used as context for the model, allowing it to\nprovide more accurate and relevant answers. File search is also able to\nprovide multimodal capabilities with text embeddings supported by\n`gemini-embedding-001`, and image/multimodal embedding supported by `gemini-embedding-2`. File storage and embedding generation at query time is free, and you'll only pay\nfor creating embeddings when you first index your files and the normal Gemini\nmodel input / output tokens cost. This new billing paradigm makes the File\nSearch Tool both easier and more cost-effective to build and scale with. See\npricing section for details. Directly upload to File Search store This example shows how to directly upload a file to the [file search store](/api/file-search/file-search-stores#method:-media.uploadtofilesearchstore): Python`from google import genai from google.genai import types import time client = genai.Client() # File name will be visible in citations file_search_store = client.file_search_stores.create( config={ 'display_name': 'your-fileSearchStore-name', 'embedding_model': 'models/gemini-embedding-2' } ) operation = client.file_search_stores.upload_to_file_search_store( file='sample.txt', file_search_store_name=file_search_store.name, config={ 'display_name' : 'display-file-name', } ) while not operation.done: time.sleep(5) operation = client.operations.get(operation) response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"\"\"Can you tell me about [insert question]\"\"\", config=types.GenerateContentConfig( tools=[ types.Tool( file_search=types.FileSearch( file_search_store_names=[file_search_store.name] ) ) ] ) ) print(response.text)` JavaScript`const { GoogleGenAI } = require('@google/genai'); const ai = new GoogleGenAI({}); async function run() { // File name will be visible in citations const fileSearchStore = await ai.fileSearchStores.create({ config: { displayName: 'your-fileSearchStore-name', embeddingModel: 'models/gemini-embedding-2' } }); let operation = await ai.fileSearchStores.uploadToFileSearchStore({ file: 'file.txt', fileSearchStoreName: fileSearchStore.name, config: { displayName: 'file-name', } }); while (!operation.done) { await new Promise(resolve => setTimeout(resolve, 5000)); operation = await ai.operations.get({ operation }); } const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Can you tell me about [insert question]\", config: { tools: [ { fileSearch: { fileSearchStoreNames: [fileSearchStore.name] } } ] } }); console.log(response.text); } run();` Check the API reference for [`uploadToFileSearchStore`](/api/file-search/file-search-stores#method:-media.uploadtofilesearchstore) for more information. Importing files Alternatively, you can upload an existing file and [import it to your file search store](/api/file-search/file-search-stores#method:-filesearchstores.importfile): Python`from google import genai from google.genai import types import time client = genai.Client() # File name will be visible in citations sample_file = client.files.upload(file='sample.txt', config={'name': 'display_file_name'}) file_search_store = client.file_search_stores.create( config={ 'display_name': 'your-fileSearchStore-name', 'embedding_model': 'models/gemini-embedding-2' } ) operation = client.file_search_stores.import_file( file_search_store_name=file_search_store.name, file_name=sample_file.name ) while not operation.done: time.sleep(5) operation = client.operations.get(operation) response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"\"\"Can you tell me about [insert question]\"\"\", config=types.GenerateContentConfig( tools=[ types.Tool( file_search=types.FileSearch( file_search_store_names=[file_search_store.name] ) ) ] ) ) print(response.text)` JavaScript`const { GoogleGenAI } = require('@google/genai'); const ai = new GoogleGenAI({}); async function run() { // File name will be visible in citations const sampleFile = await ai.files.upload({ file: 'sample.txt', config: { name: 'file-name' } }); const fileSearchStore = await ai.fileSearchStores.create({ config: { displayName: 'your-fileSearchStore-name', embeddingModel: 'models/gemini-embedding-2' } }); let operation = await ai.fileSearchStores.importFile({ fileSearchStoreName: fileSearchStore.name, fileName: sampleFile.name }); while (!operation.done) { await new Promise(resolve => setTimeout(resolve, 5000)); operation = await ai.operations.get({ operation: operation }); } const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Can you tell me about [insert question]\", config: { tools: [ { fileSearch: { fileSearchStoreNames: [fileSearchStore.name] } } ] } }); console.log(response.text); } run();` Check the API reference for [`importFile`](/api/file-search/file-search-stores#method:-filesearchstores.importfile) for more information. Chunking configuration When you import a file into a File Search store, it's automatically broken down\ninto chunks, embedded, indexed, and uploaded to your File Search store. If you\nneed more control over the chunking strategy, you can specify a\n[`chunking_config`](/api/file-search/file-search-stores#request-body_5) setting\nto set a maximum number of tokens per chunk and maximum number of overlapping\ntokens. Python`from google import genai from google.genai import types import time client = genai.Client() operation = client.file_search_stores.upload_to_file_search_store( file_search_store_name=file_search_store.name, file_name=sample_file.name, config={ 'chunking_config': { 'white_space_config': { 'max_tokens_per_chunk': 200, 'max_overlap_tokens': 20 } } } ) while not operation.done: time.sleep(5) operation = client.operations.get(operation) print(\"Custom chunking complete.\")` JavaScript`const { GoogleGenAI } = require('@google/genai'); const ai = new GoogleGenAI({}); let operation = await ai.fileSearchStores.uploadToFileSearchStore({ file: 'file.txt', fileSearchStoreName: fileSearchStore.name, config: { displayName: 'file-name', chunkingConfig: { whiteSpaceConfig: { maxTokensPerChunk: 200, maxOverlapTokens: 20 } } } }); while (!operation.done) { await new Promise(resolve => setTimeout(resolve, 5000)); operation = await ai.operations.get({ operation }); } console.log(\"Custom chunking complete.\");` To use your File Search store, pass it as a tool to the `generateContent`\nmethod, as shown in the Upload and Import examples. How it works File Search uses a technique called semantic search to find information relevant\nto the user prompt. Unlike standard keyword-based search, semantic search\nunderstands the meaning and context of your query. When you import a file, it's converted into numerical representations called\n[embeddings](/gemini-api/docs/embeddings), which capture the semantic meaning of\nthe uploaded content. These embeddings are stored in a specialized File Search database.\nWhen you make a query, it's also converted into an embedding. Then the system\nperforms a File Search to find the most similar and relevant document chunks\nfrom the File Search store. There is no Time To Live (TTL) for embeddings;\nthey persist until manually deleted, or when the model is deprecated. Files,\nhowever, are deleted after 48 hours. Here's a breakdown of the process for using the File Search\n`uploadToFileSearchStore` API: **Create a File Search store**: A File Search store contains the processed\ndata from your files. It's the persistent container for the embeddings that the\nsemantic search will operate on. **Upload a file and import into a File Search store**: Simultaneously upload\na file and import the results into your File Search store. This creates a\ntemporary `File` object, which is a reference to your raw document. That data is\nthen chunked, converted into File Search embeddings, and indexed. The `File`\nobject gets deleted after 48 hours, while the data imported into the File Search\nstore will be stored indefinitely until you choose to delete it. **Query with File Search**: Finally, you use the `FileSearch` tool in a\n`generateContent` call. In the tool configuration, you specify a\n`FileSearchRetrievalResource`, which points to the `FileSearchStore` you want to\nsearch. This tells the model to perform a semantic search on that specific\nFile Search store to find relevant information to ground its response. The indexing and querying process of File Search In this diagram, the dotted line from *Documents* to *Embedding model*\n(using [`gemini-embedding-001`](/gemini-api/docs/embeddings))\nrepresents the `uploadToFileSearchStore` API (bypassing *File storage*).\nOtherwise, using the [Files API](/gemini-api/docs/files) to separately create\nand then import files moves the indexing process from *Documents* to\n*File storage* and then to *Embedding model*. File Search stores A File Search store is a container for your document embeddings. While raw files\nuploaded through the File API are deleted after 48 hours, the data imported into\na File Search store is stored indefinitely until you manually delete it. You can\ncreate multiple File Search stores to organize your documents. The\n`FileSearchStore` API lets you create, list, get, and delete to manage your file\nsearch stores. File Search store names are globally scoped. Here are some examples of how to manage your File Search stores: Python`file_search_store = client.file_search_stores.create( config={ 'display_name': 'my-file_search-store-123', 'embedding_model': 'models/gemini-embedding-2' } ) for file_search_store in client.file_search_stores.list(): print(file_search_store) my_file_search_store = client.file_search_stores.get(name='fileSearchStores/my-file_search-store-123') client.file_search_stores.delete(name='fileSearchStores/my-file_search-store-123', config={'force': True})` JavaScript`const fileSearchStore = await ai.fileSearchStores.create({ config: { displayName: 'my-file_search-store-123', embeddingModel: 'models/gemini-embedding-2' } }); const fileSearchStores = await ai.fileSearchStores.list(); for await (const store of fileSearchStores) { console.log(store); } const myFileSearchStore = await ai.fileSearchStores.get({ name: 'fileSearchStores/my-file_search-store-123' }); await ai.fileSearchStores.delete({ name: 'fileSearchStores/my-file_search-store-123', config: { force: true } });` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=${GEMINI_API_KEY}\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"displayName\": \"My Store\", \"embedding_model\": \"models/gemini-embedding-2\" }'\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=${GEMINI_API_KEY}\" \\\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123?key=${GEMINI_API_KEY}\"\n\ncurl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123?key=${GEMINI_API_KEY}\"` File Search documents You can manage individual documents in your file stores with the\n[File Search Documents](/api/file-search/documents) API to `list` each document\nin a file search store, `get` information about a document, and `delete` a\ndocument by name. Python`for document_in_store in client.file_search_stores.documents.list(parent='fileSearchStores/my-file_search-store-123'): print(document_in_store) file_search_document = client.file_search_stores.documents.get(name='fileSearchStores/my-file_search-store-123/documents/my_doc') print(file_search_document) client.file_search_stores.documents.delete(name='fileSearchStores/my-file_search-store-123/documents/my_doc')` JavaScript`const documents = await ai.fileSearchStores.documents.list({ parent: 'fileSearchStores/my-file_search-store-123' }); for await (const doc of documents) { console.log(doc); } const fileSearchDocument = await ai.fileSearchStores.documents.get({ name: 'fileSearchStores/my-file_search-store-123/documents/my_doc', }); await ai.fileSearchStores.documents.delete({ name: 'fileSearchStores/my-file_search-store-123/documents/my_doc' });` REST`curl \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents?key=${GEMINI_API_KEY}\"\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents/my_doc?key=${GEMINI_API_KEY}\"\n\ncurl -X DELETE \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores/my-file_search-store-123/documents/my_doc?key=${GEMINI_API_KEY}\"` File metadata You can add custom metadata to your files to help filter them or provide\nadditional context. Metadata is a set of key-value pairs. Python`op = client.file_search_stores.import_file( file_search_store_name=file_search_store.name, file_name=sample_file.name, custom_metadata=[ {\"key\": \"author\", \"string_value\": \"Robert Graves\"}, {\"key\": \"year\", \"numeric_value\": 1934} ] )` JavaScript`let operation = await ai.fileSearchStores.importFile({ fileSearchStoreName: fileSearchStore.name, fileName: sampleFile.name, config: { customMetadata: [ { key: \"author\", stringValue: \"Robert Graves\" }, { key: \"year\", numericValue: 1934 } ] } });` This is useful when you have multiple documents in a File Search store and want\nto search only a subset of them. Python`response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Tell me about the book 'I, Claudius'\", config=types.GenerateContentConfig( tools=[ types.Tool( file_search=types.FileSearch( file_search_store_names=[file_search_store.name], metadata_filter=\"author=Robert Graves\", ) ) ] ) ) print(response.text)` JavaScript`const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Tell me about the book 'I, Claudius'\", config: { tools: [ { fileSearch: { fileSearchStoreNames: [fileSearchStore.name], metadataFilter: 'author=\"Robert Graves\"', } } ] } }); console.log(response.text);` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=${GEMINI_API_KEY}\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[{\"text\": \"Tell me about the book I, Claudius\"}] }], \"tools\": [{ \"file_search\": { \"file_search_store_names\":[\"'$STORE_NAME'\"], \"metadata_filter\": \"author = \\\"Robert Graves\\\"\" } }] }' 2> /dev/null > response.json\n\ncat response.json` Guidance on implementing list filter syntax for `metadata_filter` can be found\nat [google.aip.dev/160](https://google.aip.dev/160) Multimodal File Search Multimodal File Search lets you to natively embed and search through images,\nenabling rich, multimodal RAG applications. Configure the embedding model When you create a `FileSearchStore`, you must override the default text-only\nembedding model to use a multimodal model. Use `models/gemini-embedding-2` to\nprocess both text and images. Python`store = client.file_search_stores.create( config={ \"display_name\": \"Multimodal Catalog\", \"embedding_model\": \"models/gemini-embedding-2\", } )` JavaScript`const fileSearchStore = await ai.fileSearchStores.create({ config: { displayName: \"Multimodal Catalog\", embeddingModel: \"models/gemini-embedding-2\", }, });` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/fileSearchStores?key=$GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"display_name\": \"Multimodal Catalog\", \"embedding_model\": \"models/gemini-embedding-2\" }'` Upload images After you create the store with a multimodal embedding model, you can upload\nimage files directly using the same upload APIs described in\nDirectly upload to File Search store or Importing files. **Image file requirements:** Image files must be at most 4K x 4K pixels in resolution. Supported formats are PNG, JPEG. Citations When you use File Search, the model's response may include citations that\nspecify which parts of your uploaded documents were used to generate the\nanswer. This helps with fact-checking and verification. You can access citation information through the `grounding_metadata` attribute\nof the response. Python`print(response.candidates[0].grounding_metadata)` JavaScript`console.log(JSON.stringify(response.candidates?.[0]?.groundingMetadata, null, 2));` For detailed information on the structure of the grounding metadata, see the\nexamples in the [File Search\ncookbook](https://github.com/google-gemini/cookbook/blob/main/quickstarts/File_Search.ipynb)\nor [the grounding section of the Grounding with Google\nSearch](https://ai.google.dev/gemini-api/docs/google-search#attributing_sources_with_inline_citations)\ndocs. Page numbers When you use File Search with documents that have pages (such as PDFs), the\nmodel's response may include the page number where the information was found.\nYou can access this information through the `page_number` attribute of the\n`retrieved_context`. Python`# Iterate through citations and check for page numbers for chunk in response.grounding_metadata.grounding_chunks: if chunk.retrieved_context and chunk.retrieved_context.page_number: print(f\"Cited Page: {chunk.retrieved_context.page_number}\")` JavaScript`const groundingMetadata = response.candidates[0].groundingMetadata; for (const chunk of groundingMetadata.groundingChunks) { if (chunk.retrievedContext && chunk.retrievedContext.pageNumber) { console.log(`Cited Page: ${chunk.retrievedContext.pageNumber}`); } }` Media citations When the model references an image chunk during generation, the API returns a\ncitation in the grounding metadata that includes a `media_id`. You can use this\nID to download the exact image chunk the model referenced. This `media_id` is\npersistent across multiple search calls, which lets you reliably retrieve\nthe same image or cache it using the ID. The following snippet is an example REST response: `\"groundingMetadata\": { \"groundingChunks\": [ { \"retrievedContext\": { \"title\": \"product_image\", \"fileSearchStore\": \"fileSearchStores/my-store-123\", \"media_id\": \"fileSearchStores/my-store-123/media/BlobId-456\" } } ] }` The following code snippets demonstrate how to retrieve the `media_id` and\ndownload the media: Python`# Iterate through citations and download media if present for chunk in response.grounding_metadata.grounding_chunks: if chunk.retrieved_context and chunk.retrieved_context.media_id: print(f\"Cited Media ID: {chunk.retrieved_context.media_id}\") # Download the blob using the SDK blob_content = client.file_search_stores.download_media( media_id=chunk.retrieved_context.media_id ) # Save blob_content to file...` JavaScript`const groundingMetadata = response.candidates[0].groundingMetadata; for (const chunk of groundingMetadata.groundingChunks) { if (chunk.retrievedContext && chunk.retrievedContext.mediaId) { console.log(`Cited Media ID: ${chunk.retrievedContext.mediaId}`); const blobContent = await ai.fileSearchStores.downloadMedia(chunk.retrievedContext.mediaId); // Save blobContent to file... } }` REST`curl -X GET \"https://generativelanguage.googleapis.com/v1/fileSearchStores/my-store-123/media/BlobId-456\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Custom metadata in grounding data If you have added custom metadata to your files, you can access it in the\ngrounding metadata of the model's response. This is useful for passing\nadditional context (like URLs, page numbers, or authors) from your source\ndocuments to your application logic. Each `grounding_chunk` in the\n`retrieved_context` contains this custom metadata. Python`response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Tell me about [insert question]\", config=types.GenerateContentConfig( tools=[ types.Tool( file_search=types.FileSearch( file_search_store_names=[file_search_store.name] ) ) ] ) ) for chunk in response.candidates[0].grounding_metadata.grounding_chunks: if chunk.retrieved_context: print(f\"Text: {chunk.retrieved_context.text}\") if chunk.retrieved_context.custom_metadata: for metadata in chunk.retrieved_context.custom_metadata: print(f\"Metadata Key: {metadata.key}\") print(f\"Value: {metadata.string_value or metadata.numeric_value}\")` JavaScript`const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Tell me about [insert question]\", config: { tools: [ { fileSearch: { fileSearchStoreNames: [fileSearchStore.name] } } ] } }); const groundingMetadata = response.candidates[0].groundingMetadata; groundingMetadata.groundingChunks.forEach((chunk) => { if (chunk.retrievedContext) { console.log(`Text: ${chunk.retrievedContext.text}`); if (chunk.retrievedContext.customMetadata) { chunk.retrievedContext.customMetadata.forEach((metadata) => { console.log(`Metadata Key: ${metadata.key}`); console.log(`Value: ${metadata.stringValue || metadata.numericValue}`); }); } } });` REST`{ \"candidates\": [ { \"content\": { ... }, \"grounding_metadata\": { \"grounding_chunks\": [ { \"retrieved_context\": { \"text\": \"...\", \"title\": \"...\", \"uri\": \"...\", \"custom_metadata\": [ { \"key\": \"author\", \"string_value\": \"Robert Graves\" }, { \"key\": \"year\", \"numeric_value\": 1934 } ] } } ], \"grounding_supports\": [ ... ] } } ] }` Structured output Starting with Gemini 3 models, you can combine file search tool with\n[structured outputs](/gemini-api/docs/structured-output). Python`from pydantic import BaseModel, Field class Money(BaseModel): amount: str = Field(description=\"The numerical part of the amount.\") currency: str = Field(description=\"The currency of amount.\") response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"What is the minimum hourly wage in Tokyo right now?\", config=types.GenerateContentConfig( tools=[ types.Tool( file_search=types.FileSearch( file_search_store_names=[file_search_store.name] ) ) ], response_format={\"text\": {\"mime_type\": \"application/json\", \"schema\": Money.model_json_schema()}} ) ) result = Money.model_validate_json(response.text) print(result)` JavaScript`import { z } from \"zod\"; const moneySchema = z.object({ amount: z.string().describe(\"The numerical part of the amount.\"), currency: z.string().describe(\"The currency of amount.\"), }); async function run() { const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"What is the minimum hourly wage in Tokyo right now?\", config: { tools: [ { fileSearch: { fileSearchStoreNames: [file_search_store.name], }, }, ], responseFormat: { text: { mimeType: \"application/json\", schema: z.toJSONSchema(moneySchema) } }, }, }); const result = moneySchema.parse(JSON.parse(response.text)); console.log(result); } run();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\": [{\"text\": \"What is the minimum hourly wage in Tokyo right now?\"}] }], \"tools\": [ { \"fileSearch\": { \"fileSearchStoreNames\": [\"$FILE_SEARCH_STORE_NAME\"] } } ], \"generationConfig\": { \"responseFormat\": { \"text\": { \"mimeType\": \"application/json\", \"schema\": { \"type\": \"object\", \"properties\": { \"amount\": {\"type\": \"string\", \"description\": \"The numerical part of the amount.\"}, \"currency\": {\"type\": \"string\", \"description\": \"The currency of amount.\"} } } }, \"required\": [\"amount\", \"currency\"] } } }'` Supported models The following models support File Search: Model File Search [Gemini 3.8 Flash](/gemini-api/docs/models/gemini-3.8-flash) ✔️ [Gemini 3.7 Flash](/gemini-api/docs/models/gemini-3.7-flash) ✔️ [Gemini 3.6 Flash](/gemini-api/docs/models/gemini-3.6-flash) ✔️ [Gemini 3.5 Flash-Lite](/gemini-api/docs/models/gemini-3.5-flash-lite) ✔️ [Gemini 3.5 Flash](/gemini-api/docs/models/gemini-3.5-flash) ✔️ [Gemini 3.1 Pro Preview](/gemini-api/docs/gemini-3.1-pro-preview) ✔️ [Gemini 3.1 Flash-Lite](/gemini-api/docs/models/gemini-3.1-flash-lite) ✔️ [Gemini 3 Flash Preview](/gemini-api/docs/models/gemini-3-flash-preview) ✔️ [Gemini 2.5 Pro](/gemini-api/docs/models/gemini-2.5-pro) ✔️ [Gemini 2.5 Flash-Lite](/gemini-api/docs/models/gemini-2.5-flash-lite) ✔️ Supported tool combinations Gemini 3 models support combining built-in tools (like File Search) with custom\ntools (function calling). Learn more on the\n[tool combinations](/gemini-api/docs/tool-combination) page. Supported file types File Search supports a wide range of file formats, listed in the following\nsections. Application file types `application/dart` `application/ecmascript` `application/json` `application/ms-java` `application/msword` `application/pdf` `application/sql` `application/typescript` `application/vnd.curl` `application/vnd.dart` `application/vnd.ibm.secure-container` `application/vnd.jupyter` `application/vnd.ms-excel` `application/vnd.oasis.opendocument.text` `application/vnd.openxmlformats-officedocument.presentationml.presentation` `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` `application/vnd.openxmlformats-officedocument.wordprocessingml.document` `application/vnd.openxmlformats-officedocument.wordprocessingml.template` `application/x-csh` `application/x-hwp` `application/x-hwp-v5` `application/x-latex` `application/x-php` `application/x-powershell` `application/x-sh` `application/x-shellscript` `application/x-tex` `application/x-zsh` `application/xml` `application/zip` Text file types `text/1d-interleaved-parityfec` `text/RED` `text/SGML` `text/cache-manifest` `text/calendar` `text/cql` `text/cql-extension` `text/cql-identifier` `text/css` `text/csv` `text/csv-schema` `text/dns` `text/encaprtp` `text/enriched` `text/example` `text/fhirpath` `text/flexfec` `text/fwdred` `text/gff3` `text/grammar-ref-list` `text/hl7v2` `text/html` `text/javascript` `text/jcr-cnd` `text/jsx` `text/markdown` `text/mizar` `text/n3` `text/parameters` `text/parityfec` `text/php` `text/plain` `text/provenance-notation` `text/prs.fallenstein.rst` `text/prs.lines.tag` `text/prs.prop.logic` `text/raptorfec` `text/rfc822-headers` `text/rtf` `text/rtp-enc-aescm128` `text/rtploopback` `text/rtx` `text/sgml` `text/shaclc` `text/shex` `text/spdx` `text/strings` `text/t140` `text/tab-separated-values` `text/texmacs` `text/troff` `text/tsv` `text/tsx` `text/turtle` `text/ulpfec` `text/uri-list` `text/vcard` `text/vnd.DMClientScript` `text/vnd.IPTC.NITF` `text/vnd.IPTC.NewsML` `text/vnd.a` `text/vnd.abc` `text/vnd.ascii-art` `text/vnd.curl` `text/vnd.debian.copyright` `text/vnd.dvb.subtitle` `text/vnd.esmertec.theme-descriptor` `text/vnd.exchangeable` `text/vnd.familysearch.gedcom` `text/vnd.ficlab.flt` `text/vnd.fly` `text/vnd.fmi.flexstor` `text/vnd.gml` `text/vnd.graphviz` `text/vnd.hans` `text/vnd.hgl` `text/vnd.in3d.3dml` `text/vnd.in3d.spot` `text/vnd.latex-z` `text/vnd.motorola.reflex` `text/vnd.ms-mediapackage` `text/vnd.net2phone.commcenter.command` `text/vnd.radisys.msml-basic-layout` `text/vnd.senx.warpscript` `text/vnd.sosi` `text/vnd.sun.j2me.app-descriptor` `text/vnd.trolltech.linguist` `text/vnd.wap.si` `text/vnd.wap.sl` `text/vnd.wap.wml` `text/vnd.wap.wmlscript` `text/vtt` `text/wgsl` `text/x-asm` `text/x-bibtex` `text/x-boo` `text/x-c` `text/x-c++hdr` `text/x-c++src` `text/x-cassandra` `text/x-chdr` `text/x-coffeescript` `text/x-component` `text/x-csh` `text/x-csharp` `text/x-csrc` `text/x-cuda` `text/x-d` `text/x-diff` `text/x-dsrc` `text/x-emacs-lisp` `text/x-erlang` `text/x-gff3` `text/x-go` `text/x-haskell` `text/x-java` `text/x-java-properties` `text/x-java-source` `text/x-kotlin` `text/x-lilypond` `text/x-lisp` `text/x-literate-haskell` `text/x-lua` `text/x-moc` `text/x-objcsrc` `text/x-pascal` `text/x-pcs-gcd` `text/x-perl` `text/x-perl-script` `text/x-python` `text/x-python-script` `text/x-r-markdown` `text/x-rsrc` `text/x-rst` `text/x-ruby-script` `text/x-rust` `text/x-sass` `text/x-scala` `text/x-scheme` `text/x-script.python` `text/x-scss` `text/x-setext` `text/x-sfv` `text/x-sh` `text/x-siesta` `text/x-sos` `text/x-sql` `text/x-swift` `text/x-tcl` `text/x-tex` `text/x-vbasic` `text/x-vcalendar` `text/xml` `text/xml-dtd` `text/xml-external-parsed-entity` `text/yaml` Limitations **Live API:** File Search is not supported in the\n[Live API](/gemini-api/docs/live). **Tool incompatibility:** File Search cannot be combined with other tools\nlike [Grounding with Google Search](/gemini-api/docs/google-search),\n[URL Context](/gemini-api/docs/url-context), etc. at this time. Rate limits The File Search API has the following limits to enforce service stability: **Maximum file size / per document limit**: 100 MB **Total size of project File Search stores** (based on user tier):\n **Free**: 1 GB **Tier 1**: 10 GB **Tier 2**: 100 GB **Tier 3**: 1 TB **Recommendation**: Limit the size of each File Search store to under 20 GB to ensure optimal retrieval latencies. Pricing You are charged for embeddings at indexing time based on existing\n[embeddings pricing](/gemini-api/docs/pricing#gemini-embedding-2). Storage is free of charge. Query time embeddings are free of charge. Retrieved document tokens are charged as regular\n[context tokens](/gemini-api/docs/tokens). What's next Visit the API reference for [File Search Stores](/api/file-search/file-search-stores) and File Search [Documents](/api/file-search/documents). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 29179, "slov": 3336, "odkazu": 151, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:23", "sha256": "acb614966ab597a02f59fe3874683f898b21e329cbbda17c0eeb34d938f36780", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://google.aip.dev/160", "https://github.com/google-gemini/cookbook/blob/main/quickstarts/File_Search.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/files", "titulek": "Files API | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Files API", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/files", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Files API  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/files", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Files API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Files API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/files"}]}], "drobecky": ["Generate Content API", "Files API"], "osnova": [{"uroven": 1, "text": "Files API"}, {"uroven": 2, "text": "Upload a file"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Get metadata for a file"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "List uploaded files"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Delete uploaded files"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Usage information"}, {"uroven": 2, "text": "File prompting strategies"}, {"uroven": 3, "text": "Prompt design fundamentals"}, {"uroven": 3, "text": "Troubleshooting your multimodal prompt"}, {"uroven": 3, "text": "Be specific in your instructions"}, {"uroven": 3, "text": "Add a few examples"}, {"uroven": 3, "text": "Break it down step-by-step"}, {"uroven": 3, "text": "Specify the output format"}, {"uroven": 3, "text": "Put your image first for single-image prompts"}, {"uroven": 3, "text": "Troubleshooting your multimodal prompt"}, {"uroven": 4, "text": "If the model is not drawing information from the relevant part of the image"}, {"uroven": 4, "text": "If the model output is too generic and not tailored enough to the image input"}, {"uroven": 4, "text": "Troubleshooting which part of the prompt failed"}, {"uroven": 2, "text": "What's next"}], "markdown": "Files API Gemini can handle various types of input data, including text, images, and\naudio, at the same time. This guide shows you how to work with media files using the Files API. The\nbasic operations are the same for audio files, images, videos, documents, and\nother supported file types. For file prompting guidance, check out the [File prompt guide](/gemini-api/docs/files#prompt-guide) section. Upload a file You can use the Files API to upload a media file. Always use the Files API when\nthe total request size (including the files, text prompt, system instructions,\netc.) is larger than 100 MB. For PDF files, the limit is 50 MB. The following code uploads a file and then uses the file in a call to\n`generateContent`. Python`from google import genai client = genai.Client() myfile = client.files.upload(file=\"path/to/sample.mp3\") response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[\"Describe this audio clip\", myfile] ) print(response.text)` JavaScript`import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const myfile = await ai.files.upload({ file: \"path/to/sample.mp3\", config: { mimeType: \"audio/mpeg\" }, }); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: createUserContent([ createPartFromUri(myfile.uri, myfile.mimeType), \"Describe this audio clip\", ]), }); console.log(response.text); } await main();` Go`file, err := client.Files.UploadFromPath(ctx, \"path/to/sample.mp3\", nil) if err != nil { log.Fatal(err) } defer client.Files.Delete(ctx, file.Name) resp, err := client.Models.GenerateContent(ctx, \"gemini-3.8-flash\", []*genai.Content{ { Parts: []*genai.Part{ genai.NewPartFromFile(*file), genai.NewPartFromText(\"Describe this audio clip\"), }, }, }, nil) if err != nil { log.Fatal(err) } printResponse(resp)` REST`AUDIO_PATH=\"path/to/sample.mp3\" MIME_TYPE=$(file -b --mime-type \"${AUDIO_PATH}\") NUM_BYTES=$(wc -c < \"${AUDIO_PATH}\") DISPLAY_NAME=AUDIO\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"${BASE_URL}/upload/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -D \"${tmp_header_file}\" \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${AUDIO_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq \".file.uri\" file_info.json) echo file_uri=$file_uri # Now generate content using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"text\": \"Describe this audio clip\"}, {\"file_data\":{\"mime_type\": \"${MIME_TYPE}\", \"file_uri\": '$file_uri'}}] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` Get metadata for a file You can verify that the API successfully stored the uploaded file and get its\nmetadata by calling `files.get`. Python`from google import genai client = genai.Client() myfile = client.files.upload(file='path/to/sample.mp3') file_name = myfile.name myfile = client.files.get(name=file_name) print(myfile)` JavaScript`import { GoogleGenAI, } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const myfile = await ai.files.upload({ file: \"path/to/sample.mp3\", config: { mimeType: \"audio/mpeg\" }, }); const fileName = myfile.name; const fetchedFile = await ai.files.get({ name: fileName }); console.log(fetchedFile); } await main();` Go`file, err := client.Files.UploadFromPath(ctx, \"path/to/sample.mp3\", nil) if err != nil { log.Fatal(err) } gotFile, err := client.Files.Get(ctx, file.Name) if err != nil { log.Fatal(err) } fmt.Println(\"Got file:\", gotFile.Name)` REST`# file_info.json was created in the upload example name=$(jq \".file.name\" file_info.json) # Get the file of interest to check state\ncurl https://generativelanguage.googleapis.com/v1beta/files/$name \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" > file_info.json\n# Print some information about the file you got name=$(jq \".file.name\" file_info.json) echo name=$name file_uri=$(jq \".file.uri\" file_info.json) echo file_uri=$file_uri` List uploaded files The following code gets a list of all the files uploaded: Python`from google import genai client = genai.Client() print('My files:') for f in client.files.list(): print(' ', f.name)` JavaScript`import { GoogleGenAI, } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const listResponse = await ai.files.list({ config: { pageSize: 10 } }); for await (const file of listResponse) { console.log(file.name); } } await main();` Go`for file, err := range client.Files.All(ctx) { if err != nil { log.Fatal(err) } fmt.Println(file.Name) }` REST`echo \"My files: \"\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Delete uploaded files Files are automatically deleted after 48 hours. You can also manually delete an\nuploaded file: Python`from google import genai client = genai.Client() myfile = client.files.upload(file='path/to/sample.mp3') client.files.delete(name=myfile.name)` JavaScript`import { GoogleGenAI, } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const myfile = await ai.files.upload({ file: \"path/to/sample.mp3\", config: { mimeType: \"audio/mpeg\" }, }); const fileName = myfile.name; await ai.files.delete({ name: fileName }); } await main();` Go`file, err := client.Files.UploadFromPath(ctx, \"path/to/sample.mp3\", nil) if err != nil { log.Fatal(err) } client.Files.Delete(ctx, file.Name)` REST`curl --request \"DELETE\" https://generativelanguage.googleapis.com/v1beta/files/$name \\ -H \"x-goog-api-key: $GEMINI_API_KEY\"` Usage information You can use the Files API to upload and interact with media files. The Files API\nlets you store up to 20 GB of files per project, with a per-file maximum\nsize of 2 GB. Files are stored for 48 hours. During that time, you can use the API to get metadata about the files. However,\nyou can't download user-uploaded files. You can download files generated by\nmodels, such as videos, using the `files.download` method. The Files API is\navailable at no cost in all regions where the Gemini API is available. File prompting strategies This section provides guidance and best practices for using media files with\nprompts for the Gemini API. Being able to use various types of data in your prompts gives you more\nflexibility in terms of what tasks you can tackle with the Gemini API. For\nexample, you can send the model a photo of a delicious meal and ask it to write\na short blog about the meal. **Prompt** **Response** Write a short, engaging blog post based on this picture. It should\n include a description of the meal in the photo and talk about my journey\n meal prepping. \n Meal prepping is a great way to save time and money, and it can also\n help you to eat healthier. This meal is a great example of a healthy\n and delicious meal that can be easily prepped ahead of time. This meal features brown rice, roasted vegetables, and chicken teriyaki.\n The brown rice is a healthy and complex carbohydrate that will give you\n sustained energy. The roasted vegetables are a great way to get your daily\n dose of vitamins and minerals, and the chicken teriyaki is a delicious and\n protein-rich option. This meal is also very easy to prepare. Simply cook the brown rice, roast\n the vegetables, and cook the chicken teriyaki. Once everything is cooked,\n divide it into meal prep containers and store them in the refrigerator.\n You can then grab a container and go on busy mornings! If you're looking for a healthy and delicious meal that can be easily\n prepped ahead of time, this meal is a great option. It's packed with\n nutrients and flavor, and it's sure to keep you feeling full and satisfied. Here's to healthy and delicious meal prepping! If you are having trouble getting the output you want from prompts that use\nmedia files, there are some strategies that can help you get the results you\nwant. The following sections provide design approaches and troubleshooting\ntips for improving prompts that use multimodal input. You can improve your multimodal prompts by following these best practices: Prompt design fundamentals **Be specific in your instructions**: Craft clear and concise instructions that leave minimal room for misinterpretation. **Add a few examples to your prompt:** Use realistic few-shot examples to illustrate what you want to achieve. **Break it down step-by-step**: Divide complex tasks into manageable sub-goals, guiding the model through the process. **Specify the output format**: In your prompt, ask for the output to be in the format you want, like markdown, JSON, HTML and more. **Put your image first for single-image prompts**: While Gemini can handle image and text inputs in any order, for prompts containing a single image, it might perform better if that image (or video) is placed before the text prompt. However, for prompts that require images to be highly interleaved with texts to make sense, use whatever order is most natural. Troubleshooting your multimodal prompt **If the model is not drawing information from the relevant part of the image:** Drop hints with which aspects of the image you want the prompt to draw information from. **If the model output is too generic (not tailored enough to the image/video input):**At the start of the prompt, try asking the model to describe the image(s) or video before providing the task instruction, or try asking the model to refer to what's in the image. **To troubleshoot which part failed:** Ask the model to describe the image, or ask the model to explain its reasoning, to gauge the model's initial understanding. **If your prompt results in hallucinated content:** Try dialing down the temperature setting or asking the model for shorter descriptions so that it's less likely to extrapolate additional details. **Tuning the sampling parameters:** Experiment with different temperature settings and top-k selections to adjust the model's creativity.\n \n Be specific in your instructions Prompts have the most success when they are clear and detailed. If you have a\nspecific output in mind, it's better to include that requirement in the prompt\nto ensure you get the output you want. For this image of an airport board, asking the model to just \"describe this\nimage\" could generate a general description. If you need the model to parse the\ntime and city from the image, you can include that request directly in your prompt. Prompt Model response Describe this image. The image shows an airport arrivals and departures board. **Updated prompt** **Improved response** Parse the time and city from the airport board shown in this image into a list. 10:50 Moscow 11:05 Edinburgh 11:05 London 11:10 Bucharest 11:30 Kiev 11:35 Dublin 11:45 East Midlands 12:15 Sofia 12:30 London 12:30 Newcastle 12:40 St Petersburg 12:40 London 12:45 Manchester Add a few examples The Gemini model can accept multiple inputs which it can use as examples to understand the\noutput you want. Adding these examples can help the model identify the patterns and apply the\nrelationship between the given images and responses to the new example. This is also called\n\"few-shot\" learning. In the example below, the initial output is written in sentence form, and also contains the\ncountry (Brazil). Suppose you want the output in a different format or style, and you want\nonly the city, not the country. Adding few-shot examples to your prompt can steer the model\nto respond in the way you want. **Prompt** **Model response** Determine the city along with the landmark. The landmark is the Christ the Redeemer statue in Rio de Janeiro, Brazil. **Updated prompt** **Improved response** Determine the city along with the landmark. city: Rome, landmark: the Colosseum. city: Beijing, landmark: Forbidden City city: Rio de Janeiro, landmark: Christ the Redeemer statue Break it down step-by-step For complex tasks like the ones that require both visual understanding and\nreasoning, it can be helpful to split the task into smaller, more straightforward\nsteps. Alternatively, it could also be effective if you\ndirectly ask the model to “think step by step” in your prompt. Prompt Model response When will I run out of toilet paper? Soon, you only have 3 rolls left. **Updated prompt** **Improved response** 1. First, count how many toilet paper rolls are in this picture. 2. Then, determine how much toilet paper a typical person uses per day. 3. Calculate how long these rolls of toilet paper will last. 1. There are 3 rolls of toilet paper in this picture. 2. A typical person uses about 20 sheets of toilet paper per day. 3. If each roll contains 200 sheets, then each roll will last for about 10 days. Therefore, the 3 rolls will last for about a month. Math problems or other types of word problems are great candidates for asking\nthe model to think step-by-step. **Prompt** **Response** What is the 4th term in the sequence? -135\n The response from the model is incorrect. Some ways to improve this is to ask\nthe model to parse the problem before answering the prompt. **Prompt** **Response** Parse the formula in the image first. Then based on the formula, answer \"what's the 4th term in the sequence?\". *Click to expand the result* $$ b(n) = b(n-1) * (-3) $$ $$ b(1) = 15 $$ Substitute n = 4 into the formula: $$ b(4) = b(4-1) * (-3) $$ $$ b(4) = b(3) * (-3) $$ We don't know the value of b(3), so substitute n = 3 into the formula: $$ b(3) = b(3-1) * (-3) $$ $$ b(3) = b(2) * (-3) $$ We don't know the value of b(2), so substitute n = 2 into the formula: $$ b(2) = b(2-1) * (-3) $$ $$ b(2) = b(1) * (-3) $$ We know the value of b(1) is 15, so substitute it into the formula: $$ b(2) = 15 * (-3) $$ $$ b(2) = -45 $$ Now that we know the value of b(2), substitute it into the formula for b(3): $$ b(3) = b(2) * (-3) $$ $$ b(3) = -45 * (-3) $$ $$ b(3) = 135 $$ Now that we know the value of b(3), substitute it into the formula for b(4): $$ b(4) = b(3) * (-3) $$ $$ b(4) = 135 * (-3) $$ $$ b(4) = -405 $$ Therefore, the 4th term in the sequence is -405. This model response is correct - now to make the response even more streamlined,\nyou can ask the model to to think step-by-step. **Updated prompt** **Improved response** What is the 4th term in the sequence? Think step by step. The first term is 15. The second term is b(1) * (-3) = 15 * (-3) = -45. The third term is b(2) * (-3) = -45 * (-3) = 135. The fourth term is b(3) * (-3) = 135 * (-3) = -405. Specify the output format A common problem is the need for model output to be in a certain format\n(e.g. markdown, JSON, HTML), especially if the model output needs to\nbe ingested by a downstream task. You can try to produce output in that format\nby instructing the model to do so within the prompt. Below are two examples: Prompt Model response Parse the table in this image into markdown format | Subject | Status | Time | Start date | Due on | | ------- | ------ | ---- | ---------- | ------ | | Math | Done | 1.5 hrs | 11/29/2023 | 12/1/2023 | | Geography | Done | 30 min | 12/2/2023 | 12/4/2023 | | Physics | In progress | 2 hrs | 12/3/2023 | 12/5/2023 | | Biology | Not started | 6 hrs | 11/2/2016 | 12/6/2023 | **Prompt** **Model response** Provide a list of all the following attributes: ingredients, type of cuisine, vegetarian or not, in JSON format ```json { \"ingredients\": [ \"rice\", \"shrimp\", \"clams\", \"mussels\", \"peas\", \"tomatoes\", \"onions\", \"garlic\", \"olive oil\", \"paprika\", \"salt\", \"pepper\" ], \"type of cuisine\": \"Spanish\", \"vegetarian\": false } ``` Put your image first for single-image prompts While Gemini can interpret image and text in any order within a prompt, placing\na single image before the text prompt might lead to better results.\nIn the following samples, you'll notice the image comes first before the text in\neach prompt. Troubleshooting your multimodal prompt You might need to troubleshoot your prompt if you are not getting a helpful\nresponse. Here are a few strategies you could try. If the model is not drawing information from the relevant part of the image To get a more specific response, you can point out which aspects of the image\nyou want the prompt to draw information from to inform its response. Prompt Model response How many days will these diapers last a baby? The diapers will last for 198 days before they run out. **Updated prompt** **Improved response** How long will these diapers last before I run out? Use the weight shown on the box to determine the child's age, and use the total number of diapers in the box. Divide the total number by how many diapers the child goes through per day. The box contains 198 diapers. The box states the diapers are for a child weighing 22-37 lbs. The average child in this weight range is likely between 1 and 2 years old. A 2-year-old typically goes through 6 diapers per day, therefore, the diapers will last around 33 days (198/6). If the model output is too generic and not tailored enough to the image input To help the model tailor its response to the image(s), try asking it to describe\nthe images before performing its reasoning task. Prompt Model response What is in common between these images? All four images are examples of landscape photography. **Updated prompt** **Improved response** First, describe what's in each image in detail. What's in common between these images? The first image shows a person packing a suitcase. The second image shows an empty hallway in a shopping mall. The third image shows a roll of toilet paper. The fourth image shows a dark and stormy sea. The commonality between these images is that they are all examples of liminal spaces. Liminal spaces are places or situations that are in between two other places or situations. They are often characterized by a sense of uncertainty or ambiguity. The first image shows the person in between being at home and being on a trip. The second image shows the hallway in between two stores. The third image is of toilet paper, which can represent a bathroom. A bathroom is a transitional space between private\n and public realms. It's a place where we prepare ourselves to enter or leave the outside world. The fourth image shows the sea in between being calm and being stormy. Liminal spaces can be both exciting and unsettling. They can be a place of new beginning or a place of endings. They can be a place of reflection or a place of action. You can also try explicitly asking the model to refer to what's in the image. **Updated prompt** **Improved response** What is in common between these images? Refer to what's in the images in your response. All of the images are related to travel. The first image shows a person packing a suitcase, the second image shows\n an empty hallway in a shopping mall, the third image shows a stack of toilet paper, and the fourth image shows a\n dark and stormy sea. These images are all related to travel because they are all things that people need or use when\n they travel. The first image shows a person packing a suitcase, which is something that people do when they are\n going on a trip. The second image shows an empty hallway in a shopping mall, which is a place where people\n often go to buy things for their trips. The third image shows a stack of toilet paper, which is something\n that people often use when they are traveling. The fourth image shows a dark and stormy sea, which is\n something that people often encounter when they are traveling. The same tips work for creative output from images. In the following example with\nthe rabbit, explicitly asking the model to include aspects from the image can\nimprove the output. Prompt Model response Can you write me a poem about this image? Little bunny, so soft and brown,\n\n Hopping through the field, up and down.\n\n Your ears so long, your tail so small,\n\n You're the cutest creature of them all. You nibble on the grass, so green and sweet,\n\n And hop away when you see me.\n\n But I'll always be your friend,\n\n Little bunny, until the very end. **Updated prompt** **Improved response** Can you write me a descriptive and dramatic poem about this image and include the location? Little bunny on the green,\n\n Ears so long, so keen.\n\n What do you see out there,\n\n In the distance, where you stare? Is it the ocean blue,\n\n Sparkling in the sun's hue?\n\n Or the waves that crash and roar,\n\n A rhythm that you adore? Little bunny, tell me true,\n\n What captures your attention so?\n\n Is it the salty breeze,\n\n Or the seagulls' cries that please? Perhaps it's the vastness of it all,\n\n A world so big and small.\n\n A place where dreams can roam,\n\n And adventures can be sown. Little bunny, I wonder what you dream,\n\n As you sit on the grass, so serene.\n\n Do you yearn to explore the deep,\n\n Or stay on land, where you can leap? Whatever it may be, little bunny,\n\n Keep that spark of wonder burning brightly.\n\n For in your dreams and aspirations,\n\n Lies a world waiting for your creation. Troubleshooting which part of the prompt failed It can be hard to know whether a prompt failed because the model\ndidn't **understand the image** to begin with, or if it did understand the image\nbut did not perform the correct **reasoning steps** afterward.\nTo disambiguate between those reasons, ask the model to describe what's in the image. In the following example, if the model responds with a snack that seems surprising\nwhen paired with tea (e.g. popcorn), you can first troubleshoot to determine\nwhether the model correctly recognized that the image contains tea. Prompt Prompt for troubleshooting What's a snack I can make in 1 minute that would go well with this? Describe what's in this image. Another strategy is to ask the model to explain its reasoning. That can help you\nnarrow down which part of the reasoning broke down, if any. Prompt Prompt for troubleshooting What's a snack I can make in 1 minute that would go well with this? What's a snack I can make in 1 minute that would go well with this? Please explain why. What's next Try writing your own multimodal prompts using [Google AI\nStudio](http://aistudio.google.com). For information on using the Gemini Files API for\nuploading media files and including them in your prompts, see the\n[Vision](/gemini-api/docs/vision), [Audio](/gemini-api/docs/audio), and\n[Document processing](/gemini-api/docs/document-processing) guides. For more guidance on prompt design, like tuning sampling parameters, see the\n[Prompt strategies](/gemini-api/docs/prompting-strategies) page. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 23226, "slov": 3782, "odkazu": 129, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:31", "sha256": "2cea3fe73b7347561199a7fdb0af0ebbf87cbd78ecea5ef0282edaecd9ae55cd", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "http://aistudio.google.com/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/flex-inference", "titulek": "Flex inference | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Flex inference", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/flex-inference", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Flex inference  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/flex-inference", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Flex inference"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Flex inference", "item": "https://ai.google.dev/gemini-api/docs/generate-content/flex-inference"}]}], "drobecky": ["Generate Content API", "Flex inference"], "osnova": [{"uroven": 1, "text": "Flex inference"}, {"uroven": 2, "text": "How to use Flex"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How Flex inference works"}, {"uroven": 3, "text": "Key benefits"}, {"uroven": 3, "text": "Use cases"}, {"uroven": 3, "text": "Rate limits"}, {"uroven": 3, "text": "Sheddable capacity"}, {"uroven": 3, "text": "Error codes"}, {"uroven": 3, "text": "Client responsibility"}, {"uroven": 2, "text": "Adjust timeout windows"}, {"uroven": 3, "text": "Per-request timeouts"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Global timeouts"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 2, "text": "Implement retries"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "Supported models"}, {"uroven": 2, "text": "What's next"}], "markdown": "Flex inference Description: Learn how to optimize costs with the Flex inference tier\n\n The Gemini Flex API is an inference tier that offers a 50% cost reduction\ncompared to standard rates, in exchange for variable latency and best-effort\navailability. It's designed for latency-tolerant workloads that require\nsynchronous processing but don't need the real-time performance of the standard\nAPI. How to use Flex To use the Flex tier, specify the `service_tier` as `flex` in the\nrequest body. By default, requests use the standard tier if this field is\nomitted. Python`from google import genai client = genai.Client() try: response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Analyze this dataset for trends...\", config={\"service_tier\": \"flex\"}, ) print(response.text) except Exception as e: print(f\"Flex request failed: {e}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI({}); async function main() { try { const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Analyze this dataset for trends...\", config: { serviceTier: \"flex\" }, }); console.log(response.text); } catch (e) { console.log(`Flex request failed: ${e}`); } } await main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } result, err := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", genai.Text(\"Analyze this dataset for trends...\"), &genai.GenerateContentConfig{ ServiceTier: \"flex\", }, ) if err != nil { log.Printf(\"Flex request failed: %v\", err) return } fmt.Println(result.Text()) }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{ \"contents\": [{ \"parts\":[{\"text\": \"Summarize the latest research on quantum computing.\"}] }], \"service_tier\": \"flex\" }'` How Flex inference works Gemini Flex inference bridges the gap between the standard API and the 24-hour\nturnaround of the [Batch API](/gemini-api/docs/batch-api). It utilizes off-peak,\n\"sheddable\" compute capacity to provide a cost-effective solution for background\ntasks and sequential workflows. Feature Flex Priority Standard Batch **Pricing** 50% discount 75-100% more than Standard Full price 50% discount **Latency** Minutes (1–15 min target) Low (Seconds) Seconds to minutes Up to 24 hours **Reliability** Best-effort (Sheddable) High (Non-sheddable) High / Medium-high High (for throughput) **Interface** Synchronous Synchronous Synchronous Asynchronous Key benefits **Cost efficiency**: Substantial savings for non-production evals, background agents, and data enrichment. **Low friction**: No need to manage batch objects, job IDs, or polling; simply add a single parameter to your existing requests. **Synchronous workflows**: Ideal for sequential API chains where the next request depends on the output of the previous one, making it more flexible than Batch for agentic workflows. Use cases **Offline evaluations**: Running \"LLM-as-a-judge\" regression tests or leaderboards. **Background agents**: Sequential tasks like CRM updates, profile building, or content moderation where minutes of delay are acceptable. **Budget-constrained research**: Academic experiments that require high token volume on a limited budget. Rate limits Flex inference traffic counts towards your general [rate limits](https://aistudio.google.com/rate-limit); it doesn't\noffer extended rate limits like the [Batch API](/gemini-api/docs/batch-api). Sheddable capacity Flex traffic is treated with lower priority. If there is a spike in\nstandard traffic, Flex requests may be preempted or evicted to ensure capacity\nfor high-priority users. If you're looking for high-priority inference, check\n[Priority inference](/gemini-api/docs/priority-inference) Error codes When Flex capacity is unavailable or the system is congested, the API will\nreturn standard error codes: **503 Service Unavailable**: The system is currently at capacity. **429 Too Many Requests**: Rate limits or resource exhaustion. Client responsibility **No server-side fallback**: To prevent unexpected charges, the system won't\nautomatically upgrade a Flex request to the Standard tier if Flex capacity is\nfull. **Retries**: You must implement your own client-side retry logic with\nexponential backoff. **Timeouts**: Because Flex requests may sit in a queue, we recommend\nincreasing client-side timeouts to 10 minutes or more to avoid premature\nconnection closure. Adjust timeout windows You can configure per-request timeouts for the REST API and client libraries,\nand global timeouts only when using the client libraries. Always ensure your client-side timeout covers the intended server patience\nwindow (e.g., 600s+ for Flex wait queues). The SDKs expect timeout values in\nmilliseconds. Per-request timeouts Python`from google import genai client = genai.Client() try: response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"why is the sky blue?\", config={ \"service_tier\": \"flex\", \"http_options\": {\"timeout\": 900000} }, ) except Exception as e: print(f\"Flex request failed: {e}\") # Example with streaming try: response = client.models.generate_content_stream( model=\"gemini-3.8-flash\", contents=[\"List 5 ideas for a sci-fi movie.\"], config={ \"service_tier\": \"flex\", \"http_options\": {\"timeout\": 60000} } # Per-request timeout for the streaming operation ) for chunk in response: print(chunk.text, end=\"\") except Exception as e: print(f\"An error occurred during streaming: {e}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; const client = new GoogleGenAI({}); async function main() { try { const response = await client.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"why is the sky blue?\", config: { serviceTier: \"flex\", httpOptions: {timeout: 900000} }, }); } catch (e) { console.log(`Flex request failed: ${e}`); } // Example with streaming try { const response = await client.models.generateContentStream({ model: \"gemini-3.8-flash\", contents: [\"List 5 ideas for a sci-fi movie.\"], config: { serviceTier: \"flex\", httpOptions: {timeout: 60000} }, }); for await (const chunk of response.stream) { process.stdout.write(chunk.text()); } } catch (e) { console.log(`An error occurred during streaming: ${e}`); } } await main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"time\" \"google.golang.org/api/iterator\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() timeoutCtx, cancel := context.WithTimeout(ctx, 900*time.Second) defer cancel() _, err = client.Models.GenerateContent( timeoutCtx, \"gemini-3.8-flash\", genai.Text(\"why is the sky blue?\"), &genai.GenerateContentConfig{ ServiceTier: \"flex\", }, ) if err != nil { fmt.Printf(\"Flex request failed: %v\\n\", err) } // Example with streaming streamTimeoutCtx, streamCancel := context.WithTimeout(ctx, 60*time.Second) defer streamCancel() iter := client.Models.GenerateContentStream( streamTimeoutCtx, \"gemini-3.8-flash\", genai.Text(\"List 5 ideas for a sci-fi movie.\"), &genai.GenerateContentConfig{ ServiceTier: \"flex\", }, ) for { response, err := iter.Next() if err == iterator.Done { break } if err != nil { fmt.Printf(\"An error occurred during streaming: %v\\n\", err) break } fmt.Print(response.Candidates[0].Content.Parts[0]) } }` RESTWhen making REST calls, you can control timeouts using a combination of HTTP\nheaders and `curl` options: **`X-Server-Timeout` header (server-side timeout)**: This header suggests a\npreferred timeout duration (default 600s) to the Gemini API server. The server\nwill attempt to respect this, but it's not guaranteed. The value should be in\nseconds. **`--max-time` in `curl` (Client-Side Timeout)**: The `curl --max-time\n` option sets a hard limit on the total time (in seconds) that `curl`\nwill wait for the entire operation to complete. This is a client-side safeguard. `# Set a server timeout hint of 120 seconds and a client-side curl timeout of 125 seconds. curl --max-time 125 \\ -X POST \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -H \"X-Server-Timeout: 120\" \\ -d '{ \"contents\": [{ \"parts\":[{\"text\": \"Summarize the latest research on quantum computing.\"}] }], \"service_tier\": \"flex\" }'` Global timeouts If you want all API calls made through a specific `genai.Client` instance\n(client libraries only) to have a default timeout, you can configure this when\ninitializing the client using `http_options` and `genai.types.HttpOptions`. Python`from google import genai from google.genai import types global_timeout_ms = 120000 client_with_global_timeout = genai.Client( http_options=types.HttpOptions(timeout=global_timeout_ms) ) try: # Calling generate_content using global timeout... response = client_with_global_timeout.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Summarize the history of AI development since 2000.\", config={\"service_tier\": \"flex\"}, ) print(response.text) # A per-request timeout will *override* the global timeout for that specific call. shorter_timeout = 30000 response = client_with_global_timeout.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Provide a very brief definition of machine learning.\", config={ \"service_tier\": \"flex\", \"http_options\":{\"timeout\": shorter_timeout} } # Overrides the global timeout ) print(response.text) except TimeoutError: print( f\"A GenerateContent call timed out. Check if the global or per-request timeout was exceeded.\" ) except Exception as e: print(f\"An error occurred: {e}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; const globalTimeoutMs = 120000; const clientWithGlobalTimeout = new GoogleGenAI({httpOptions: {timeout: globalTimeoutMs}}); async function main() { try { // Calling generate_content using global timeout... const response1 = await clientWithGlobalTimeout.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Summarize the history of AI development since 2000.\", config: { serviceTier: \"flex\" }, }); console.log(response1.text()); // A per-request timeout will *override* the global timeout for that specific call. const shorterTimeout = 30000; const response2 = await clientWithGlobalTimeout.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Provide a very brief definition of machine learning.\", config: { serviceTier: \"flex\", httpOptions: {timeout: shorterTimeout} } // Overrides the global timeout }); console.log(response2.text()); } catch (e) { if (e.name === 'TimeoutError' || e.message?.includes('timeout')) { console.log( \"A GenerateContent call timed out. Check if the global or per-request timeout was exceeded.\" ); } else { console.log(`An error occurred: ${e}`); } } } await main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"time\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() model := client.GenerativeModel(\"gemini-3.8-flash\") // Go uses context for timeouts, not client options. // Set a default timeout for requests. globalTimeout := 120 * time.Second fmt.Printf(\"Using default timeout of %v seconds.\\n\", globalTimeout.Seconds()) fmt.Println(\"Calling generate_content (using default timeout)...\") ctx1, cancel1 := context.WithTimeout(ctx, globalTimeout) defer cancel1() resp1, err := model.GenerateContent(ctx1, genai.Text(\"Summarize the history of AI development since 2000.\"), &genai.GenerateContentConfig{ServiceTier: \"flex\"}) if err != nil { log.Printf(\"Request 1 failed: %v\", err) } else { fmt.Println(\"GenerateContent 1 successful.\") fmt.Println(resp1.Text()) } // A different timeout can be used for other requests. shorterTimeout := 30 * time.Second fmt.Printf(\"\\nCalling generate_content with a shorter timeout of %v seconds...\\n\", shorterTimeout.Seconds()) ctx2, cancel2 := context.WithTimeout(ctx, shorterTimeout) defer cancel2() resp2, err := model.GenerateContent(ctx2, genai.Text(\"Provide a very brief definition of machine learning.\"), &genai.GenerateContentConfig{ ServiceTier: \"flex\", }) if err != nil { log.Printf(\"Request 2 failed: %v\", err) } else { fmt.Println(\"GenerateContent 2 successful.\") fmt.Println(resp2.Text()) } }` Implement retries Because Flex is sheddable and fails with 503 errors, here is an example of\noptionally implementing retry logic to continue with failed requests: Python`import time from google import genai client = genai.Client() def call_with_retry(max_retries=3, base_delay=5): for attempt in range(max_retries): try: return client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Analyze this batch statement.\", config={\"service_tier\": \"flex\"}, ) except Exception as e: # Check for 503 Service Unavailable or 429 Rate Limits print(e.code) if attempt < max_retries - 1: delay = base_delay * (2 ** attempt) # Exponential Backoff print(f\"Flex busy, retrying in {delay}s...\") time.sleep(delay) else: # Fallback to standard on last strike (Optional) print(\"Flex exhausted, falling back to Standard...\") return client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Analyze this batch statement.\" ) # Usage response = call_with_retry() print(response.text)` JavaScript`import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI({}); async function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function callWithRetry(maxRetries = 3, baseDelay = 5) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { console.log(`Attempt ${attempt + 1}: Calling Flex tier...`); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Analyze this batch statement.\", config: { serviceTier: 'flex' }, }); return response; } catch (e) { if (attempt < maxRetries - 1) { const delay = baseDelay * (2 ** attempt); console.log(`Flex busy, retrying in ${delay}s...`); await sleep(delay * 1000); } else { console.log(\"Flex exhausted, falling back to Standard...\"); return await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Analyze this batch statement.\", }); } } } } async function main() { const response = await callWithRetry(); console.log(response.text); } await main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"math\" \"time\" \"google.golang.org/genai\" ) func callWithRetry(ctx context.Context, client *genai.Client, maxRetries int, baseDelay time.Duration) (*genai.GenerateContentResponse, error) { modelName := \"gemini-3.8-flash\" content := genai.Text(\"Analyze this batch statement.\") flexConfig := &genai.GenerateContentConfig{ ServiceTier: \"flex\", } for attempt := 0; attempt < maxRetries; attempt++ { log.Printf(\"Attempt %d: Calling Flex tier...\", attempt+1) resp, err := client.Models.GenerateContent(ctx, modelName, content, flexConfig) if err == nil { return resp, nil } log.Printf(\"Attempt %d failed: %v\", attempt+1, err) if attempt < maxRetries-1 { delay := time.Duration(float64(baseDelay) * math.Pow(2, float64(attempt))) log.Printf(\"Flex busy, retrying in %v...\", delay) time.Sleep(delay) } else { log.Println(\"Flex exhausted, falling back to Standard...\") return client.Models.GenerateContent(ctx, modelName, content) } } return nil, fmt.Errorf(\"retries exhausted\") // Should not be reached } func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() resp, err := callWithRetry(ctx, client, 3, 5*time.Second) if err != nil { log.Fatalf(\"Failed after retries: %v\", err) } fmt.Println(resp.Text()) }` Pricing Flex inference is priced at 50% of the [standard API](/gemini-api/docs/pricing)\nand billed per token. Supported models The following models support Flex inference: Model Flex inference [Gemini 3.8 Flash](/gemini-api/docs/models/gemini-3.8-flash) ✔️ [Gemini 3.7 Flash](/gemini-api/docs/models/gemini-3.7-flash) ✔️ [Gemini 3.6 Flash](/gemini-api/docs/models/gemini-3.6-flash) ✔️ [Gemini 3.5 Flash-Lite](/gemini-api/docs/models/gemini-3.5-flash-lite) ✔️ [Gemini 3.5 Flash](/gemini-api/docs/models/gemini-3.5-flash) ✔️ [Gemini 3.1 Flash-Lite](/gemini-api/docs/models/gemini-3.1-flash-lite) ✔️ [Gemini 3.1 Pro Preview](/gemini-api/docs/models/gemini-3.1-pro-preview) ✔️ [Gemini 3 Flash Preview](/gemini-api/docs/models/gemini-3-flash-preview) ✔️ [Gemini 3 Pro Image Preview](/gemini-api/docs/models/gemini-3-pro-image) ✔️ [Gemini 2.5 Pro](/gemini-api/docs/models/gemini-2.5-pro) ✔️ [Gemini 2.5 Flash](/gemini-api/docs/models/gemini-2.5-flash) ✔️ [Gemini 2.5 Flash Image](/gemini-api/docs/models/gemini-2.5-flash-image) ✔️ [Gemini 2.5 Flash-Lite](/gemini-api/docs/models/gemini-2.5-flash-lite) ✔️ What's next Read about Gemini's other [inference and optimization](/gemini-api/docs/optimization) options: [Priority inference](/gemini-api/docs/priority-inference) for ultra-low latency. [Batch API](/gemini-api/docs/batch-api) for asynchronous processing within 24 hours. [Context caching](/gemini-api/docs/caching) for reduced input token costs. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 17571, "slov": 2280, "odkazu": 138, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:09", "sha256": "bebc1b548ba8b26818e23c155f28738f350b9bdce2a92771081ef8a895fb7777", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/rate-limit", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/function-calling", "titulek": "Function calling with the Gemini API | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Function calling with the Gemini API", "popis": "Get started started using Function Calling with the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/function-calling", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Function calling with the Gemini API  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Get started started using Function Calling with the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/function-calling", "og:image": "https://ai.google.dev/static/site-assets/images/function-calling.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Function calling with the Gemini API"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Function calling with the Gemini API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/function-calling"}]}], "drobecky": ["Generate Content API", "Function calling with the Gemini API"], "osnova": [{"uroven": 1, "text": "Function calling with the Gemini API"}, {"uroven": 3, "text": "Schedule Meeting"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Get Weather"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Create Chart"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How function calling works"}, {"uroven": 3, "text": "Step 1: Define a function declaration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Step 2: Call the model with function declarations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Step 3: Execute set_light_values function code"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Step 4: Create user friendly response with function result and call the model again"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Function declarations"}, {"uroven": 2, "text": "Function calling with thinking models"}, {"uroven": 3, "text": "Managing conversation history manually"}, {"uroven": 4, "text": "Gemini 3 thought signatures"}, {"uroven": 5, "text": "Inspecting thought signatures"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Parallel function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Compositional function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Function calling modes"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Automatic function calling (Python only)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Automatic function schema declaration"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Multi-tool use: Combine built-in tools with function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 2, "text": "Multimodal function responses"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Function calling with Structured output"}, {"uroven": 2, "text": "Model context protocol (MCP)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Limitations with built-in MCP support"}, {"uroven": 2, "text": "Supported models"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Workarounds for pre-tool text requirements"}, {"uroven": 3, "text": "Preferred workaround: Wrap working notes in a dedicated function call"}, {"uroven": 2, "text": "Notes and limitations"}], "markdown": "Function calling with the Gemini API Function calling lets you connect models to external tools and APIs.\nInstead of generating text responses, the model determines when to call specific\nfunctions and provides the necessary parameters to execute real-world actions.\nThis allows the model to act as a bridge between natural language and real-world\nactions and data. Function calling has 3 primary use cases: **Take Actions:** Interact with external systems using APIs, such as\nscheduling appointments, creating invoices, sending emails, or controlling\nsmart home devices. **Augment Knowledge:** Access information from external sources like\ndatabases, APIs, and knowledge bases. **Extend Capabilities:** Use external tools to perform computations and\nextend the limitations of the model, such as using a calculator or creating\ncharts. You can browse examples of these use cases below: Schedule Meeting This example shows how to define a function that schedules a meeting with attendees at a specific time, allowing the model to parse user requests and return structured arguments to trigger actions in external systems. Python`from google import genai from google.genai import types # Define the function declaration for the model schedule_meeting_function = { \"name\": \"schedule_meeting\", \"description\": \"Schedules a meeting with specified attendees at a given time and date.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"attendees\": { \"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"List of people attending the meeting.\", }, \"date\": { \"type\": \"string\", \"description\": \"Date of the meeting (e.g., '2024-07-29')\", }, \"time\": { \"type\": \"string\", \"description\": \"Time of the meeting (e.g., '15:00')\", }, \"topic\": { \"type\": \"string\", \"description\": \"The subject or topic of the meeting.\", }, }, \"required\": [\"attendees\", \"date\", \"time\", \"topic\"], }, } # Configure the client and tools client = genai.Client() tools = types.Tool(function_declarations=[schedule_meeting_function]) config = types.GenerateContentConfig(tools=[tools]) # Send request with function declarations response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning.\", config=config, ) # Check for a function call if response.candidates[0].content.parts[0].function_call: function_call = response.candidates[0].content.parts[0].function_call print(f\"Function to call: {function_call.name}\") print(f\"ID: {function_call.id}\") print(f\"Arguments: {function_call.args}\") # In a real app, you would call your function here: # result = schedule_meeting(**function_call.args) else: print(\"No function call found in the response.\") print(response.text)` JavaScript`import { GoogleGenAI, Type } from '@google/genai'; // Configure the client const ai = new GoogleGenAI({}); // Define the function declaration for the model const scheduleMeetingFunctionDeclaration = { name: 'schedule_meeting', description: 'Schedules a meeting with specified attendees at a given time and date.', parameters: { type: Type.OBJECT, properties: { attendees: { type: Type.ARRAY, items: { type: Type.STRING }, description: 'List of people attending the meeting.', }, date: { type: Type.STRING, description: 'Date of the meeting (e.g., \"2024-07-29\")', }, time: { type: Type.STRING, description: 'Time of the meeting (e.g., \"15:00\")', }, topic: { type: Type.STRING, description: 'The subject or topic of the meeting.', }, }, required: ['attendees', 'date', 'time', 'topic'], }, }; // Send request with function declarations const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.', config: { tools: [{ functionDeclarations: [scheduleMeetingFunctionDeclaration] }], }, }); // Check for function calls in the response if (response.functionCalls && response.functionCalls.length > 0) { const functionCall = response.functionCalls[0]; // Assuming one function call console.log(`Function to call: ${functionCall.name}`); console.log(`ID: ${functionCall.id}`); console.log(`Arguments: ${JSON.stringify(functionCall.args)}`); // In a real app, you would call your actual function here: // const result = await scheduleMeeting(functionCall.args); } else { console.log(\"No function call found in the response.\"); console.log(response.text); }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"role\": \"user\", \"parts\": [ { \"text\": \"Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.\" } ] } ], \"tools\": [ { \"functionDeclarations\": [ { \"name\": \"schedule_meeting\", \"description\": \"Schedules a meeting with specified attendees at a given time and date.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"attendees\": { \"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"List of people attending the meeting.\" }, \"date\": { \"type\": \"string\", \"description\": \"Date of the meeting (e.g., '2024-07-29')\" }, \"time\": { \"type\": \"string\", \"description\": \"Time of the meeting (e.g., '15:00')\" }, \"topic\": { \"type\": \"string\", \"description\": \"The subject or topic of the meeting.\" } }, \"required\": [\"attendees\", \"date\", \"time\", \"topic\"] } } ] } ] }'` Get Weather This example shows how to define a function that retrieves temperature data for a location, enabling the model to call external APIs to answer queries requiring real-time or external information. Python`from google import genai from google.genai import types # Define the function declaration for the model weather_function = { \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": { \"type\": \"string\", \"description\": \"The city name, e.g. San Francisco\", }, }, \"required\": [\"location\"], }, } # Configure the client and tools client = genai.Client() tools = types.Tool(function_declarations=[weather_function]) config = types.GenerateContentConfig(tools=[tools]) # Send request with function declarations response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"What's the temperature in London?\", config=config, ) # Check for a function call if response.candidates[0].content.parts[0].function_call: function_call = response.candidates[0].content.parts[0].function_call print(f\"Function to call: {function_call.name}\") print(f\"ID: {function_call.id}\") print(f\"Arguments: {function_call.args}\") # In a real app, you would call your function here: # result = get_current_temperature(**function_call.args) else: print(\"No function call found in the response.\") print(response.text)` JavaScript`import { GoogleGenAI, Type } from '@google/genai'; // Configure the client const ai = new GoogleGenAI({}); // Define the function declaration for the model const weatherFunctionDeclaration = { name: 'get_current_temperature', description: 'Gets the current temperature for a given location.', parameters: { type: Type.OBJECT, properties: { location: { type: Type.STRING, description: 'The city name, e.g. San Francisco', }, }, required: ['location'], }, }; // Send request with function declarations const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: \"What's the temperature in London?\", config: { tools: [{ functionDeclarations: [weatherFunctionDeclaration] }], }, }); // Check for function calls in the response if (response.functionCalls && response.functionCalls.length > 0) { const functionCall = response.functionCalls[0]; // Assuming one function call console.log(`Function to call: ${functionCall.name}`); console.log(`ID: ${functionCall.id}`); console.log(`Arguments: ${JSON.stringify(functionCall.args)}`); // In a real app, you would call your actual function here: // const result = await getCurrentTemperature(functionCall.args); } else { console.log(\"No function call found in the response.\"); console.log(response.text); }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"role\": \"user\", \"parts\": [ { \"text\": \"What'\\''s the temperature in London?\" } ] } ], \"tools\": [ { \"functionDeclarations\": [ { \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": { \"type\": \"string\", \"description\": \"The city name, e.g. San Francisco\" } }, \"required\": [\"location\"] } } ] } ] }'` Create Chart This example shows how to define a function that generates a bar chart from structured data, demonstrating how the model can use external tools to perform computations or create visual assets: Python`import os from google import genai from google.genai import types # Define the function declaration for the model create_chart_function = { \"name\": \"create_bar_chart\", \"description\": \"Creates a bar chart given a title, labels, and corresponding values.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"title\": { \"type\": \"string\", \"description\": \"The title for the chart.\", }, \"labels\": { \"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"List of labels for the data points (e.g., ['Q1', 'Q2', 'Q3']).\", }, \"values\": { \"type\": \"array\", \"items\": {\"type\": \"number\"}, \"description\": \"List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).\", }, }, \"required\": [\"title\", \"labels\", \"values\"], }, } # Configure the client and tools client = genai.Client() tools = types.Tool(function_declarations=[create_chart_function]) config = types.GenerateContentConfig(tools=[tools]) # Send request with function declarations response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Create a bar chart titled 'Quarterly Sales' with data: Q1: 50000, Q2: 75000, Q3: 60000.\", config=config, ) # Check for a function call if response.candidates[0].content.parts[0].function_call: function_call = response.candidates[0].content.parts[0].function_call print(f\"Function to call: {function_call.name}\") print(f\"ID: {function_call.id}\") print(f\"Arguments: {function_call.args}\") # In a real app, you would call your function here using a charting library: # result = create_bar_chart(**function_call.args) else: print(\"No function call found in the response.\") print(response.text)` JavaScript`import { GoogleGenAI, Type } from '@google/genai'; // Configure the client const ai = new GoogleGenAI({}); // Define the function declaration for the model const createChartFunctionDeclaration = { name: 'create_bar_chart', description: 'Creates a bar chart given a title, labels, and corresponding values.', parameters: { type: Type.OBJECT, properties: { title: { type: Type.STRING, description: 'The title for the chart.', }, labels: { type: Type.ARRAY, items: { type: Type.STRING }, description: 'List of labels for the data points (e.g., [\"Q1\", \"Q2\", \"Q3\"]).', }, values: { type: Type.ARRAY, items: { type: Type.NUMBER }, description: 'List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).', }, }, required: ['title', 'labels', 'values'], }, }; // Send request with function declarations const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: \"Create a bar chart titled 'Quarterly Sales' with data: Q1: 50000, Q2: 75000, Q3: 60000.\", config: { tools: [{ functionDeclarations: [createChartFunctionDeclaration] }], }, }); // Check for function calls in the response if (response.functionCalls && response.functionCalls.length > 0) { const functionCall = response.functionCalls[0]; // Assuming one function call console.log(`Function to call: ${functionCall.name}`); console.log(`ID: ${functionCall.id}`); console.log(`Arguments: ${JSON.stringify(functionCall.args)}`); // In a real app, you would call your actual function here: // const result = await createBarChart(functionCall.args); } else { console.log(\"No function call found in the response.\"); console.log(response.text); }` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"role\": \"user\", \"parts\": [ { \"text\": \"Create a bar chart titled ''Quarterly Sales'' with data: Q1: 50000, Q2: 75000, Q3: 60000.\" } ] } ], \"tools\": [ { \"functionDeclarations\": [ { \"name\": \"create_bar_chart\", \"description\": \"Creates a bar chart given a title, labels, and corresponding values.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"title\": { \"type\": \"string\", \"description\": \"The title for the chart.\" }, \"labels\": { \"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"List of labels for the data points (e.g., [''Q1'', ''Q2'', ''Q3'']).\" }, \"values\": { \"type\": \"array\", \"items\": {\"type\": \"number\"}, \"description\": \"List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).\" } }, \"required\": [\"title\", \"labels\", \"values\"] } } ] } ] }'` How function calling works Function calling involves a structured interaction between your application, the\nmodel, and external functions. Here's a breakdown of the process: **Define function declaration:** Define the function declaration in your\napplication code. Function Declarations describe the function's name,\nparameters, and purpose to the model. **Call API with function declarations:** Send user prompt along with the\nfunction declaration(s) to the model. It analyzes the request and determines\nif a function call would be helpful. If so, it responds with a structured\nJSON object containing the function name, arguments, and a unique `id`\n(this `id` is now always returned by the API for Gemini 3 models*). **Execute function code (your responsibility):** The Model *doesn't*\nexecute the function itself. It's your application's responsibility to\nprocess the response and check for a function call. If\n **Yes**: Extract the name, args, and `id` of the function and execute\nthe corresponding function in your application. **No:** The model has provided a direct text response to the prompt\n(this flow is less emphasized in the example but is a possible outcome). **Create user friendly response:** If a function was executed, capture the\nresult and send it back to the model, ensuring you include the matching\n`id`, in a subsequent turn of the conversation. It will use the result to\ngenerate a final, user-friendly response that incorporates the information\nfrom the function call. This process can be repeated over multiple turns, allowing for complex\ninteractions and workflows. The model also supports calling multiple functions\nin a single turn (parallel function calling), in\nsequence (compositional function calling),\nand with built-in Gemini tools (multi-tool use). * **Always map function IDs:** Gemini 3 now always returns a unique\n`id` with every `functionCall`. Include this exact `id` in your\n`functionResponse` so the model can accurately map your result back to the\noriginal request. Step 1: Define a function declaration Define a function and its declaration within your application code that allows\nusers to set light values and make an API request. This function could call\nexternal services or APIs. Python`# Define a function that the model can call to control smart lights set_light_values_declaration = { \"name\": \"set_light_values\", \"description\": \"Sets the brightness and color temperature of a light.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": { \"type\": \"integer\", \"description\": \"Light level from 0 to 100. Zero is off and 100 is full brightness\", }, \"color_temp\": { \"type\": \"string\", \"enum\": [\"daylight\", \"cool\", \"warm\"], \"description\": \"Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.\", }, }, \"required\": [\"brightness\", \"color_temp\"], }, } # This is the actual function that would be called based on the model's suggestion def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]: \"\"\"Set the brightness and color temperature of a room light. (mock API). Args: brightness: Light level from 0 to 100. Zero is off and 100 is full brightness color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`. Returns: A dictionary containing the set brightness and color temperature. \"\"\" return {\"brightness\": brightness, \"colorTemperature\": color_temp}` JavaScript`import { Type } from '@google/genai'; // Define a function that the model can call to control smart lights const setLightValuesFunctionDeclaration = { name: 'set_light_values', description: 'Sets the brightness and color temperature of a light.', parameters: { type: Type.OBJECT, properties: { brightness: { type: Type.NUMBER, description: 'Light level from 0 to 100. Zero is off and 100 is full brightness', }, color_temp: { type: Type.STRING, enum: ['daylight', 'cool', 'warm'], description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.', }, }, required: ['brightness', 'color_temp'], }, }; /** * Set the brightness and color temperature of a room light. (mock API) * @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness * @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`. * @return {Object} A dictionary containing the set brightness and color temperature. */ function setLightValues(brightness, color_temp) { return { brightness: brightness, colorTemperature: color_temp }; }` Step 2: Call the model with function declarations Once you have defined your function declarations, you can prompt the model to\nuse them. It analyzes the prompt and function declarations and decides whether\nto respond directly or to call a function. If a function is called, the response\nobject will contain a function call suggestion. Python`from google.genai import types # Configure the client and tools client = genai.Client() tools = types.Tool(function_declarations=[set_light_values_declaration]) config = types.GenerateContentConfig(tools=[tools]) # Define user prompt contents = [ types.Content( role=\"user\", parts=[types.Part(text=\"Turn the lights down to a romantic level\")] ) ] # Send request with function declarations response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=contents, config=config, ) print(response.candidates[0].content.parts[0].function_call)` JavaScript`import { GoogleGenAI } from '@google/genai'; // Generation config with function declaration const config = { tools: [{ functionDeclarations: [setLightValuesFunctionDeclaration] }] }; // Configure the client const ai = new GoogleGenAI({}); // Define user prompt const contents = [ { role: 'user', parts: [{ text: 'Turn the lights down to a romantic level' }] } ]; // Send request with function declarations const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: contents, config: config }); console.log(response.functionCalls[0]);` The model then returns a `functionCall` object in an OpenAPI compatible\nschema specifying how to call one or more of the declared functions in order to\nrespond to the user's question. Python`id='8f2b1a3c' args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'` JavaScript`{ id: '8f2b1a3c', name: 'set_light_values', args: { brightness: 25, color_temp: 'warm' } }` Step 3: Execute set_light_values function code Extract the function call details from the model's response, parse the arguments\n, and execute the `set_light_values` function. 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}\")` 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)}`); }` Step 4: Create user friendly response with function result and call the model again Finally, send the result of the function execution back to the model so it can\nincorporate this information into its final response to the user. Python`from google import genai from google.genai import types # Create a function response part function_response_part = types.Part.from_function_response( name=tool_call.name, response={\"result\": result}, id=tool_call.id, ) # Append function call and result of the function execution to contents contents.append(response.candidates[0].content) # Append the content from the model's response. contents.append(types.Content(role=\"user\", parts=[function_response_part])) # Append the function response client = genai.Client() final_response = client.models.generate_content( model=\"gemini-3.8-flash\", config=config, contents=contents, ) print(final_response.text)` JavaScript`// Create a function response part const function_response_part = { name: tool_call.name, response: { result }, id: tool_call.id } // Append function call and result of the function execution to contents contents.push(response.candidates[0].content); contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] }); // Get the final response from the model const final_response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: contents, config: config }); console.log(final_response.text);` This completes the function calling flow. The model successfully used the\n`set_light_values` function to perform the request action of the user. Function declarations When you implement function calling in a prompt, you create a `tools` object,\nwhich contains one or more `function declarations`. You define functions using\nJSON, specifically with a [select subset](https://ai.google.dev/api/caching#Schema)\nof the [OpenAPI schema](https://spec.openapis.org/oas/v3.0.3#schemaw) format. A\nsingle function declaration can include the following parameters: `name` (string): A unique name for the function (`get_weather_forecast`,\n`send_email`). Use descriptive names without spaces or special characters\n(use underscores or camelCase). `description` (string): A clear and detailed explanation of the function's\npurpose and capabilities. This is crucial for the model to understand when\nto use the function. Be specific and provide examples if helpful (\"Finds\ntheaters based on location and optionally movie title which is currently\nplaying in theaters.\"). `parameters` (object): Defines the input parameters the function\nexpects.\n `type` (string): Specifies the overall data type, such as `object`. `properties` (object): Lists individual parameters, each with:\n `type` (string): The data type of the parameter, such as `string`,\n`integer`, `boolean, array`. `description` (string): A description of the parameter's purpose and\nformat. Provide examples and constraints (\"The city and state,\ne.g., 'San Francisco, CA' or a zip code e.g., '95616'.\"). `enum` (array, optional): If the parameter values are from a fixed\nset, use \"enum\" to list the allowed values instead of just describing\nthem in the description. This improves accuracy (\"enum\":\n[\"daylight\", \"cool\", \"warm\"]). `required` (array): An array of strings listing the parameter names that\nare mandatory for the function to operate. You can also construct `FunctionDeclarations` from Python functions directly using\n`types.FunctionDeclaration.from_callable(client=client, callable=your_function)`. Function calling with thinking models Gemini 3 and 2.5 series models use an internal [\"thinking\"](/gemini-api/docs/thinking) process to reason through requests. This\nsignificantly improves function calling performance,\nallowing the model to better determine when to call a function and which\nparameters to use. Because the Gemini API is stateless, models use\n[thought signatures](/gemini-api/docs/thought-signatures) to maintain context\nacross multi-turn conversations. This section covers advanced management of thought signatures and is only\nnecessary if you're manually constructing API requests (e.g., via REST) or\nmanipulating conversation history. **If you're using the [Google GenAI SDKs](/gemini-api/docs/libraries) (our\nofficial libraries), you don't need to manage this process**. The SDKs\nautomatically handle the necessary steps, as shown in the earlier\n[example](/gemini-api/docs/function-calling#step-4). Managing conversation history manually If you modify the conversation history manually, instead of sending the\n[complete previous response](/gemini-api/docs/function-calling#step-4) you\nmust correctly handle the `thought_signature` included in the model's turn. Follow these rules to ensure the model's context is preserved: Always send the `thought_signature` back to the model inside its original\n[`Part`](/api#request-body-structure). **Always include the exact `id` from the `function_call` in your\n`function_response` so the API can map the result to the correct request.** Don't merge a `Part` containing a signature with one that does not. This\nbreaks the positional context of the thought. Don't combine two `Parts` that both contain signatures, as the signature\nstrings cannot be merged. Gemini 3 thought signatures In Gemini 3, any [`Part`](/api#request-body-structure) of a model response\nmay contain a thought signature.\nWhile we generally recommend returning signatures from all `Part` types,\npassing back thought signatures is mandatory for function calling. Unless you\nare manipulating conversation history manually, the Google GenAI SDK will\nhandle thought signatures automatically. If you are manipulating conversation history manually, refer to the\n[Thoughts Signatures](/gemini-api/docs/thought-signatures) page for complete\nguidance and details on handling thought signatures for Gemini 3. Inspecting thought signatures While not necessary for implementation, you can inspect the response to see the\n`thought_signature` for debugging or educational purposes. Python`import base64 # After receiving a response from a model with thinking enabled # response = client.models.generate_content(...) # The signature is attached to the response part containing the function call part = response.candidates[0].content.parts[0] if part.thought_signature: print(base64.b64encode(part.thought_signature).decode(\"utf-8\"))` JavaScript`// After receiving a response from a model with thinking enabled // const response = await ai.models.generateContent(...) // The signature is attached to the response part containing the function call const part = response.candidates[0].content.parts[0]; if (part.thoughtSignature) { console.log(part.thoughtSignature); }` Learn more about limitations and usage of thought signatures, and about thinking\nmodels in general, on the [Thinking](/gemini-api/docs/thinking#signatures) page. Parallel function calling In addition to single turn function calling, you can also call multiple\nfunctions at once. Parallel function calling lets you execute multiple functions\nat once and is used when the functions are not dependent on each other. This is\nuseful in scenarios like gathering data from multiple independent sources, such\nas retrieving customer details from different databases or checking inventory\nlevels across various warehouses or performing multiple actions such as\nconverting your apartment into a disco. When the model initiates multiple function calls in a single turn, you don't\nneed to return the `function_result` objects in the same order that the\n`function_call` objects were received. The Gemini API maps each result back to\nits corresponding call using the `id` from the model's output. This lets you\nexecute your functions asynchronously and append the results to your list as\nthey complete. Python`power_disco_ball = { \"name\": \"power_disco_ball\", \"description\": \"Powers the spinning disco ball.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"power\": { \"type\": \"boolean\", \"description\": \"Whether to turn the disco ball on or off.\", } }, \"required\": [\"power\"], }, } start_music = { \"name\": \"start_music\", \"description\": \"Play some music matching the specified parameters.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"energetic\": { \"type\": \"boolean\", \"description\": \"Whether the music is energetic or not.\", }, \"loud\": { \"type\": \"boolean\", \"description\": \"Whether the music is loud or not.\", }, }, \"required\": [\"energetic\", \"loud\"], }, } dim_lights = { \"name\": \"dim_lights\", \"description\": \"Dim the lights.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"brightness\": { \"type\": \"number\", \"description\": \"The brightness of the lights, 0.0 is off, 1.0 is full.\", } }, \"required\": [\"brightness\"], }, }` JavaScript`import { Type } from '@google/genai'; const powerDiscoBall = { name: 'power_disco_ball', description: 'Powers the spinning disco ball.', parameters: { type: Type.OBJECT, properties: { power: { type: Type.BOOLEAN, description: 'Whether to turn the disco ball on or off.' } }, required: ['power'] } }; const startMusic = { name: 'start_music', description: 'Play some music matching the specified parameters.', parameters: { type: Type.OBJECT, properties: { energetic: { type: Type.BOOLEAN, description: 'Whether the music is energetic or not.' }, loud: { type: Type.BOOLEAN, description: 'Whether the music is loud or not.' } }, required: ['energetic', 'loud'] } }; const dimLights = { name: 'dim_lights', description: 'Dim the lights.', parameters: { type: Type.OBJECT, properties: { brightness: { type: Type.NUMBER, description: 'The brightness of the lights, 0.0 is off, 1.0 is full.' } }, required: ['brightness'] } };` Configure the function calling mode to allow using all of the specified tools.\nTo learn more, you can read about\n[configuring function calling](/gemini-api/docs/function-calling#function_calling_modes). Python`from google import genai from google.genai import types # Configure the client and tools client = genai.Client() house_tools = [ types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights]) ] config = types.GenerateContentConfig( tools=house_tools, automatic_function_calling=types.AutomaticFunctionCallingConfig( disable=True ), # Force the model to call 'any' function, instead of chatting. tool_config=types.ToolConfig( function_calling_config=types.FunctionCallingConfig(mode='ANY') ), ) chat = client.chats.create(model=\"gemini-3.8-flash\", config=config) response = chat.send_message(\"Turn this place into a party!\") # Print out each of the function calls requested from this single call print(\"Example 1: Forced function calling\") for fn in response.function_calls: args = \", \".join(f\"{key}={val}\" for key, val in fn.args.items()) print(f\"{fn.name}({args}) - ID: {fn.id}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; // Set up function declarations const houseFns = [powerDiscoBall, startMusic, dimLights]; const config = { tools: [{ functionDeclarations: houseFns }], // Force the model to call 'any' function, instead of chatting. toolConfig: { functionCallingConfig: { mode: 'any' } } }; // Configure the client const ai = new GoogleGenAI({}); // Create a chat session const chat = ai.chats.create({ model: 'gemini-3.8-flash', config: config }); const response = await chat.sendMessage({message: 'Turn this place into a party!'}); // Print out each of the function calls requested from this single call console.log(\"Example 1: Forced function calling\"); for (const fn of response.functionCalls) { const args = Object.entries(fn.args) .map(([key, val]) => `${key}=${val}`) .join(', '); console.log(`${fn.name}(${args}) - ID: ${fn.id}`); }` Each of the printed results reflects a single function call that the model has\nrequested. To send the results back, include the responses in the same order as\nthey were requested. The Python SDK supports [automatic function calling](/gemini-api/docs/function-calling#automatic_function_calling_python_only),\nwhich automatically converts Python functions to declarations, handles the\nfunction call execution and response cycle for you. Following is an example for\nthe disco use case. Python`from google import genai from google.genai import types # Actual function implementations def power_disco_ball_impl(power: bool) -> dict: \"\"\"Powers the spinning disco ball. Args: power: Whether to turn the disco ball on or off. Returns: A status dictionary indicating the current state. \"\"\" return {\"status\": f\"Disco ball powered {'on' if power else 'off'}\"} def start_music_impl(energetic: bool, loud: bool) -> dict: \"\"\"Play some music matching the specified parameters. Args: energetic: Whether the music is energetic or not. loud: Whether the music is loud or not. Returns: A dictionary containing the music settings. \"\"\" music_type = \"energetic\" if energetic else \"chill\" volume = \"loud\" if loud else \"quiet\" return {\"music_type\": music_type, \"volume\": volume} def dim_lights_impl(brightness: float) -> dict: \"\"\"Dim the lights. Args: brightness: The brightness of the lights, 0.0 is off, 1.0 is full. Returns: A dictionary containing the new brightness setting. \"\"\" return {\"brightness\": brightness} # Configure the client client = genai.Client() config = types.GenerateContentConfig( tools=[power_disco_ball_impl, start_music_impl, dim_lights_impl] ) # Make the request response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Do everything you need to this place into party!\", config=config, ) print(\"\\nExample 2: Automatic function calling\") print(response.text) # I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!` Compositional function calling Compositional or sequential function calling allows Gemini to chain multiple\nfunction calls together to fulfill a complex request. For example, to answer\n\"Get the temperature in my current location\", the Gemini API might first invoke\na `get_current_location()` function followed by a `get_weather()` function that\ntakes the location as a parameter. The following example demonstrates how to implement compositional function\ncalling using the Python SDK and automatic function calling. PythonThis example uses the automatic function calling feature of the\n`google-genai` Python SDK. The SDK automatically converts the Python\nfunctions to the required schema, executes the function calls when requested\nby the model, and sends the results back to the model to complete the task. `import os from google import genai from google.genai import types # Example Functions def get_weather_forecast(location: str) -> dict: \"\"\"Gets the current weather temperature for a given location.\"\"\" print(f\"Tool Call: get_weather_forecast(location={location})\") # TODO: Make API call print(\"Tool Response: {'temperature': 25, 'unit': 'celsius'}\") return {\"temperature\": 25, \"unit\": \"celsius\"} # Dummy response def set_thermostat_temperature(temperature: int) -> dict: \"\"\"Sets the thermostat to a desired temperature.\"\"\" print(f\"Tool Call: set_thermostat_temperature(temperature={temperature})\") # TODO: Interact with a thermostat API print(\"Tool Response: {'status': 'success'}\") return {\"status\": \"success\"} # Configure the client and model client = genai.Client() config = types.GenerateContentConfig( tools=[get_weather_forecast, set_thermostat_temperature] ) # Make the request response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.\", config=config, ) # Print the final, user-facing response print(response.text)` **Expected Output** When you run the code, you will see the SDK orchestrating the function\ncalls. The model first calls `get_weather_forecast`, receives the\ntemperature, and then calls `set_thermostat_temperature` with the correct\nvalue based on the logic in the prompt. `Tool Call: get_weather_forecast(location=London) Tool Response: {'temperature': 25, 'unit': 'celsius'} Tool Call: set_thermostat_temperature(temperature=20) Tool Response: {'status': 'success'} OK. I've set the thermostat to 20°C.` JavaScriptThis example shows how to use JavaScript/TypeScript SDK to do comopositional\nfunction calling using a manual execution loop. `import { GoogleGenAI, Type } from \"@google/genai\"; // Configure the client const ai = new GoogleGenAI({}); // Example Functions function get_weather_forecast({ location }) { console.log(`Tool Call: get_weather_forecast(location=${location})`); // TODO: Make API call console.log(\"Tool Response: {'temperature': 25, 'unit': 'celsius'}\"); return { temperature: 25, unit: \"celsius\" }; } function set_thermostat_temperature({ temperature }) { console.log( `Tool Call: set_thermostat_temperature(temperature=${temperature})`, ); // TODO: Make API call console.log(\"Tool Response: {'status': 'success'}\"); return { status: \"success\" }; } const toolFunctions = { get_weather_forecast, set_thermostat_temperature, }; const tools = [ { functionDeclarations: [ { name: \"get_weather_forecast\", description: \"Gets the current weather temperature for a given location.\", parameters: { type: Type.OBJECT, properties: { location: { type: Type.STRING, }, }, required: [\"location\"], }, }, { name: \"set_thermostat_temperature\", description: \"Sets the thermostat to a desired temperature.\", parameters: { type: Type.OBJECT, properties: { temperature: { type: Type.NUMBER, }, }, required: [\"temperature\"], }, }, ], }, ]; // Prompt for the model let contents = [ { role: \"user\", parts: [ { text: \"If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.\", }, ], }, ]; // Loop until the model has no more function calls to make while (true) { const result = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents, config: { tools }, }); if (result.functionCalls && result.functionCalls.length > 0) { const functionCall = result.functionCalls[0]; const { name, args } = functionCall; if (!toolFunctions[name]) { throw new Error(`Unknown function call: ${name}`); } // Call the function and get the response. const toolResponse = toolFunctions[name](args); const functionResponsePart = { name: functionCall.name, response: { result: toolResponse, }, id: functionCall.id, }; // Send the function response back to the model. contents.push({ role: \"model\", parts: [ { functionCall: functionCall, }, ], }); contents.push({ role: \"user\", parts: [ { functionResponse: functionResponsePart, }, ], }); } else { // No more function calls, break the loop. console.log(result.text); break; } }` **Expected Output** When you run the code, you will see the SDK orchestrating the function\ncalls. The model first calls `get_weather_forecast`, receives the\ntemperature, and then calls `set_thermostat_temperature` with the correct\nvalue based on the logic in the prompt. `Tool Call: get_weather_forecast(location=London) Tool Response: {'temperature': 25, 'unit': 'celsius'} Tool Call: set_thermostat_temperature(temperature=20) Tool Response: {'status': 'success'} OK. It's 25°C in London, so I've set the thermostat to 20°C.` Compositional function calling is a native [Live\nAPI](https://ai.google.dev/gemini-api/docs/live) feature. This means Live API\ncan handle the function calling similar to the Python SDK. Python`# Light control schemas turn_on_the_lights_schema = {'name': 'turn_on_the_lights'} turn_off_the_lights_schema = {'name': 'turn_off_the_lights'} prompt = \"\"\" Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights? \"\"\" tools = [ {'code_execution': {}}, {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]} ] await run(prompt, tools=tools, modality=\"AUDIO\")` JavaScript`// Light control schemas const turnOnTheLightsSchema = { name: 'turn_on_the_lights' }; const turnOffTheLightsSchema = { name: 'turn_off_the_lights' }; const prompt = ` Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights? `; const tools = [ { codeExecution: {} }, { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] } ]; await run(prompt, tools=tools, modality=\"AUDIO\")` Function calling modes The Gemini API lets you control how the model uses the provided tools\n(function declarations). Specifically, you can set the mode within\nthe.`function_calling_config`. `VALIDATED`: Default mode for tool combination (when built-in tools or\nstructured outputs also enabled). The model is constrained to predict either\nfunction calls or natural language, and ensures function schema adherence. If\n`allowed_function_names` is not provided, the model picks from all of the\navailable function declarations. If `allowed_function_names` is provided, the\nmodel picks from the set of allowed functions. This mode reduces malformed\nfunction calls (compared to `AUTO` mode). `AUTO`: Default mode when only function_declarations tool enabled.\nThe model decides whether to generate a natural language response or suggest\na function call based on the prompt and context. `ANY`: The model is constrained to always predict a function call and\nensures function schema adherence. If `allowed_function_names` is not\nspecified, the model can choose from any of the provided function declarations.\nIf `allowed_function_names` is provided as a list, the model can only choose\nfrom the functions in that list. Use this mode when you require a function\ncall response to every prompt (if applicable). `NONE`: The model is *prohibited* from making function calls. This is\nequivalent to sending a request without any function declarations. Use this to\ntemporarily disable function calling without removing your tool definitions. Python`from google.genai import types # Configure function calling mode tool_config = types.ToolConfig( function_calling_config=types.FunctionCallingConfig( mode=\"ANY\", allowed_function_names=[\"get_current_temperature\"] ) ) # Create the generation config config = types.GenerateContentConfig( tools=[tools], # not defined here. tool_config=tool_config, )` JavaScript`import { FunctionCallingConfigMode } from '@google/genai'; // Configure function calling mode const toolConfig = { functionCallingConfig: { mode: FunctionCallingConfigMode.ANY, allowedFunctionNames: ['get_current_temperature'] } }; // Create the generation config const config = { tools: tools, // not defined here. toolConfig: toolConfig, };` Automatic function calling (Python only) When using the Python SDK, you can provide Python functions directly as tools.\nThe SDK converts these functions into declarations, manages the function call\nexecution, and handles the response cycle for you. Define your function with\ntype hints and a docstring. For optimal results, it is recommended to use\n[Google-style docstrings.](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods)\nThe SDK will then automatically: Detect function call responses from the model. Call the corresponding Python function in your code. Send the function's response back to the model. Return the model's final text response. The SDK currently doesn't parse argument descriptions into the property\ndescription slots of the generated function declaration. Instead, it sends the\nentire docstring as the top-level function description. Python`from google import genai from google.genai import types # Define the function with type hints and docstring def get_current_temperature(location: str) -> dict: \"\"\"Gets the current temperature for a given location. Args: location: The city and state, e.g. San Francisco, CA Returns: A dictionary containing the temperature and unit. \"\"\" # ... (implementation) ... return {\"temperature\": 25, \"unit\": \"Celsius\"} # Configure the client client = genai.Client() config = types.GenerateContentConfig( tools=[get_current_temperature] ) # Pass the function itself # Make the request response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"What's the temperature in Boston?\", config=config, ) print(response.text) # The SDK handles the function call and returns the final text` You can disable automatic function calling with: Python`config = types.GenerateContentConfig( tools=[get_current_temperature], automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True) )` Automatic function schema declaration The API is able to describe any of the following types. `Pydantic` types are\nallowed, as long as the fields defined on them are also composed of allowed\ntypes. Dict types (like `dict[str: int]`) are not well supported here, don't\nuse them. Python`AllowedType = ( int | float | bool | str | list['AllowedType'] | pydantic.BaseModel)` To see what the inferred schema looks like, you can convert it using\n[`from_callable`](https://googleapis.github.io/python-genai/genai.html#genai.types.FunctionDeclaration.from_callable): Python`from google import genai from google.genai import types def multiply(a: float, b: float): \"\"\"Returns a * b.\"\"\" return a * b client = genai.Client() fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client) # to_json_dict() provides a clean JSON representation. print(fn_decl.to_json_dict())` Multi-tool use: Combine built-in tools with function calling You can enable multiple tools, combining built-in tools with function calling in\nthe same request. Gemini 3 models can combine built-in tools with function calling out-of-the-box,\nthanks to the tool context circulation feature. Read the page on\n[Combining built-in tools and function calling](/gemini-api/docs/tool-combination) to learn more. Python`from google import genai from google.genai import types client = genai.Client() getWeather = { \"name\": \"getWeather\", \"description\": \"Gets the weather for a requested city.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"city\": { \"type\": \"string\", \"description\": \"The city and state, e.g. UtqiaÄĄvik, Alaska\", }, }, \"required\": [\"city\"], }, } response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"What is the northernmost city in the United States? What's the weather like there today?\", config=types.GenerateContentConfig( tools=[ types.Tool( google_search=types.ToolGoogleSearch(), # Built-in tool function_declarations=[getWeather] # Custom tool ), ], include_server_side_tool_invocations=True ), ) history = [ types.Content( role=\"user\", parts=[types.Part(text=\"What is the northernmost city in the United States? What's the weather like there today?\")] ), response.candidates[0].content, types.Content( role=\"user\", parts=[types.Part( function_response=types.FunctionResponse( name=\"getWeather\", response={\"response\": \"Very cold. 22 degrees Fahrenheit.\"}, id=response.candidates[0].content.parts[2].function_call.id ) )] ) ] response_2 = client.models.generate_content( model=\"gemini-3.8-flash\", contents=history, config=types.GenerateContentConfig( tools=[ types.Tool( google_search=types.ToolGoogleSearch(), function_declarations=[getWeather] ), ], include_server_side_tool_invocations=True ), )` Javascript`import { GoogleGenAI} from '@google/genai'; const client = new GoogleGenAI({}); const getWeather = { name: \"getWeather\", description: \"Get the weather in a given location\", parameters: { type: \"OBJECT\", properties: { location: { type: \"STRING\", description: \"The city and state, e.g. San Francisco, CA\" } }, required: [\"location\"] } }; async function run() { const tools = [ { googleSearch: {} }, { functionDeclarations: [getWeather] } ]; const toolConfig = { includeServerSideToolInvocations: true }; const response1 = await client.models.generateContent({ model: \"gemini-3.8-flash\", contents: [{role: \"user\", parts: [{text: \"What is the northernmost city in the United States? What's the weather like there today?\"}]}], config: { tools: tools, toolConfig: toolConfig, }, }); const functionCallId = response1.candidates[0].content.parts.find(p => p.functionCall)?.functionCall?.id; const history = [ { role: \"user\", parts:[{text: \"What is the northernmost city in the United States? What's the weather like there today?\"}] }, response1.candidates[0].content, { role: \"user\", parts: [{ functionResponse: { name: \"getWeather\", response: {response: \"Very cold. 22 degrees Fahrenheit.\"}, id: functionCallId } }] } ]; const response2 = await client.models.generateContent({ model: \"gemini-3.8-flash\", contents: history, config: { tools: tools, toolConfig: toolConfig, }, }); } run();` For models before the Gemini 3 series, use the\n[Live API](/gemini-api/docs/live-api/tools). Multimodal function responses For Gemini 3 series models, you can include multimodal content in\nthe function response parts that you send to the model. The model can process\nthis multimodal content in its next turn to produce a more informed response.\nThe following MIME types are supported for multimodal content in function\nresponses: **Images**: `image/png`, `image/jpeg`, `image/webp` **Documents**: `application/pdf`, `text/plain` To include multimodal data in a function response, include it as one or more\nparts nested within the `functionResponse` part. Each multimodal part must\ncontain `inlineData`. If you reference a multimodal part from\nwithin the structured `response` field, it must contain a unique `displayName`. You can also reference a multimodal part from within the structured `response`\nfield of the `functionResponse` part by using the JSON reference format\n`{\"$ref\": \"\"}`. The model substitutes the reference with the\nmultimodal content when processing the response. Each `displayName` can only be\nreferenced once in the structured `response` field. The following example shows a message containing a `functionResponse` for a\nfunction named `get_image` and a nested part containing image data with\n`displayName: \"instrument.jpg\"`. The `functionResponse`'s `response` field\nreferences this image part: Python `from google import genai from google.genai import types import requests client = genai.Client() # This is a manual, two turn multimodal function calling workflow: # 1. Define the function tool get_image_declaration = types.FunctionDeclaration( name=\"get_image\", description=\"Retrieves the image file reference for a specific order item.\", parameters={ \"type\": \"object\", \"properties\": { \"item_name\": { \"type\": \"string\", \"description\": \"The name or description of the item ordered (e.g., 'instrument').\" } }, \"required\": [\"item_name\"], }, ) tool_config = types.Tool(function_declarations=[get_image_declaration]) # 2. Send a message that triggers the tool prompt = \"Show me the instrument I ordered last month.\" response_1 = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[prompt], config=types.GenerateContentConfig( tools=[tool_config], ) ) # 3. Handle the function call function_call = response_1.function_calls[0] requested_item = function_call.args[\"item_name\"] print(f\"Model wants to call: {function_call.name}\") # Execute your tool (e.g., call an API) # (This is a mock response for the example) print(f\"Calling external tool for: {requested_item}\") function_response_data = { \"image_ref\": {\"$ref\": \"instrument.jpg\"}, } image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content function_response_multimodal_data = types.FunctionResponsePart( inline_data=types.FunctionResponseBlob( mime_type=\"image/jpeg\", display_name=\"instrument.jpg\", data=image_bytes, ) ) # 4. Send the tool's result back # Append this turn's messages to history for a final response. history = [ types.Content(role=\"user\", parts=[types.Part(text=prompt)]), response_1.candidates[0].content, types.Content( role=\"user\", parts=[ types.Part.from_function_response( id=function_call.id, name=function_call.name, response=function_response_data, parts=[function_response_multimodal_data] ) ], ) ] response_2 = client.models.generate_content( model=\"gemini-3.8-flash\", contents=history, config=types.GenerateContentConfig( tools=[tool_config], thinking_config=types.ThinkingConfig(include_thoughts=True) ), ) print(f\"\\nFinal model response: {response_2.text}\")` JavaScript `import { GoogleGenAI, Type } from '@google/genai'; const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }); // This is a manual, two turn multimodal function calling workflow: // 1. Define the function tool const getImageDeclaration = { name: 'get_image', description: 'Retrieves the image file reference for a specific order item.', parameters: { type: Type.OBJECT, properties: { item_name: { type: Type.STRING, description: \"The name or description of the item ordered (e.g., 'instrument').\", }, }, required: ['item_name'], }, }; const toolConfig = { functionDeclarations: [getImageDeclaration], }; // 2. Send a message that triggers the tool const prompt = 'Show me the instrument I ordered last month.'; const response1 = await client.models.generateContent({ model: 'gemini-3.8-flash', contents: prompt, config: { tools: [toolConfig], }, }); // 3. Handle the function call const functionCall = response1.functionCalls[0]; const requestedItem = functionCall.args.item_name; console.log(`Model wants to call: ${functionCall.name}`); // Execute your tool (e.g., call an API) // (This is a mock response for the example) console.log(`Calling external tool for: ${requestedItem}`); const functionResponseData = { image_ref: { $ref: 'instrument.jpg' }, }; 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 functionResponseMultimodalData = { inlineData: { mimeType: 'image/jpeg', displayName: 'instrument.jpg', data: base64ImageData, }, }; // 4. Send the tool's result back // Append this turn's messages to history for a final response. const history = [ { role: 'user', parts: [{ text: prompt }] }, response1.candidates[0].content, { role: 'user', parts: [ { functionResponse: { id: functionCall.id, name: functionCall.name, response: functionResponseData, parts: [functionResponseMultimodalData] }, }, ], }, ]; const response2 = await client.models.generateContent({ model: 'gemini-3.8-flash', contents: history, config: { tools: [toolConfig], thinkingConfig: { includeThoughts: true }, }, }); console.log(`\\nFinal model response: ${response2.text}`);` REST `IMG_URL=\"https://goo.gle/instrument-img\" MIME_TYPE=$(curl -sIL \"$IMG_URL\" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\\r$//' | head -n 1) if [[ -z \"$MIME_TYPE\" || ! \"$MIME_TYPE\" == image/* ]]; then MIME_TYPE=\"image/jpeg\" fi # Check for macOS if [[ \"$(uname)\" == \"Darwin\" ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -b 0) elif [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64) else IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -w0) fi\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ ..., { \"role\": \"user\", \"parts\": [ { \"functionResponse\": { \"name\": \"get_image\", \"id\": \"UNIQUE_CALL_ID_HERE\", \"response\": { \"image_ref\": { \"$ref\": \"instrument.jpg\" } }, \"parts\": [ { \"inlineData\": { \"displayName\": \"instrument.jpg\", \"mimeType\":\"'\"$MIME_TYPE\"'\", \"data\": \"'\"$IMAGE_B64\"'\" } } ] } } ] } ] }'` Function calling with Structured output For Gemini 3 series models, you can use function calling with\n[structured output](/gemini-api/docs/structured-output). This lets the model\npredict function calls or outputs that adhere to a specific schema. As a result,\nyou receive consistently formatted responses when the model doesn't generate\nfunction calls. Model context protocol (MCP) [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is\nan open standard for connecting AI applications with external tools and data.\nMCP provides a common protocol for models to access context, such as functions\n(tools), data sources (resources), or predefined prompts. The Gemini SDKs have built-in support for the MCP, reducing boilerplate code and\noffering\n[automatic tool calling](/gemini-api/docs/function-calling#automatic_function_calling_python_only)\nfor MCP tools. When the model generates an MCP tool call, the Python and\nJavaScript client SDK can automatically execute the MCP tool and send the\nresponse back to the model in a subsequent request, continuing this loop until\nno more tool calls are made by the model. Here, you can find an example of how to use a local MCP server with Gemini and\n`mcp` SDK. PythonMake sure the latest version of the\n[`mcp` SDK](https://modelcontextprotocol.io/introduction) is installed on\nyour platform of choice. `pip install mcp``import os import asyncio from datetime import datetime from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from google import genai client = genai.Client() # Create server parameters for stdio connection server_params = StdioServerParameters( command=\"npx\", # Executable args=[\"-y\", \"@philschmid/weather-mcp\"], # MCP Server env=None, # Optional environment variables ) async def run(): async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: # Prompt to get the weather for the current day in London. prompt = f\"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?\" # Initialize the connection between client and server await session.initialize() # Send request to the model with MCP function declarations response = await client.aio.models.generate_content( model=\"gemini-3.8-flash\", contents=prompt, config=genai.types.GenerateContentConfig( temperature=0, tools=[session], # uses the session, will automatically call the tool # Uncomment if you **don't** want the SDK to automatically call the tool # automatic_function_calling=genai.types.AutomaticFunctionCallingConfig( # disable=True # ), ), ) print(response.text) # Start the asyncio event loop and run the main function asyncio.run(run())` JavaScriptMake sure the latest version of the `mcp` SDK is installed on your platform\nof choice. `npm install @modelcontextprotocol/sdk``import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai'; import { Client } from \"@modelcontextprotocol/sdk/client/index.js\"; import { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\"; // Create server parameters for stdio connection const serverParams = new StdioClientTransport({ command: \"npx\", // Executable args: [\"-y\", \"@philschmid/weather-mcp\"] // MCP Server }); const client = new Client( { name: \"example-client\", version: \"1.0.0\" } ); // Configure the client const ai = new GoogleGenAI({}); // Initialize the connection between client and server await client.connect(serverParams); // Send request to the model with MCP tools const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`, config: { tools: [mcpToTool(client)], // uses the session, will automatically call the tool // Uncomment if you **don't** want the sdk to automatically call the tool // automaticFunctionCalling: { // disable: true, // }, }, }); console.log(response.text) // Close the connection await client.close();` Limitations with built-in MCP support Built-in MCP support is a [experimental](/gemini-api/docs/models#preview)\nfeature in our SDKs and has the following limitations: Only tools are supported, not resources nor prompts It is available for the Python and JavaScript/TypeScript SDK. Breaking changes might occur in future releases. Manual integration of MCP servers is always an option if these limit what you're\nbuilding. Supported models This section lists models and their function calling capabilities. Experimental\nmodels are not included. You can find a comprehensive capabilities overview on\nthe [model overview](https://ai.google.dev/gemini-api/docs/models) page. Model Function calling Parallel function calling Compositional function calling [Gemini 3.8 Flash](/gemini-api/docs/models/gemini-3.8-flash) ✔️ ✔️ ✔️ [Gemini 3.7 Flash](/gemini-api/docs/models/gemini-3.7-flash) ✔️ ✔️ ✔️ [Gemini 3.6 Flash](/gemini-api/docs/models/gemini-3.6-flash) ✔️ ✔️ ✔️ [Gemini 3.5 Flash-Lite](/gemini-api/docs/models/gemini-3.5-flash-lite) ✔️ ✔️ ✔️ [Gemini 3.1 Pro Preview](/gemini-api/docs/models/gemini-3.1-pro-preview) ✔️ ✔️ ✔️ [Gemini 3.1 Flash-Lite](/gemini-api/docs/models/gemini-3.1-flash-lite) ✔️ ✔️ ✔️ [Gemini 3.5 Flash](/gemini-api/docs/models/gemini-3.5-flash) ✔️ ✔️ ✔️ [Gemini 2.5 Pro](/gemini-api/docs/models/gemini-2.5-pro) ✔️ ✔️ ✔️ [Gemini 2.5 Flash](/gemini-api/docs/models/gemini-2.5-flash) ✔️ ✔️ ✔️ [Gemini 2.5 Flash-Lite](/gemini-api/docs/models/gemini-2.5-flash-lite) ✔️ ✔️ ✔️ Best practices **Function and Parameter Descriptions:** Be extremely clear and specific in\nyour descriptions. The model relies on these to choose the correct function\nand provide appropriate arguments. **Naming:** Use descriptive function names (without spaces, periods, or\ndashes). **Strong Typing:** Use specific types (integer, string, enum) for parameters\nto reduce errors. If a parameter has a limited set of valid values, use an\nenum. **Tool Selection:** While the model can use an arbitrary number of tools,\nproviding too many can increase the risk of selecting an incorrect or\nsuboptimal tool. For best results, aim to provide only the relevant tools\nfor the context or task, ideally keeping the active set to a maximum of\n10-20. Consider dynamic tool selection based on conversation context if you\nhave a large total number of tools. **Prompt Engineering:** Provide context: Tell the model its role (e.g., \"You are a helpful\nweather assistant.\"). Give instructions: Specify how and when to use functions (e.g., \"Don't\nguess dates; always use a future date for forecasts.\"). Encourage clarification: Instruct the model to ask clarifying questions\nif needed. See [Agentic workflows](/gemini-api/docs/prompting-strategies#agentic-workflows)\nfor further strategies on designing these prompts. Here is an example of a tested\n[system instruction](/gemini-api/docs/prompting-strategies#agentic-si-template). **Temperature:** Use a low temperature (e.g., 0) for more deterministic and\nreliable function calls. **Validation:** If a function call has significant consequences (e.g.,\nplacing an order), validate the call with the user before executing it. **Check Finish Reason:** Always check the [`finishReason`](/api/generate-content#FinishReason)\nin the model's response to handle cases where the model failed to generate a\nvalid function call. **Error Handling**: Implement robust error handling in your functions to\ngracefully handle unexpected inputs or API failures. Return informative\nerror messages that the model can use to generate helpful responses to the\nuser. **Security:** Be mindful of security when calling external APIs. Use\nappropriate authentication and authorization mechanisms. Avoid exposing\nsensitive data in function calls. **Token Limits:** Function descriptions and parameters count towards your\ninput token limit. If you're hitting token limits, consider limiting the\nnumber of functions or the length of the descriptions, break down complex\ntasks into smaller, more focused function sets. **Mix of bash and custom tools** For those building with a mix of bash and\ncustom tools, Gemini 3.1 Pro Preview\ncomes with a separate endpoint available via the API called\n[`gemini-3.1-pro-preview-customtools`](/gemini-api/docs/models/gemini-3.1-pro-preview#gemini-31-pro-preview-customtools). Workarounds for pre-tool text requirements **Issue:** If your prompt requires the model to output structured text (XML, YAML, JSON, etc.) (e.g., `...`) immediately before making a tool call, the tool call may occasionally fail with `Malformed_Function_Call`. **Solutions:** The following workarounds resolve this issue: **PREFERRED:** Instruct the model to put its pre-tool notes inside a dedicated `update()` function call instead of raw text (details below). Instruct the model to write notes as Markdown headers (`# UPDATE`, `## PLAN`) instead of structured text. Do not require the model to output text before tool calls. Preferred workaround: Wrap working notes in a dedicated function call Instead of the original instruction: `Before calling a tool, in every response you MUST first output a single `` part as specified, don't skip this part or any of required sub-tags within ``.` Use this updated instruction: `Before calling any other tool, in every response you MUST first call `update` with all required parameters (previous_step, plan, next_step, external).` And update all references to the old `` XML format in the customer request. Then add the corresponding function declaration for the update function: `{ \"name\": \"update\", \"description\": \"Update working notes (previous step analysis, plan, next step, external note).\", \"parameters\": { \"type\": \"OBJECT\", \"properties\": { \"previous_step\": { \"type\": \"STRING\", \"description\": \"Key findings and outcomes since the previous step.\" }, \"plan\": { \"type\": \"STRING\", \"description\": \"The current status of the plan.\" }, \"next_step\": { \"type\": \"STRING\", \"description\": \"Brief explanation of the immediate next action according to the plan.\" }, \"external\": { \"type\": \"STRING\", \"description\": \"A short, plain-language note shown to the User about what you are ABOUT TO DO next.\" } }, \"required\": [ \"previous_step\", \"plan\", \"next_step\", \"external\" ] } }` Then the model will make two calls in the same step: the `update()` call that replaces the structured XML, and the actual function call it wants to make. Notes and limitations Positioning of function call parts: When using custom function declarations\n[alongside built-in tools](/gemini-api/docs/tool-combination) (like Google\nSearch), the model may return a mix of `functionCall`, `toolCall`, and\n`toolResponse` parts in a single turn. Because of this, don't assume the\n`functionCall` will always be the last item in the parts array. If you are\nmanually parsing the JSON response, always iterate through the parts array\nrather than relying on position. Only a [subset of the OpenAPI\nschema](/api/caching#FunctionDeclaration) is supported. For `ANY` mode, the API may reject very large or deeply nested schemas. If\nyou encounter errors, try simplifying your function parameter and response\nschemas by shortening property names, reducing nesting, or limiting the\nnumber of function declarations. Supported parameter types in Python are limited. Automatic function calling is a Python SDK feature only. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-03 UTC.", "znaku_textu": 66901, "slov": 8859, "odkazu": 161, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:02:56", "sha256": "b2f04d9f217d1801b6b7e3b6d5b59189bd80439f73d4ed6bd633f8dd54001235", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://spec.openapis.org/oas/v3.0.3", "https://google.github.io/styleguide/pyguide.html", "https://googleapis.github.io/python-genai/genai.html", "https://modelcontextprotocol.io/introduction", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/gemini-3", "titulek": "Gemini 3 developer guide | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Gemini 3 developer guide", "popis": "Learn about the new features of Gemini 3 in the Gemini API.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/gemini-3", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini 3 developer guide  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Learn about the new features of Gemini 3 in the Gemini API.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/gemini-3", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Gemini 3 developer guide"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Gemini 3 developer guide", "item": "https://ai.google.dev/gemini-api/docs/generate-content/gemini-3"}]}], "drobecky": ["Generate Content API", "Gemini 3 developer guide"], "osnova": [{"uroven": 1, "text": "Gemini 3 developer guide"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Meet the Gemini 3 series"}, {"uroven": 2, "text": "New API features in Gemini 3"}, {"uroven": 3, "text": "Thinking level"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Media resolution"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Temperature"}, {"uroven": 3, "text": "Thought signatures"}, {"uroven": 4, "text": "Function calling (strict validation)"}, {"uroven": 4, "text": "Text and streaming"}, {"uroven": 4, "text": "Image generation and editing"}, {"uroven": 4, "text": "Code examples"}, {"uroven": 4, "text": "Multi-step Function Calling (Sequential)"}, {"uroven": 4, "text": "Parallel Function Calling"}, {"uroven": 4, "text": "Text/In-Context Reasoning (No Validation)"}, {"uroven": 4, "text": "Image Generation & Editing"}, {"uroven": 4, "text": "Migrating from other models"}, {"uroven": 3, "text": "Structured Outputs with tools"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Image generation"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Code Execution with images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Multimodal function responses"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Combine built-in tools and function calling"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 2, "text": "Migrating from Gemini 2.5"}, {"uroven": 2, "text": "OpenAI compatibility"}, {"uroven": 2, "text": "Prompting best practices"}, {"uroven": 2, "text": "FAQ"}, {"uroven": 2, "text": "Next steps"}], "markdown": "Gemini 3 developer guide Gemini 3 is our most intelligent model family to date, built on a foundation of\nstate-of-the-art reasoning. It is designed to bring any idea to life by\nmastering agentic workflows, autonomous coding, and complex multimodal tasks.\nThis guide covers key features of the Gemini 3 model family and how to get the\nmost out of it. [Try Gemini 3.1 Pro Preview](https://aistudio.google.com/prompts/new_chat?model=gemini-3.1-pro-preview) [Try Gemini 3 Flash Preview](https://aistudio.google.com/prompts/new_chat?model=gemini-3-flash-preview) [Try Gemini 3.1 Flash-Lite](https://aistudio.google.com/prompts/new_chat?model=gemini-3-flash-lite) [Try Nano Banana 2](https://aistudio.google.com/prompts/new_chat?model=gemini-3.1-flash-image-preview) Explore our [collection of Gemini 3 apps](https://aistudio.google.com/app/apps?source=showcase&showcaseTag=gemini-3) to\nsee how the model handles advanced reasoning, autonomous coding, and complex\nmultimodal tasks. Get started with a few lines of code: Python`from google import genai client = genai.Client() response = client.models.generate_content( model=\"gemini-3.1-pro-preview\", contents=\"Find the race condition in this multi-threaded C++ snippet: [code here]\", ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function run() { const response = await ai.models.generateContent({ model: \"gemini-3.1-pro-preview\", contents: \"Find the race condition in this multi-threaded C++ snippet: [code here]\", }); console.log(response.text); } run();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\": [{\"text\": \"Find the race condition in this multi-threaded C++ snippet: [code here]\"}] }] }'` Meet the Gemini 3 series Gemini 3.1 Pro is best for complex tasks that\nrequire broad world knowledge and advanced reasoning across modalities. Gemini 3 Flash is our latest 3-series model, with Pro-level intelligence at the\nspeed and pricing of Flash. Nano Banana Pro (also known as Gemini 3 Pro Image) is our highest quality image\ngeneration model, and Nano Banana 2 (also known as Gemini 3.1 Flash Image) is\nthe high-volume, high-efficiency, lower price-point equivalent. Gemini 3.1 Flash-Lite is our workhorse model built for cost-efficiency model and\nhigh-volume tasks. Model ID Context Window (In / Out) Knowledge Cutoff Pricing (Input / Output)* **gemini-3.1-flash-lite** 1M / 64k Jan 2025 $0.25 (text, image, video), $0.50 (audio) / $1.50 **gemini-3.1-flash-image-preview** 128k / 32k Jan 2025 $0.25 (Text Input) / $0.067 (Image Output)** **gemini-3.1-pro-preview** 1M / 64k Jan 2025 $2 / $12 (<200k tokens) \n $4 / $18 (>200k tokens) **gemini-3-flash-preview** 1M / 64k Jan 2025 $0.50 / $3 **gemini-3-pro-image-preview** 65k / 32k Jan 2025 $2 (Text Input) / $0.134 (Image Output)** ** Pricing is per 1 million tokens unless otherwise noted.* *** Image pricing varies by resolution. See the [pricing page](/gemini-api/docs/pricing) for details.* For detailed limits, pricing, and additional information, see the\n[models page](/gemini-api/docs/models/gemini). New API features in Gemini 3 Gemini 3 introduces new parameters designed to give developers more control over\nlatency, cost, and multimodal fidelity. Thinking level Gemini 3 series models use dynamic thinking by default to reason through\nprompts. You can use the `thinking_level` parameter, which controls the\n**maximum** depth of the model's internal reasoning process before it produces a\nresponse. Gemini 3 treats these levels as relative allowances for thinking\nrather than strict token guarantees. If `thinking_level` is not specified, Gemini 3 will default to `high`. For\nfaster, lower-latency responses when complex reasoning isn't required, you can\nconstrain the model's thinking level to `low`. Thinking Level Gemini 3.1 Pro Gemini 3.1 Flash-Lite Gemini 3 Flash Description **`minimal`** Not supported Supported (Default) Supported Matches the \"no thinking\" setting for most queries. The model may think very minimally for complex coding tasks. Minimizes latency for chat or high throughput applications. Note, `minimal` does not guarantee that thinking is off. **`low`** Supported Supported Supported Minimizes latency and cost. Best for simple instruction following, chat, or high-throughput applications. **`medium`** Supported Supported Supported Balanced thinking for most tasks. **`high`** Supported (Default, Dynamic) Supported (Dynamic) Supported (Default, Dynamic) Maximizes reasoning depth. The model may take significantly longer to\n reach a first (non thinking) output token, but the output will be more carefully reasoned. Python`from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model=\"gemini-3.1-pro-preview\", contents=\"How does AI work?\", config=types.GenerateContentConfig( thinking_config=types.ThinkingConfig(thinking_level=\"low\") ), ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); const response = await ai.models.generateContent({ model: \"gemini-3.1-pro-preview\", contents: \"How does AI work?\", config: { thinkingConfig: { thinkingLevel: \"low\", } }, }); console.log(response.text);` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\": [{\"text\": \"How does AI work?\"}] }], \"generationConfig\": { \"thinkingConfig\": { \"thinkingLevel\": \"low\" } } }'` Media resolution Gemini 3 introduces granular control over multimodal vision processing using the\n`media_resolution` parameter. Higher resolutions improve the model's ability to\nread fine text or identify small details, but increase token usage and latency.\nThe `media_resolution` parameter determines the **maximum number of tokens\nallocated per input image or video frame.** You can now set the resolution to `media_resolution_low`,\n`media_resolution_medium`, `media_resolution_high`, or\n`media_resolution_ultra_high` per individual media part or globally (via\n`generation_config`, global not available for ultra high). If unspecified, the\nmodel uses optimal defaults based on the media type. **Recommended settings** Media Type Recommended Setting Max Tokens Usage Guidance **Images** `media_resolution_high` 1120 Recommended for most image analysis tasks to ensure maximum quality. **PDFs** `media_resolution_medium` 560 Optimal for document understanding; quality typically saturates at `medium`. Increasing to `high` rarely improves OCR results for standard documents. **Video** (General) `media_resolution_low` (or `media_resolution_medium`) 70 (per frame) **Note:** For video, `low` and `medium` settings are treated identically (70 tokens) to optimize context usage. This is sufficient for most action recognition and description tasks. **Video** (Text-heavy) `media_resolution_high` 280 (per frame) Required only when the use case involves reading dense text (OCR) or small details within video frames. Python`from google import genai from google.genai import types import base64 # The media_resolution parameter is available in the v1beta API version. client = genai.Client(http_options={'api_version': 'v1beta'}) response = client.models.generate_content( model=\"gemini-3.1-pro-preview\", contents=[ types.Content( parts=[ types.Part(text=\"What is in this image?\"), types.Part( inline_data=types.Blob( mime_type=\"image/jpeg\", data=base64.b64decode(\"...\"), ), media_resolution={\"level\": \"media_resolution_high\"} ) ] ) ] ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; // The media_resolution parameter is available in the v1beta API version. const ai = new GoogleGenAI({ apiVersion: \"v1beta\" }); async function run() { const response = await ai.models.generateContent({ model: \"gemini-3.1-pro-preview\", contents: [ { parts: [ { text: \"What is in this image?\" }, { inlineData: { mimeType: \"image/jpeg\", data: \"...\", }, mediaResolution: { level: \"media_resolution_high\" } } ] } ] }); console.log(response.text); } run();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\": [ { \"text\": \"What is in this image?\" }, { \"inlineData\": { \"mimeType\": \"image/jpeg\", \"data\": \"...\" }, \"mediaResolution\": { \"level\": \"media_resolution_high\" } } ] }] }'` Temperature For all Gemini 3 models, we strongly recommend keeping the temperature parameter\nat its default value of `1.0`. While previous models often benefited from tuning temperature to control\ncreativity versus determinism, Gemini 3's reasoning capabilities are optimized\nfor the default setting. Changing the temperature (setting it below 1.0) may\nlead to unexpected behavior, such as looping or degraded performance,\nparticularly in complex mathematical or reasoning tasks. Thought signatures Gemini 3 uses [Thought signatures](/gemini-api/docs/thought-signatures) to\nmaintain reasoning context across API calls. These signatures are encrypted\nrepresentations of the model's internal thought process. To ensure the model\nmaintains its reasoning capabilities you must return these signatures back to\nthe model in your request exactly as they were received: **Function Calling (Strict):** The API enforces strict validation on the\n\"Current Turn\". Missing signatures will result in a 400 error. **Text/Chat:** Validation is not strictly enforced, but omitting signatures will degrade the model's reasoning and answer quality. **Image generation/editing (Strict)**: The API enforces strict validation on all Model parts including a `thoughtSignature`. Missing signatures will result in a 400 error. Function calling (strict validation) When Gemini generates a `functionCall`, it relies on the `thoughtSignature` to\nprocess the tool's output correctly in the next turn. The \"Current Turn\"\nincludes all Model (`functionCall`) and User (`functionResponse`) steps that\noccurred since the last standard **User** `text` message. **Single Function Call:** The `functionCall` part contains a signature. You must return it. **Parallel Function Calls:** Only the first `functionCall` part in the list will contain the signature. You must return the parts in the exact order received. **Multi-Step (Sequential):** If the model calls a tool, receives a result,\nand calls *another* tool (within the same turn), **both** function calls have\nsignatures. You must return **all** accumulated signatures in the history. Text and streaming For standard chat or text generation, the presence of a signature is not\nguaranteed. **Non-Streaming**: The final content part of the response may contain a\n`thoughtSignature`, though it is not always present. If one is returned, you\nshould send it back to maintain best performance. **Streaming**: If a signature is generated, it may arrive in a final chunk\nthat contains an empty text part. Ensure your stream parser checks for\nsignatures even if the text field is empty. Image generation and editing For `gemini-3-pro-image-preview` and `gemini-3.1-flash-image-preview`, thought\nsignatures are critical for\nconversational editing. When you ask the model to modify an image it relies on\nthe `thoughtSignature` from the previous turn to understand the composition and\nlogic of the original image. **Editing:** Signatures are guaranteed on the first part after the thoughts\nof the response (`text` or `inlineData`) and on every subsequent `inlineData`\npart. You must return all of these signatures to avoid errors. Code examples Multi-step Function Calling (Sequential) The user asks a question requiring two separate steps (Check Flight -> Book Taxi) in one turn. \n\n **Step 1: Model calls Flight Tool.**\n\n The model returns a signature `` // Model Response (Turn 1, Step 1) { \"role\": \"model\", \"parts\": [ { \"functionCall\": { \"name\": \"check_flight\", \"args\": {...} }, \"thoughtSignature\": \"\" // SAVE THIS } ] } **Step 2: User sends Flight Result**\n\n We must send back `` to keep the model's train of thought. // User Request (Turn 1, Step 2) [ { \"role\": \"user\", \"parts\": [{ \"text\": \"Check flight AA100...\" }] }, { \"role\": \"model\", \"parts\": [ { \"functionCall\": { \"name\": \"check_flight\", \"args\": {...} }, \"thoughtSignature\": \"\" // REQUIRED } ] }, { \"role\": \"user\", \"parts\": [{ \"functionResponse\": { \"name\": \"check_flight\", \"response\": {...} } }] } ] **Step 3: Model calls Taxi Tool**\n\n The model remembers the flight delay via `` and now decides to book a taxi. It generates a *new* signature ``. // Model Response (Turn 1, Step 3) { \"role\": \"model\", \"parts\": [ { \"functionCall\": { \"name\": \"book_taxi\", \"args\": {...} }, \"thoughtSignature\": \"\" // SAVE THIS } ] } **Step 4: User sends Taxi Result**\n\n To complete the turn, you must send back the entire chain: `` AND ``. // User Request (Turn 1, Step 4) [ // ... previous history ... { \"role\": \"model\", \"parts\": [ { \"functionCall\": { \"name\": \"check_flight\", ... }, \"thoughtSignature\": \"\" } ] }, { \"role\": \"user\", \"parts\": [{ \"functionResponse\": {...} }] }, { \"role\": \"model\", \"parts\": [ { \"functionCall\": { \"name\": \"book_taxi\", ... }, \"thoughtSignature\": \"\" } ] }, { \"role\": \"user\", \"parts\": [{ \"functionResponse\": {...} }] } ] Parallel Function Calling The user asks: \"Check the weather in Paris and London.\" The model returns two function calls in one response. // User Request (Sending Parallel Results) [ { \"role\": \"user\", \"parts\": [ { \"text\": \"Check the weather in Paris and London.\" } ] }, { \"role\": \"model\", \"parts\": [ // 1. First Function Call has the signature { \"functionCall\": { \"name\": \"check_weather\", \"args\": { \"city\": \"Paris\" } }, \"thoughtSignature\": \"\" }, // 2. Subsequent parallel calls DO NOT have signatures { \"functionCall\": { \"name\": \"check_weather\", \"args\": { \"city\": \"London\" } } } ] }, { \"role\": \"user\", \"parts\": [ // 3. Function Responses are grouped together in the next block { \"functionResponse\": { \"name\": \"check_weather\", \"response\": { \"temp\": \"15C\" } } }, { \"functionResponse\": { \"name\": \"check_weather\", \"response\": { \"temp\": \"12C\" } } } ] } ] Text/In-Context Reasoning (No Validation) The user asks a question that requires in-context reasoning without external tools. While not strictly validated, including the signature helps the model maintain the reasoning chain for follow-up questions. // User Request (Follow-up question) [ { \"role\": \"user\", \"parts\": [{ \"text\": \"What are the risks of this investment?\" }] }, { \"role\": \"model\", \"parts\": [ { \"text\": \"I need to calculate the risk step-by-step. First, I'll look at volatility...\", \"thoughtSignature\": \"\" // Recommended to include } ] }, { \"role\": \"user\", \"parts\": [{ \"text\": \"Summarize that in one sentence.\" }] } ] Image Generation & Editing For image generation, signatures are strictly validated. They appear on the **first part** (text or image) and **all subsequent image parts**. All must be returned in the next turn. // Model Response (Turn 1) { \"role\": \"model\", \"parts\": [ // 1. First part ALWAYS has a signature (even if text) { \"text\": \"I will generate a cyberpunk city...\", \"thoughtSignature\": \"\" }, // 2. ALL InlineData (Image) parts ALWAYS have signatures { \"inlineData\": { ... }, \"thoughtSignature\": \"\" }, ] } // User Request (Turn 2 - Requesting an Edit) { \"contents\": [ // History must include ALL signatures received { \"role\": \"user\", \"parts\": [{ \"text\": \"Generate a cyberpunk city\" }] }, { \"role\": \"model\", \"parts\": [ { \"text\": \"...\", \"thoughtSignature\": \"\" }, { \"inlineData\": \"...\", \"thoughtSignature\": \"\" }, ] }, // New User Prompt { \"role\": \"user\", \"parts\": [{ \"text\": \"Make it daytime.\" }] } ] } Migrating from other models If you are transferring a conversation trace from another model (e.g., Gemini\n2.5) or injecting a custom function call that was not generated by Gemini 3,\nyou will not have a valid signature. To bypass strict validation in these specific scenarios, populate the field with\nthis specific dummy string: `\"thoughtSignature\": \"context_engineering_is_the_way\nto_go\"` Structured Outputs with tools Gemini 3 models allow you to combine [Structured Outputs](/gemini-api/docs/structured-output) with built-in tools, including\n[Grounding with Google Search](/gemini-api/docs/google-search), [URL Context](/gemini-api/docs/url-context), [Code Execution](/gemini-api/docs/code-execution), and [Function Calling](/gemini-api/docs/function-calling). Python`from google import genai from google.genai import types from pydantic import BaseModel, Field from typing import List class MatchResult(BaseModel): winner: str = Field(description=\"The name of the winner.\") final_match_score: str = Field(description=\"The final match score.\") scorers: List[str] = Field(description=\"The name of the scorer.\") client = genai.Client() response = client.models.generate_content( model=\"gemini-3.1-pro-preview\", contents=\"Search for all details for the latest Euro.\", config={ \"tools\": [ {\"google_search\": {}}, {\"url_context\": {}} ], \"response_format\": {\"text\": {\"mime_type\": \"application/json\", \"schema\": MatchResult.model_json_schema()}}, }, ) result = MatchResult.model_validate_json(response.text) print(result)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import { z } from \"zod\"; import { zodToJsonSchema } from \"zod-to-json-schema\"; const ai = new GoogleGenAI({}); const matchSchema = z.object({ winner: z.string().describe(\"The name of the winner.\"), final_match_score: z.string().describe(\"The final score.\"), scorers: z.array(z.string()).describe(\"The name of the scorer.\") }); async function run() { const response = await ai.models.generateContent({ model: \"gemini-3.1-pro-preview\", contents: \"Search for all details for the latest Euro.\", config: { tools: [ { googleSearch: {} }, { urlContext: {} } ], responseFormat: { text: { mimeType: \"application/json\", schema: zodToJsonSchema(matchSchema) } }, }, }); const match = matchSchema.parse(JSON.parse(response.text)); console.log(match); } run();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\": [{\"text\": \"Search for all details for the latest Euro.\"}] }], \"tools\": [ {\"googleSearch\": {}}, {\"urlContext\": {}} ], \"generationConfig\": { \"responseFormat\": { \"text\": { \"mimeType\": \"application/json\", \"schema\": { \"type\": \"object\", \"properties\": { \"winner\": {\"type\": \"string\", \"description\": \"The name of the winner.\"}, \"final_match_score\": {\"type\": \"string\", \"description\": \"The final score.\"}, \"scorers\": { \"type\": \"array\", \"items\": {\"type\": \"string\"}, \"description\": \"The name of the scorer.\" } } } }, \"required\": [\"winner\", \"final_match_score\", \"scorers\"] } } }'` Image generation Gemini 3.1 Flash Image and Gemini 3 Pro Image let you generate and edit images\nfrom text prompts. It uses\nreasoning to \"think\" through a prompt and can retrieve real-time data—such as\nweather forecasts or stock charts—before using [Google Search](/gemini-api/docs/google-search) grounding before generating high-fidelity\nimages. **New & improved capabilities:** **4K & text rendering:** Generate sharp, legible text and diagrams with up\nto 2K and 4K resolutions. **Grounded generation:** Use the `google_search` tool to verify facts and\ngenerate imagery based on real-world information. Grounding with Google *Image*\nSearch available for Gemini 3.1 Flash Image. **Conversational editing:** Multi-turn image editing by simply asking for\nchanges (e.g., \"Make the background a sunset\"). This workflow relies on\n**Thought Signatures** to preserve visual context between turns. For complete details on aspect ratios, editing workflows, and configuration\noptions, see the [Image Generation guide](/gemini-api/docs/image-generation). Python`from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model=\"gemini-3-pro-image-preview\", contents=\"Generate an infographic of the current weather in Tokyo.\", config=types.GenerateContentConfig( tools=[{\"google_search\": {}}], response_format={\"image\": {\"aspect_ratio\": \"16:9\", \"image_size\": \"4K\"}} ) ) image_parts = [part for part in response.parts if part.inline_data] if image_parts: image = image_parts[0].as_image() image.save('weather_tokyo.png') image.show()` 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: {} }], responseFormat: { image: { 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();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\": [{\"text\": \"Generate a visualization of the current weather in Tokyo.\"}] }], \"tools\": [{\"googleSearch\": {}}], \"generationConfig\": { \"responseFormat\": { \"image\": { \"aspectRatio\": \"16:9\", \"imageSize\": \"4K\" } } } }'` **Example Response** Code Execution with images Gemini 3 Flash can treat vision as an active investigation, not just a static\nglance. By combining reasoning with [code execution](/gemini-api/docs/code-execution), the model formulates a plan, then writes and\nexecutes Python code to zoom in, crop, annotate, or otherwise manipulate images\nstep-by-step to visually ground its answers. **Use cases:** **Zoom and inspect:** The model implicitly detects when details are too\nsmall (e.g., reading a distant gauge or serial number) and writes code to crop\nand re-examine the area at higher resolution. **Visual math and plotting:** The model can run multi-step calculations using\ncode (e.g., summing line items on a receipt, or generating a Matplotlib chart\nfrom extracted data). **Image annotation:** The model can draw arrows, bounding boxes, or other\nannotations directly onto images to answer spatial questions like \"Where should\nthis item go?\". To enable visual thinking, configure [Code Execution](/gemini-api/docs/code-execution) as a tool. The model will automatically use\ncode to manipulate images when needed. Python`from google import genai from google.genai import types import requests from PIL import Image import io image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content image = types.Part.from_bytes(data=image_bytes, mime_type=\"image/jpeg\") client = genai.Client() response = client.models.generate_content( model=\"gemini-3-flash-preview\", contents=[ image, \"Zoom into the expression pedals and tell me how many pedals are there?\" ], config=types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution)] ), ) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) if part.executable_code is not None: print(part.executable_code.code) if part.code_execution_result is not None: print(part.code_execution_result.output) if part.as_image() is not None: display(Image.open(io.BytesIO(part.as_image().image_bytes)))` 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();` REST`IMG_URL=\"https://goo.gle/instrument-img\" MODEL=\"gemini-3-flash-preview\" MIME_TYPE=$(curl -sIL \"$IMG_URL\" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\\r$//' | head -n 1) if [[ -z \"$MIME_TYPE\" || ! \"$MIME_TYPE\" == image/* ]]; then MIME_TYPE=\"image/jpeg\" fi if [[ \"$(uname)\" == \"Darwin\" ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -b 0) elif [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64) else IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -w0) fi\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/$MODEL:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ { \"inline_data\": { \"mime_type\":\"'\"$MIME_TYPE\"'\", \"data\": \"'\"$IMAGE_B64\"'\" } }, {\"text\": \"Zoom into the expression pedals and tell me how many pedals are there?\"} ] }], \"tools\": [{\"code_execution\": {}}] }'` For more details on code execution with images, see [Code Execution](/gemini-api/docs/code-execution#images). Multimodal function responses [Multimodal function calling](/gemini-api/docs/function-calling#multimodal)\nallows users to have function responses containing\nmultimodal objects allowing for improved utilization of function calling\ncapabilities of the model. Standard function calling only supports text-based\nfunction responses: Python `from google import genai from google.genai import types import requests client = genai.Client() # This is a manual, two turn multimodal function calling workflow: # 1. Define the function tool get_image_declaration = types.FunctionDeclaration( name=\"get_image\", description=\"Retrieves the image file reference for a specific order item.\", parameters={ \"type\": \"object\", \"properties\": { \"item_name\": { \"type\": \"string\", \"description\": \"The name or description of the item ordered (e.g., 'instrument').\" } }, \"required\": [\"item_name\"], }, ) tool_config = types.Tool(function_declarations=[get_image_declaration]) # 2. Send a message that triggers the tool prompt = \"Show me the instrument I ordered last month.\" response_1 = client.models.generate_content( model=\"gemini-3-flash-preview\", contents=[prompt], config=types.GenerateContentConfig( tools=[tool_config], ) ) # 3. Handle the function call function_call = response_1.function_calls[0] requested_item = function_call.args[\"item_name\"] print(f\"Model wants to call: {function_call.name}\") # Execute your tool (e.g., call an API) # (This is a mock response for the example) print(f\"Calling external tool for: {requested_item}\") function_response_data = { \"image_ref\": {\"$ref\": \"instrument.jpg\"}, } image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content function_response_multimodal_data = types.FunctionResponsePart( inline_data=types.FunctionResponseBlob( mime_type=\"image/jpeg\", display_name=\"instrument.jpg\", data=image_bytes, ) ) # 4. Send the tool's result back # Append this turn's messages to history for a final response. history = [ types.Content(role=\"user\", parts=[types.Part(text=prompt)]), response_1.candidates[0].content, types.Content( role=\"user\", parts=[ types.Part.from_function_response( name=function_call.name, response=function_response_data, parts=[function_response_multimodal_data] ) ], ) ] response_2 = client.models.generate_content( model=\"gemini-3-flash-preview\", contents=history, config=types.GenerateContentConfig( tools=[tool_config], thinking_config=types.ThinkingConfig(include_thoughts=True) ), ) print(f\"\\nFinal model response: {response_2.text}\")` JavaScript `import { GoogleGenAI, Type } from '@google/genai'; const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }); // This is a manual, two turn multimodal function calling workflow: // 1. Define the function tool const getImageDeclaration = { name: 'get_image', description: 'Retrieves the image file reference for a specific order item.', parameters: { type: Type.OBJECT, properties: { item_name: { type: Type.STRING, description: \"The name or description of the item ordered (e.g., 'instrument').\", }, }, required: ['item_name'], }, }; const toolConfig = { functionDeclarations: [getImageDeclaration], }; // 2. Send a message that triggers the tool const prompt = 'Show me the instrument I ordered last month.'; const response1 = await client.models.generateContent({ model: 'gemini-3-flash-preview', contents: prompt, config: { tools: [toolConfig], }, }); // 3. Handle the function call const functionCall = response1.functionCalls[0]; const requestedItem = functionCall.args.item_name; console.log(`Model wants to call: ${functionCall.name}`); // Execute your tool (e.g., call an API) // (This is a mock response for the example) console.log(`Calling external tool for: ${requestedItem}`); const functionResponseData = { image_ref: { $ref: 'instrument.jpg' }, }; 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 functionResponseMultimodalData = { inlineData: { mimeType: 'image/jpeg', displayName: 'instrument.jpg', data: base64ImageData, }, }; // 4. Send the tool's result back // Append this turn's messages to history for a final response. const history = [ { role: 'user', parts: [{ text: prompt }] }, response1.candidates[0].content, { role: 'tool', parts: [ { functionResponse: { name: functionCall.name, response: functionResponseData, parts: [functionResponseMultimodalData], }, }, ], }, ]; const response2 = await client.models.generateContent({ model: 'gemini-3-flash-preview', contents: history, config: { tools: [toolConfig], thinkingConfig: { includeThoughts: true }, }, }); console.log(`\\nFinal model response: ${response2.text}`);` REST `IMG_URL=\"https://goo.gle/instrument-img\" MIME_TYPE=$(curl -sIL \"$IMG_URL\" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\\r$//' | head -n 1) if [[ -z \"$MIME_TYPE\" || ! \"$MIME_TYPE\" == image/* ]]; then MIME_TYPE=\"image/jpeg\" fi # Check for macOS if [[ \"$(uname)\" == \"Darwin\" ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -b 0) elif [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64) else IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -w0) fi\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ ..., { \"role\": \"user\", \"parts\": [ { \"functionResponse\": { \"name\": \"get_image\", \"response\": { \"image_ref\": { \"$ref\": \"instrument.jpg\" } }, \"parts\": [ { \"inlineData\": { \"displayName\": \"instrument.jpg\", \"mimeType\":\"'\"$MIME_TYPE\"'\", \"data\": \"'\"$IMAGE_B64\"'\" } } ] } } ] } ] }'` Combine built-in tools and function calling Gemini 3 allows the use of built-in tools (like Google Search, URL\ncontext, and [more](/gemini-api/docs/tools)) and custom [function calling](/gemini-api/docs/function-calling) tools in the same API call, allowing for\nmore complex workflows. Learn more on the [tool combinations](/gemini-api/docs/tool-combination) page. Python`from google import genai from google.genai import types client = genai.Client() getWeather = { \"name\": \"getWeather\", \"description\": \"Gets the weather for a requested city.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"city\": { \"type\": \"string\", \"description\": \"The city and state, e.g. UtqiaÄĄvik, Alaska\", }, }, \"required\": [\"city\"], }, } response = client.models.generate_content( model=\"gemini-3-flash-preview\", contents=\"What is the northernmost city in the United States? What's the weather like there today?\", config=types.GenerateContentConfig( tools=[ types.Tool( google_search=types.ToolGoogleSearch(), # Built-in tool function_declarations=[getWeather] # Custom tool ), ], include_server_side_tool_invocations=True ), ) history = [ types.Content( role=\"user\", parts=[types.Part(text=\"What is the northernmost city in the United States? What's the weather like there today?\")] ), response.candidates[0].content, types.Content( role=\"user\", parts=[types.Part( function_response=types.FunctionResponse( name=\"getWeather\", response={\"response\": \"Very cold. 22 degrees Fahrenheit.\"}, id=response.candidates[0].content.parts[2].function_call.id ) )] ) ] response_2 = client.models.generate_content( model=\"gemini-3-flash-preview\", contents=history, config=types.GenerateContentConfig( tools=[ types.Tool( google_search=types.ToolGoogleSearch(), function_declarations=[getWeather] ), ], include_server_side_tool_invocations=True ), )` Javascript`import { GoogleGenAI } from '@google/genai'; const client = new GoogleGenAI({}); const getWeather = { name: \"getWeather\", description: \"Get the weather in a given location\", parameters: { type: \"OBJECT\", properties: { location: { type: \"STRING\", description: \"The city and state, e.g. San Francisco, CA\" } }, required: [\"location\"] } }; async function run() { const tools = [ { googleSearch: {} }, { functionDeclarations: [getWeather] } ]; const toolConfig = { includeServerSideToolInvocations: true }; const response1 = await client.models.generateContent({ model: \"gemini-3-flash-preview\", contents: [{role: \"user\", parts: [{text: \"What is the northernmost city in the United States? What's the weather like there today?\"}]}], config: { tools: tools, toolConfig: toolConfig, }, }); const functionCallId = response1.candidates[0].content.parts.find(p => p.functionCall)?.functionCall?.id; const history = [ { role: \"user\", parts:[{text: \"What is the northernmost city in the United States? What's the weather like there today?\"}] }, response1.candidates[0].content, { role: \"user\", parts: [{ functionResponse: { name: \"getWeather\", response: {response: \"Very cold. 22 degrees Fahrenheit.\"}, id: functionCallId } }] } ]; const response2 = await client.models.generateContent({ model: \"gemini-3-flash-preview\", contents: history, config: { tools: tools, toolConfig: toolConfig, }, }); } run();` Migrating from Gemini 2.5 Gemini 3 is our most capable model family to date and offers a stepwise\nimprovement over Gemini 2.5. When migrating, consider the following: **Thinking:** If you were previously using complex prompt engineering (like\nchain of thought) to force Gemini 2.5 to reason, try Gemini 3 with\n`thinking_level: \"high\"` and simplified prompts. **Temperature settings:** If your existing code explicitly sets temperature\n(especially to low values for deterministic outputs), we recommend removing this\nparameter and using the Gemini 3 default of 1.0 to avoid potential looping\nissues or performance degradation on complex tasks. **PDF & document understanding:**\nIf you relied on specific behavior for dense document parsing, test the new\n`media_resolution_high` setting to ensure continued accuracy. **Token consumption:** Migrating to Gemini 3 defaults may **increase** token\nusage for PDFs but **decrease** token usage for video. If requests now exceed\nthe context window due to higher default resolutions, we recommend explicitly\nreducing the media resolution. **Image segmentation:** Image segmentation capabilities (returning pixel-level\nmasks for objects) are not supported in Gemini 3 Pro or Gemini 3 Flash. For\nworkloads requiring native image segmentation, we recommend continuing to\nutilize Gemini 2.5 Flash with thinking turned off. **Computer Use:** Gemini 3 Pro and Gemini 3 Flash support [Computer\nUse](/gemini-api/docs/computer-use). Unlike the 2.5 series, you don't need to\nuse a separate model to access the Computer Use tool. **Tool support**: [Combining built-in tools with function calling](/gemini-api/docs/tool-combination) is now supported for Gemini 3 models. [Maps\ngrounding](/gemini-api/docs/maps-grounding) is also now supported for Gemini 3\nmodels. **Candidate count**: Gemini 3 models do not support `candidateCount > 1`.\nSetting this parameter to a value greater than `1` will return a\n400 error. OpenAI compatibility For users utilizing the [OpenAI compatibility layer](/gemini-api/docs/openai),\nstandard parameters (OpenAI's `reasoning_effort`) are automatically mapped to\nGemini (`thinking_level`) equivalents. Prompting best practices Gemini 3 is a reasoning model, which changes how you should prompt. **Precise instructions:** Be concise in your input prompts. Gemini 3 responds\nbest to direct, clear instructions. It may over-analyze verbose or overly\ncomplex prompt engineering techniques used for older models. **Output verbosity:** By default, Gemini 3 is less verbose and prefers\nproviding direct, efficient answers. If your use case requires a more\nconversational or \"chatty\" persona, you must explicitly steer the model in the\nprompt (e.g., \"Explain this as a friendly, talkative assistant\"). **Context management:** When working with large datasets (e.g., entire books, \ncodebases, or long videos), place your specific instructions or questions at the\nend of the prompt, after the data context. Anchor the model's reasoning to the\nprovided data by starting your question with a phrase like, \"Based on the\ninformation above...\". Learn more about prompt design strategies in the [prompt engineering guide](/gemini-api/docs/prompting-strategies). FAQ **What is the knowledge cutoff for Gemini 3?** Gemini 3 models have a\nknowledge cutoff of January 2025. For more recent information, use the\n[Search Grounding](/gemini-api/docs/google-search) tool. **What are the context window limits?** Gemini 3 models support a 1 million\ntoken input context window and up to 64k tokens of output. **Is there a free tier for Gemini 3?** Gemini 3 Flash\n`gemini-3-flash-preview` and 3.1 Flash-Lite `gemini-3.1-flash-lite` have\nfree tiers in the Gemini API. You can try Gemini 3.1 Pro and 3 Flash for free in\nGoogle AI Studio, but there is no free tier available for\n`gemini-3.1-pro-preview` in the Gemini API. **Will my old `thinking_budget` code still work?** Yes, `thinking_budget` is\nstill supported for backward compatibility, but we recommend migrating to\n`thinking_level` for more predictable performance. Do not use both in the same\nrequest. **Does Gemini 3 support the Batch API?** Yes, Gemini 3 supports the\n[Batch API](/gemini-api/docs/batch-api). **Is Context Caching supported?** Yes, [Context Caching](/gemini-api/docs/caching) is supported for Gemini 3. **Which tools are supported in Gemini 3?** Gemini 3 supports [Google Search](/gemini-api/docs/google-search), [Grounding with Google Maps](/gemini-api/docs/maps-grounding), [File Search](/gemini-api/docs/file-search),\n[Code Execution](/gemini-api/docs/code-execution), and [URL Context](/gemini-api/docs/url-context). It also supports standard [Function Calling](/gemini-api/docs/function-calling) for your own custom tools,\nand in [combination with built-in tools](/gemini-api/docs/tool-combination). **What is `gemini-3.1-pro-preview-customtools`?** If you are using `gemini-3.1-pro-preview` and the model ignores your custom tools in favor of bash commands, try the `gemini-3.1-pro-preview-customtools` model instead. More info [here](/gemini-api/docs/models/gemini-3.1-pro-preview#gemini-31-pro-preview-customtools). Next steps Get started with the [Gemini 3 Cookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started.ipynb#templateParams=%7B%22MODEL_ID%22%3A+%22gemini-3-pro-preview%22%7D) Check the dedicated Cookbook guide on [thinking levels](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started_thinking_REST.ipynb#gemini3) and how to migrate from thinking budget to thinking levels. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-03 UTC.", "znaku_textu": 40320, "slov": 5431, "odkazu": 48, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:04", "sha256": "6ac32a6b6038f7b61fcc8032bcba7c5b7cb0c49a7e7898a8fe793cda9780028e", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.1-pro-preview", "https://aistudio.google.com/prompts/new_chat?model=gemini-3-flash-preview", "https://aistudio.google.com/prompts/new_chat?model=gemini-3-flash-lite", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.1-flash-image-preview", "https://aistudio.google.com/app/apps?showcaseTag=gemini-3&source=showcase", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started.ipynb", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started_thinking_REST.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/get-started", "titulek": "Getting started | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Getting started", "popis": "Get started with the Gemini API for Developers using generateContent", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/get-started", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Getting started  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Get started with the Gemini API for Developers using generateContent", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/get-started", "og:image": "https://ai.google.dev/static/site-assets/images/quickstart.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Getting started"}], "drobecky": ["Home", "Gemini API", "Generate Content API", "Docs"], "osnova": [{"uroven": 1, "text": "Getting started"}, {"uroven": 2, "text": "Get an API key"}, {"uroven": 3, "text": "Upgrade to the paid tier"}, {"uroven": 2, "text": "Install the Google GenAI SDK"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Generate text"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Stream responses"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Multi-turn conversations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Use tools"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Call custom functions"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "What's next"}], "markdown": "Getting started This guide will help you get started using the legacy **generateContent** API.\nFor new projects and applications, we strongly recommend using the new\n**Interactions API** instead, which is our simplest and best way to build with\nGemini models and agents. This quickstart shows you how to install our\n[libraries](/gemini-api/docs/libraries) and make your first request, stream\nresponses, build multi-turn conversations, and use tools using the standard\n`generateContent` method. Get an API key To use the Gemini API, you need to have an API key to authenticate your requests, enforce security limits, and track usage to your account. Google AI Studio automatically creates a project and API key for new users.\nYou can copy it from the [API keys page](https://aistudio.google.com/api-keys). If you need a new key, click **Create API key** in AI Studio and follow the\ndialog to add a new key-project pair. [Create a Gemini API Key](https://aistudio.google.com/apikey) Set your key as an environment variable: `export GEMINI_API_KEY=\"YOUR_API_KEY\"` Upgrade to the paid tier Upgrading to the paid tier increases your rate limits and requires setting up\nCloud Billing. Click **Set up billing** on the AI Studio\n[API keys](https://aistudio.google.com/api-keys) or\n[Projects](https://aistudio.google.com/projects) pages. Follow the Cloud Billing dialog to create or link a billing account, add a\npayment method, and prepay a minimum of $5 (or currency equivalent) in\npaid credits. View your API usage in [Google AI Studio](https://aistudio.google.com/usage)\nunder **Dashboard** > **Usage**. See the [Billing page](/gemini-api/docs/billing) for more information. Install the Google GenAI SDK PythonUsing [Python 3.9+](https://www.python.org/downloads/), install the\n[`google-genai` package](https://pypi.org/project/google-genai/)\nusing the following\n[pip command](https://packaging.python.org/en/latest/tutorials/installing-packages/): `pip install -q -U google-genai` JavaScriptUsing [Node.js v18+](https://nodejs.org/en/download/package-manager),\ninstall the\n[Google Gen AI SDK for TypeScript and JavaScript](https://www.npmjs.com/package/@google/genai)\nusing the following\n[npm command](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm): `npm install @google/genai` Generate text Use the `models.generate_content` method to\n[generate a text response](/gemini-api/docs/text-generation). Python`from google import genai client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Explain how AI works in a few words\" ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Explain how AI works in a few words\", }); console.log(response.text); } main();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"parts\": [ { \"text\": \"Explain how AI works in a few words\" } ] } ] }'` Stream responses By default, the model returns a response only after the entire generation\nprocess is complete. For a faster, more interactive experience, you can\n[stream the response](/gemini-api/docs/text-generation#stream) chunks as they\nare generated. Python`response = client.models.generate_content_stream( model=\"gemini-3.8-flash\", contents=\"Explain how AI works in detail\" ) for chunk in response: print(chunk.text, end=\"\", flush=True)` JavaScript`async function main() { const responseStream = await ai.models.generateContentStream({ model: \"gemini-3.8-flash\", contents: \"Explain how AI works in detail\", }); for await (const chunk of responseStream) { process.stdout.write(chunk.text); } } main();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ --no-buffer \\ -X POST \\ -d '{ \"contents\": [ { \"parts\": [ { \"text\": \"Explain how AI works in detail\" } ] } ] }'` Multi-turn conversations For multi-turn conversations, the SDKs provide a stateful `chats` helper to\nbuild a [multi-turn chat experience](/gemini-api/docs/text-generation#chat)\nthat automatically manages conversation history. Python`chat = client.chats.create(model=\"gemini-3.8-flash\") response1 = chat.send_message(\"I have 2 dogs in my house.\") print(\"Response 1:\", response1.text) response2 = chat.send_message(\"How many paws are in my house?\") print(\"Response 2:\", response2.text)` JavaScript`async function main() { const chat = ai.chats.create({ model: \"gemini-3.8-flash\" }); let response = await chat.sendMessage({ message: \"I have 2 dogs in my house.\" }); console.log(\"Response 1:\", response.text); response = await chat.sendMessage({ message: \"How many paws are in my house?\" }); console.log(\"Response 2:\", response.text); } main();` REST`# REST is stateless. You must pass the full conversation history in the request.\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"role\": \"user\", \"parts\": [{\"text\": \"I have 2 dogs in my house.\"}] }, { \"role\": \"model\", \"parts\": [{\"text\": \"That is nice! Two dogs mean you have plenty of company.\"}] }, { \"role\": \"user\", \"parts\": [{\"text\": \"How many paws are in my house?\"}] } ] }'` Use tools Extend the model's capabilities by\n[grounding responses with Google Search](/gemini-api/docs/google-search)\nto access real-time web content. The model automatically decides when to\nsearch, executes queries, and synthesizes a response. Python`from google import genai from google.genai import types config = types.GenerateContentConfig( tools=[types.Tool(google_search=types.GoogleSearch())] ) response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Who won the euro 2024?\", config=config ) print(response.text) metadata = response.candidates[0].grounding_metadata if metadata.web_search_queries: print(\"\\nSearch queries executed:\") for query in metadata.web_search_queries: print(f\" - {query}\") if metadata.grounding_chunks: print(\"\\nSources:\") for chunk in metadata.grounding_chunks: print(f\" - [{chunk.web.title}]({chunk.web.uri})\")` JavaScript`async function main() { const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Who won the euro 2024?\", config: { tools: [{ googleSearch: {} }] } }); console.log(response.text); const metadata = response.candidates[0]?.groundingMetadata; if (metadata?.webSearchQueries) { console.log(\"\\nSearch queries executed:\"); for (const query of metadata.webSearchQueries) { console.log(` - ${query}`); } } if (metadata?.groundingChunks) { console.log(\"\\nSources:\"); for (const chunk of metadata.groundingChunks) { console.log(` - [${chunk.web.title}](${chunk.web.uri})`); } } } main();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -X POST \\ -d '{ \"contents\": [ { \"parts\": [ {\"text\": \"Who won the euro 2024?\"} ] } ], \"tools\": [ { \"google_search\": {} } ] }'` The Gemini API also supports other built-in tools: **[Code execution](/gemini-api/docs/code-execution)**:\nLets the model write and run Python code to solve complex math problems. **[URL context](/gemini-api/docs/url-context)**: Lets you\nground responses in specific web page URLs you provide. **[File search](/gemini-api/docs/file-search)**: Lets you\nupload files and ground responses in their content using semantic search. **[Google Maps](/gemini-api/docs/maps-grounding)**: Lets you\nground responses in location data and search for places, directions, and\nmaps. **[Computer use](/gemini-api/docs/computer-use)**: Lets the\nmodel interact with a virtual computer screen, keyboard, and mouse to\nperform tasks. Call custom functions Use **[function calling](/gemini-api/docs/function-calling)** to connect\nmodels to your custom tools and APIs. The model determines when to call your\nfunction and returns a `functionCall` in the response for your application\nto execute. This example declares a mock temperature function and checks if the model\nwants to call it. Python`from google import genai from google.genai import types weather_function = { \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": { \"type\": \"string\", \"description\": \"The city name, e.g. San Francisco\", }, }, \"required\": [\"location\"], }, } tools = types.Tool(function_declarations=[weather_function]) config = types.GenerateContentConfig(tools=[tools]) contents = [\"What's the temperature in London?\"] response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=contents, config=config, ) part = response.candidates[0].content.parts[0] if part.function_call: fc = part.function_call print(f\"Model requested function: {fc.name} with args {fc.args}\") mock_result = {\"temperature\": \"15C\", \"condition\": \"Cloudy\"} contents.append(response.candidates[0].content) fn_response_part = types.Part.from_function_response( name=fc.name, response=mock_result, id=fc.id ) contents.append(types.Content(role=\"user\", parts=[fn_response_part])) final_response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=contents, config=config, ) print(\"Final Response:\", final_response.text)` JavaScript`import { GoogleGenAI, Type } from '@google/genai'; async function main() { const weatherFunction = { name: 'get_current_temperature', description: 'Gets the current temperature for a given location.', parameters: { type: Type.OBJECT, properties: { location: { type: Type.STRING, description: 'The city name, e.g. San Francisco', }, }, required: ['location'], }, }; const contents = [{ role: 'user', parts: [{ text: \"What's the temperature in London?\" }] }]; const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: contents, config: { tools: [{ functionDeclarations: [weatherFunction] }], }, }); if (response.functionCalls && response.functionCalls.length > 0) { const fc = response.functionCalls[0]; console.log(`Model requested function: ${fc.name}`); const mockResult = { temperature: \"15C\", condition: \"Cloudy\" }; contents.push(response.candidates[0].content); contents.push({ role: 'user', parts: [{ functionResponse: { name: fc.name, response: mockResult, id: fc.id } }] }); const finalResponse = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: contents, config: { tools: [{ functionDeclarations: [weatherFunction] }], }, }); console.log(\"Final Response:\", finalResponse.text); } } main();` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [ { \"role\": \"user\", \"parts\": [{\"text\": \"What'\\''s the temperature in London?\"}] } ], \"tools\": [ { \"functionDeclarations\": [ { \"name\": \"get_current_temperature\", \"description\": \"Gets the current temperature for a given location.\", \"parameters\": { \"type\": \"object\", \"properties\": { \"location\": { \"type\": \"string\", \"description\": \"The city name, e.g. San Francisco\" } }, \"required\": [\"location\"] } } ] } ] }'` What's next Now that you've got started with the Gemini API, explore the following\nguides to build more advanced applications: [Text generation](/gemini-api/docs/text-generation) [Image generation](/gemini-api/docs/image-generation) [Image understanding](/gemini-api/docs/image-understanding) [Thinking](/gemini-api/docs/thinking) [Function calling](/gemini-api/docs/function-calling) [Grounding with Google Search](/gemini-api/docs/google-search) [Long context](/gemini-api/docs/long-context) [Embeddings](/gemini-api/docs/embeddings) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 12415, "slov": 1541, "odkazu": 145, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:20", "sha256": "1f706b788b66b1882d6b994b1b80e73bb1e96bf81cfaf49f231b368d8ef46ec0", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/api-keys", "https://aistudio.google.com/projects", "https://aistudio.google.com/usage", "https://www.python.org/downloads/", "https://pypi.org/project/google-genai/", "https://packaging.python.org/en/latest/tutorials/installing-packages/", "https://nodejs.org/en/download/package-manager", "https://www.npmjs.com/package/@google/genai", "https://docs.npmjs.com/downloading-and-installing-node-js-and-npm", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/google-search", "titulek": "Grounding with Google Search | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Grounding with Google Search", "popis": "Ground your model's responses in real-time information from Google Search to improve factual accuracy and provide citations.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/google-search", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Grounding with Google Search  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Ground your model's responses in real-time information from Google Search to improve factual accuracy and provide citations.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/google-search", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Grounding with Google Search"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Grounding with Google Search", "item": "https://ai.google.dev/gemini-api/docs/generate-content/google-search"}]}], "drobecky": ["Generate Content API", "Grounding with Google Search"], "osnova": [{"uroven": 1, "text": "Grounding with Google Search"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How grounding with Google Search works"}, {"uroven": 2, "text": "Understanding the grounding response"}, {"uroven": 2, "text": "Attributing sources with inline citations"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "Supported models"}, {"uroven": 2, "text": "Supported tool combinations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Grounding with Google Search Grounding with Google Search connects the Gemini model to real-time web content\nand works with all available languages. This allows\nGemini to provide more accurate answers and cite verifiable sources beyond its\nknowledge cutoff. Grounding helps you build applications that can: **Increase factual accuracy:** Reduce model hallucinations by basing\nresponses on real-world information. **Access real-time information:** Answer questions about recent events and\ntopics. **Provide citations:** Build user trust by showing the sources for the\nmodel's claims. Python`from google import genai from google.genai import types client = genai.Client() grounding_tool = types.Tool( google_search=types.GoogleSearch() ) config = types.GenerateContentConfig( tools=[grounding_tool] ) response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Who won the euro 2024?\", config=config, ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); const groundingTool = { googleSearch: {}, }; const config = { tools: [groundingTool], }; const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Who won the euro 2024?\", config, }); console.log(response.text);` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -X POST \\ -d '{ \"contents\": [ { \"parts\": [ {\"text\": \"Who won the euro 2024?\"} ] } ], \"tools\": [ { \"google_search\": {} } ] }'` You can learn more by trying the [Search tool\nnotebook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Search_Grounding.ipynb). How grounding with Google Search works When you enable the `google_search` tool, the model handles the entire workflow\nof searching, processing, and citing information automatically. **User Prompt:** Your application sends a user's prompt to the Gemini API\nwith the `google_search` tool enabled. **Prompt Analysis:** The model analyzes the prompt and determines if a\nGoogle Search can improve the answer. **Google Search:** If needed, the model automatically generates one or\nmultiple search queries and executes them. **Search Results Processing:** The model processes the search results,\nsynthesizes the information, and formulates a response. **Grounded Response:** The API returns a final, user-friendly response that\nis grounded in the search results. This response includes the model's text\nanswer and `groundingMetadata` with the search queries, web results, and\ncitations. Understanding the grounding response When a response is successfully grounded, the response includes a\n`groundingMetadata` field. This structured data is essential for verifying\nclaims and building a rich citation experience in your application. `{ \"candidates\": [ { \"content\": { \"parts\": [ { \"text\": \"Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title.\" } ], \"role\": \"model\" }, \"groundingMetadata\": { \"webSearchQueries\": [ \"UEFA Euro 2024 winner\", \"who won euro 2024\" ], \"searchEntryPoint\": { \"renderedContent\": \"\" }, \"groundingChunks\": [ {\"web\": {\"uri\": \"https://vertexaisearch.cloud.google.com.....\", \"title\": \"aljazeera.com\"}}, {\"web\": {\"uri\": \"https://vertexaisearch.cloud.google.com.....\", \"title\": \"uefa.com\"}} ], \"groundingSupports\": [ { \"segment\": {\"startIndex\": 0, \"endIndex\": 85, \"text\": \"Spain won Euro 2024, defeatin...\"}, \"groundingChunkIndices\": [0] }, { \"segment\": {\"startIndex\": 86, \"endIndex\": 210, \"text\": \"This victory marks Spain's...\"}, \"groundingChunkIndices\": [0, 1] } ] } } ] }` The Gemini API returns the following information with the `groundingMetadata`: `webSearchQueries` : Array of the search queries used. This is useful for\ndebugging and understanding the model's reasoning process. `searchEntryPoint` : Contains the HTML and CSS to render the required Search\nSuggestions. Full usage requirements are detailed in the [Terms of\nService](/gemini-api/terms#grounding-with-google-search). `groundingChunks` : Array of objects containing the web sources (`uri` and\n`title`). `groundingSupports` : Array of chunks to connect model response `text` to\nthe sources in `groundingChunks`. Each chunk links a text `segment` (defined\nby `startIndex` and `endIndex`) to one or more `groundingChunkIndices`. This\nis the key to building inline citations. Grounding with Google Search can also be used in combination with the [URL\ncontext tool](/gemini-api/docs/url-context) to ground responses in both public\nweb data and the specific URLs you provide. Attributing sources with inline citations The API returns structured citation data, giving you complete control over how\nyou display sources in your user interface. You can use the `groundingSupports`\nand `groundingChunks` fields to link the model's statements directly to their\nsources. Here is a common pattern for processing the metadata to create a\nresponse with inline, clickable citations. Python`def add_citations(response): text = response.text supports = response.candidates[0].grounding_metadata.grounding_supports chunks = response.candidates[0].grounding_metadata.grounding_chunks # Sort supports by end_index in descending order to avoid shifting issues when inserting. sorted_supports = sorted(supports, key=lambda s: s.segment.end_index, reverse=True) for support in sorted_supports: end_index = support.segment.end_index if support.grounding_chunk_indices: # Create citation string like [1](link1)[2](link2) citation_links = [] for i in support.grounding_chunk_indices: if i < len(chunks): uri = chunks[i].web.uri citation_links.append(f\"[{i + 1}]({uri})\") citation_string = \", \".join(citation_links) text = text[:end_index] + citation_string + text[end_index:] return text # Assuming response with grounding metadata text_with_citations = add_citations(response) print(text_with_citations)` JavaScript`function addCitations(response) { let text = response.text; const supports = response.candidates[0]?.groundingMetadata?.groundingSupports; const chunks = response.candidates[0]?.groundingMetadata?.groundingChunks; // Sort supports by end_index in descending order to avoid shifting issues when inserting. const sortedSupports = [...supports].sort( (a, b) => (b.segment?.endIndex ?? 0) - (a.segment?.endIndex ?? 0), ); for (const support of sortedSupports) { const endIndex = support.segment?.endIndex; if (endIndex === undefined || !support.groundingChunkIndices?.length) { continue; } const citationLinks = support.groundingChunkIndices .map(i => { const uri = chunks[i]?.web?.uri; if (uri) { return `[${i + 1}](${uri})`; } return null; }) .filter(Boolean); if (citationLinks.length > 0) { const citationString = citationLinks.join(\", \"); text = text.slice(0, endIndex) + citationString + text.slice(endIndex); } } return text; } const textWithCitations = addCitations(response); console.log(textWithCitations);` The new response with inline citations will look like this: `Spain won Euro 2024, defeating England 2-1 in the final.[1](https:/...), [2](https:/...), [4](https:/...), [5](https:/...) This victory marks Spain's record-breaking fourth European Championship title.[5]((https:/...), [2](https:/...), [3](https:/...), [4](https:/...)` Pricing When you use Grounding with Google Search with Gemini 3, your project is billed\nfor each search query that the model decides to execute. If the model decides to\nexecute multiple search queries to answer a single prompt (for example,\nsearching for `\"UEFA Euro 2024 winner\"` and `\"Spain vs England Euro 2024 final\nscore\"` within the same API call), this counts as two billable uses of the tool\nfor that request. For billing purposes, we ignore the empty web search queries\nwhen counting unique queries. This billing model only applies to Gemini 3\nmodels; when you use search grounding with Gemini 2.5 or older models, your\nproject is billed per prompt. For detailed pricing information, see the [Gemini API pricing\npage](/gemini-api/docs/pricing). Supported models You can find full capabilities on the [model\noverview](https://ai.google.dev/gemini-api/docs/models) page. Model Grounding with Google Search Gemini 3.8 Flash ✔️ Gemini 3.7 Flash ✔️ Gemini 3.6 Flash ✔️ Gemini 3.5 Flash-Lite ✔️ Gemini 3.5 Flash ✔️ Gemini 3.1 Flash-Lite ✔️ Gemini 3.1 Flash Image Preview ✔️ Gemini 3.1 Pro Preview ✔️ Gemini 3 Pro Image Preview ✔️ Gemini 3 Flash Preview ✔️ Gemini 3.1 Flash-Lite Preview ✔️ Gemini 2.5 Pro ✔️ Gemini 2.5 Flash ✔️ Gemini 2.5 Flash-Lite ✔️ Gemini 2.0 Flash ✔️ Supported tool combinations You can use Grounding with Google Search with other tools like\n[code execution](/gemini-api/docs/code-execution),\n[URL context](/gemini-api/docs/url-context), and\n[Grounding with Google Maps](/gemini-api/docs/maps-grounding) (supported on\nGemini 3.5 Flash and later models) to power more complex use cases. Gemini 3\nmodels also support combining these built-in tools with custom tools (function\ncalling). Learn more on the\n[tool combinations](/gemini-api/docs/tool-combination) page. What's next Try the [Grounding with Google Search in the Gemini API\nCookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Search_Grounding.ipynb). Learn about other available tools, like [Function Calling](/gemini-api/docs/function-calling). Learn how to augment prompts with specific URLs using the [URL context\ntool](/gemini-api/docs/url-context). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 9984, "slov": 1298, "odkazu": 130, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:57", "sha256": "77bda85dd559906a7be9a3e9725f5a0ae7857e172c1bcc9f4aafcc2f45fe5ee1", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Search_Grounding.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/image-generation", "titulek": "Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Nano Banana image generation", "popis": "Get started generating images with the Gemini API using Nano Banana and Nano Banana Pro", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/image-generation", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Get started generating images with the Gemini API using Nano Banana and Nano Banana Pro", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/image-generation", "og:image": "https://ai.google.dev/static/site-assets/images/image-generation.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": ""}], "drobecky": ["Home", "Gemini API", "Generate Content API", "Docs"], "osnova": [{"uroven": 1, "text": "Nano Banana image generation"}, {"uroven": 2, "text": "Image generation (text-to-image)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Image editing (text-and-image-to-image)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Multi-turn image editing"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "New with Gemini 3 image models"}, {"uroven": 3, "text": "Use up to 14 reference images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Grounding with Google Search"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Grounding with Google Search for images (3.1 Flash)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Video-to-image generation (3.1 Flash and 3.1 Flash Lite)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Generate images up to 4K resolution"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Thinking process"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 4, "text": "Controlling thinking levels"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 4, "text": "Thought signatures"}, {"uroven": 2, "text": "Other image generation modes"}, {"uroven": 2, "text": "Generate images in batch"}, {"uroven": 2, "text": "Prompting guide and strategies"}, {"uroven": 3, "text": "Prompts for generating images"}, {"uroven": 4, "text": "Photography"}, {"uroven": 4, "text": "Stylized illustrations and stickers"}, {"uroven": 4, "text": "Accurate text in images"}, {"uroven": 4, "text": "Product mockups and commercial photography"}, {"uroven": 4, "text": "Minimalist and negative space design"}, {"uroven": 4, "text": "Sequential art (comic panel / storyboard)"}, {"uroven": 4, "text": "Grounding with Google Search"}, {"uroven": 3, "text": "Prompts for editing images"}, {"uroven": 4, "text": "Adding and removing elements"}, {"uroven": 4, "text": "Inpainting (semantic masking)"}, {"uroven": 4, "text": "Style transfer"}, {"uroven": 4, "text": "Advanced composition: combining multiple images"}, {"uroven": 4, "text": "High-fidelity detail preservation"}, {"uroven": 4, "text": "Bring something to life"}, {"uroven": 4, "text": "Character consistency: 360 view"}, {"uroven": 3, "text": "Best practices"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "Optional configurations"}, {"uroven": 3, "text": "Output types"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Aspect ratios and image size"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "3.1 Flash Image"}, {"uroven": 3, "text": "3.1 Flash Lite Image"}, {"uroven": 3, "text": "3.1 Pro Image"}, {"uroven": 3, "text": "Gemini 2.5 Flash Image"}, {"uroven": 2, "text": "Model selection"}, {"uroven": 3, "text": "When to use Imagen"}, {"uroven": 2, "text": "What's next"}], "markdown": "Nano Banana image generation \n Prompt to prototype fully-functional, UI-complete apps, and see\n Nano Banana 2 integrated with real-world tools, data, and the Gemini\n ecosystem. All before writing a single line of code.\n [Try a Nano Banana 2 app](https://aistudio.google.com/apps/bundled/pet_passport) Or build your own from prompts: Generated by Nano Banana 2 **Prompt:** \"A photo of a glossy magazine cover, the minimal blue cover has the large bold words Nano Banana. The text is in a serif font and fills the view. No other text. In front of the text there is a portrait of a person in a sleek and minimal dress. She is playfully holding the number 2, which is the focal point.\n \nPut the issue number and \"Feb 2026\" date in the corner along with a barcode. The magazine is on a shelf against an orange plastered wall, within a designer store.\"\n Create professional product shots in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2) Generated by Nano Banana Pro **Prompt:** \"Present a clear, 45° top-down isometric miniature 3D cartoon scene of London, featuring its most iconic landmarks and architectural elements. Use soft, refined textures with realistic PBR materials and gentle, lifelike lighting and shadows. Integrate the current weather conditions directly into the city environment to create an immersive atmospheric mood. Use a clean, minimalistic composition with a soft, solid-colored background. At the top-center, place the title \"London\" in large bold text, a prominent weather icon beneath it, then the date (small text) and temperature (medium text). All text must be centered with consistent spacing, and may subtly overlap the tops of the buildings.\"\n Learn more about search grounding and try it in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2,search_grounding) Generated by Nano Banana 2 **Prompt:** \"Use image search to find accurate images of a resplendent quetzal bird. Create a beautiful 3:2 wallpaper of this bird, with a natural top to bottom gradient and minimal composition.\"\n Use Google Image Search grounding with Nano Banana 2. Try it in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2,search_grounding) Generated by Nano Banana Pro **Prompt:** \"Put this logo on a high-end ad for a banana scented perfume. The logo is perfectly integrated into the bottle.\"\n Try Nano Banana's high fidelity detail preservation in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2) Generated by Nano Banana Pro **Prompt:** \"A photo of an everyday scene at a busy cafe serving breakfast. In the foreground is an anime man with blue hair, one of the people is a pencil sketch, another is a claymation person\"\n Experiment with different artistic styles with Nano Banana in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2) Generated by Nano Banana Pro **Prompt:** \"Use search to find how the Gemini 3 Flash launch has been received. Use this information to write a short article about it (with headings). Return a photo of the article as it appeared in a design focused glossy magazine. It is a photo of a single folded over page, showing the article about Gemini 3 Flash. One hero photo. Headline in serif.\"\n Generate accurate text from search. Try Nano Banana in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2,search_grounding) Generated by Nano Banana Pro **Prompt:** \"An icon representing a cute dog. The background is white. Make the icons in a colorful and tactile 3D style. No text.\"\n Create icons, stickers, and assets with Nano Banana in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2,search_grounding) Generated by Nano Banana 2 **Prompt:** \"Make a photo that is perfectly isometric. It is not a miniature, it is a captured photo that just happened to be perfectly isometric. It is a photo of a beautiful modern garden. There's a large 2 shaped pool and the words: Nano Banana 2.\"\n Try photorealistic image generation in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2) **Nano Banana** is the name for Gemini's native image generation capabilities.\nGemini can generate and process images conversationally\nwith text, images, video, or a combination. This lets you create, edit, and\niterate on visuals with unprecedented control. Nano Banana refers to four distinct models available in the Gemini API: **Nano Banana 2 Lite ([Gemini 3.1 Flash Lite Image](/gemini-api/docs/models/gemini-3.1-flash-lite-image))\n(`gemini-3.1-flash-lite-image`):** Our fastest and cheapest Gemini image\nmodel, engineered for velocity and scale where speed and cost are the\nprimary operational constraints. Not optimized for multiple reference inputs\nor multi-turn sequential editing. **Nano Banana 2 ([Gemini 3.1 Flash Image](/gemini-api/docs/models/gemini-3.1-flash-image))\n(`gemini-3.1-flash-image`):** Serves as the most versatile model, generalist\nworkhorse model for all tasks. It balances speed with state-of-the-art 4K\ngeneration, world knowledge, and reliable text rendering. Excelling at\nmultiple reference image processing and consistency. **Nano Banana Pro ([Gemini 3 Pro Image](/gemini-api/docs/models/gemini-3-pro-image))\n(`gemini-3-pro-image`):** The premium choice for the most complex visual\ntasks, offering the highest level of world knowledge, advanced localization,\naccurate brand consistency, and precision creative control. **Nano Banana ([Gemini 2.5 Flash Image](/gemini-api/docs/models/gemini-2.5-flash-image))\n(`gemini-2.5-flash-image`):** The legacy pioneer of the Nano Banana series.\nWhile it has been a reliable workhorse, we strongly recommend that customers\ntransition to Nano Banana 2 Lite to experience enhanced quality, faster\ngeneration speeds, and lower API pricing. All generated images include a [SynthID watermark](/responsible/docs/safeguards/synthid). Image generation (text-to-image) Python`from google import genai from google.genai import types from PIL import Image client = genai.Client() prompt = (\"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme\") response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=[prompt], ) for part in response.parts: if part.text is not None: print(part.text) elif part.inline_data is not None: image = part.as_image() image.save(\"generated_image.png\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const prompt = \"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme\"; const response = await ai.models.generateContent({ model: \"gemini-3.1-flash-image\", contents: prompt, }); for (const part of response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, \"base64\"); fs.writeFileSync(\"gemini-native-image.png\", buffer); console.log(\"Image saved as gemini-native-image.png\"); } } } main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"os\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.1-flash-image\", genai.Text(\"Create a picture of a nano banana dish in a \" + \" fancy restaurant with a Gemini theme\"), ) for _, part := range result.Candidates[0].Content.Parts { if part.Text != \"\" { fmt.Println(part.Text) } else if part.InlineData != nil { imageBytes := part.InlineData.Data outputFilename := \"gemini_generated_image.png\" _ = os.WriteFile(outputFilename, imageBytes, 0644) } } }` Java`import com.google.genai.Client; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.Part; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class TextToImage { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"TEXT\", \"IMAGE\") .build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.1-flash-image\", \"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme\", config); for (Part part : response.parts()) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"_01_generated_image.png\"), blob.data().get()); } } } } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class TextToImage { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme\" } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"generated_image.png\", imageBytes); Console.WriteLine(\"Image saved as generated_image.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme\"} ] }] }'` Image editing (text-and-image-to-image) **Reminder**: Make sure you have the necessary rights to any images you upload.\nDon't generate content that infringe on others' rights, including videos or\nimages that deceive, harass, or harm. Your use of this generative AI service is\nsubject to our [Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy). Provide an image and use text prompts to add, remove, or modify elements,\nchange the style, or adjust the color grading. The following example demonstrates uploading `base64` encoded images.\nFor multiple images, larger payloads, and supported MIME types, check the [Image\nunderstanding](/gemini-api/docs/image-understanding) page. Python`from google import genai from google.genai import types from PIL import Image client = genai.Client() prompt = ( \"Create a picture of my cat eating a nano-banana in a \" \"fancy restaurant under the Gemini constellation\", ) image = Image.open(\"/path/to/cat_image.png\") response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=[prompt, image], ) for part in response.parts: if part.text is not None: print(part.text) elif part.inline_data is not None: image = part.as_image() image.save(\"generated_image.png\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const imagePath = \"path/to/cat_image.png\"; const imageData = fs.readFileSync(imagePath); const base64Image = imageData.toString(\"base64\"); const prompt = [ { text: \"Create a picture of my cat eating a nano-banana in a\" + \"fancy restaurant under the Gemini constellation\" }, { inlineData: { mimeType: \"image/png\", data: base64Image, }, }, ]; const response = await ai.models.generateContent({ model: \"gemini-3.1-flash-image\", contents: prompt, }); for (const part of response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, \"base64\"); fs.writeFileSync(\"gemini-native-image.png\", buffer); console.log(\"Image saved as gemini-native-image.png\"); } } } main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"os\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } imagePath := \"/path/to/cat_image.png\" imgData, _ := os.ReadFile(imagePath) parts := []*genai.Part{ genai.NewPartFromText(\"Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\"), &genai.Part{ InlineData: &genai.Blob{ MIMEType: \"image/png\", Data: imgData, }, }, } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.1-flash-image\", contents, ) for _, part := range result.Candidates[0].Content.Parts { if part.Text != \"\" { fmt.Println(part.Text) } else if part.InlineData != nil { imageBytes := part.InlineData.Data outputFilename := \"gemini_generated_image.png\" _ = os.WriteFile(outputFilename, imageBytes, 0644) } } }` Java`import com.google.genai.Client; import com.google.genai.types.Content; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.Part; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class TextAndImageToImage { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"TEXT\", \"IMAGE\") .build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.1-flash-image\", Content.fromParts( Part.fromText(\"\"\" Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation \"\"\"), Part.fromBytes( Files.readAllBytes( Path.of(\"src/main/resources/cat.jpg\")), \"image/jpeg\")), config); for (Part part : response.parts()) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"gemini_generated_image.png\"), blob.data().get()); } } } } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class TextAndImageToImage { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\" }, new Part { FileData = new FileData { FileUri = \"file:///path/to/cat_image.png\" } } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"gemini_generated_image.png\", imageBytes); Console.WriteLine(\"Image saved as gemini_generated_image.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d \"{ \\\"contents\\\": [{ \\\"parts\\\":[ {\\\"text\\\": \\\"'Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\\\"}, { \\\"inline_data\\\": { \\\"mime_type\\\":\\\"image/jpeg\\\", \\\"data\\\": \\\"\\\" } } ] }] }\"` Multi-turn image editing Keep generating and editing images conversationally. Chat or multi-turn\nconversation is the recommended way to iterate on images. The following\nexample shows a prompt to generate an infographic about photosynthesis. Python`from google import genai from google.genai import types client = genai.Client() chat = client.chats.create( model=\"gemini-3.1-flash-image\", config=types.GenerateContentConfig( response_modalities=['TEXT', 'IMAGE'], tools=[{\"google_search\": {}}] ) ) message = \"Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \\\"ingredients\\\" (sunlight, water, CO2) and the \\\"finished dish\\\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.\" response = chat.send_message(message) for part in response.parts: if part.text is not None: print(part.text) elif image:= part.as_image(): image.save(\"photosynthesis.png\")` Javascript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const chat = ai.chats.create({ model: \"gemini-3.1-flash-image\", config: { responseModalities: ['TEXT', 'IMAGE'], tools: [{googleSearch: {}}], }, }); } await main(); const message = \"Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \\\"ingredients\\\" (sunlight, water, CO2) and the \\\"finished dish\\\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.\" let response = await chat.sendMessage({message}); for (const part of response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, \"base64\"); fs.writeFileSync(\"photosynthesis.png\", buffer); console.log(\"Image saved as photosynthesis.png\"); } }` Go`package main import ( \"context\" \"fmt\" \"log\" \"os\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() model := client.GenerativeModel(\"gemini-3.1-flash-image\") model.GenerationConfig = &pb.GenerationConfig{ ResponseModalities: []pb.ResponseModality{genai.Text, genai.Image}, } chat := model.StartChat() message := \"Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \\\"ingredients\\\" (sunlight, water, CO2) and the \\\"finished dish\\\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.\" resp, err := chat.SendMessage(ctx, genai.Text(message)) if err != nil { log.Fatal(err) } for _, part := range resp.Candidates[0].Content.Parts { if txt, ok := part.(genai.Text); ok { fmt.Printf(\"%s\", string(txt)) } else if img, ok := part.(genai.ImageData); ok { err := os.WriteFile(\"photosynthesis.png\", img.Data, 0644) if err != nil { log.Fatal(err) } } } }` Java`import com.google.genai.Chat; import com.google.genai.Client; import com.google.genai.types.Content; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.GoogleSearch; import com.google.genai.types.ImageConfig; import com.google.genai.types.Part; import com.google.genai.types.RetrievalConfig; import com.google.genai.types.Tool; import com.google.genai.types.ToolConfig; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class MultiturnImageEditing { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"TEXT\", \"IMAGE\") .tools(Tool.builder() .googleSearch(GoogleSearch.builder().build()) .build()) .build(); Chat chat = client.chats.create(\"gemini-3.1-flash-image\", config); GenerateContentResponse response = chat.sendMessage(\"\"\" Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader. \"\"\"); for (Part part : response.parts()) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"photosynthesis.png\"), blob.data().get()); } } } // ... } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class MultiturnImageEditing { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \\\"ingredients\\\" (sunlight, water, CO2) and the \\\"finished dish\\\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.\" } }, config: new GenerateContentConfig { ResponseModalities = new List { \"TEXT\", \"IMAGE\" }, Tools = new List { new Tool { GoogleSearch = new GoogleSearch() } } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"photosynthesis.png\", imageBytes); Console.WriteLine(\"Image saved as photosynthesis.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"role\": \"user\", \"parts\": [ {\"text\": \"Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plants favorite food. Show the \\\"ingredients\\\" (sunlight, water, CO2) and the \\\"finished dish\\\" (sugar/energy). The style should be like a page from a colorful kids cookbook, suitable for a 4th grader.\"} ] }], \"generationConfig\": { \"responseModalities\": [\"TEXT\", \"IMAGE\"] } }'` AI-generated infographic about photosynthesis You can then use the same chat to change the language on the graphic to Spanish. Python`message = \"Update this infographic to be in Spanish. Do not change any other elements of the image.\" aspect_ratio = \"16:9\" # \"1:1\",\"1:4\",\"1:8\",\"2:3\",\"3:2\",\"3:4\",\"4:1\",\"4:3\",\"4:5\",\"5:4\",\"8:1\",\"9:16\",\"16:9\",\"21:9\" resolution = \"2K\" # \"512\", \"1K\", \"2K\", \"4K\" response = chat.send_message(message, config=types.GenerateContentConfig( response_format={\"image\": {aspect_ratio: aspect_ratio, image_size: resolution}}, )) for part in response.parts: if part.text is not None: print(part.text) elif image:= part.as_image(): image.save(\"photosynthesis_spanish.png\")` Javascript`const message = 'Update this infographic to be in Spanish. Do not change any other elements of the image.'; const aspectRatio = '16:9'; const resolution = '2K'; let response = await chat.sendMessage({ message, config: { responseModalities: ['TEXT', 'IMAGE'], responseFormat: { image: { aspectRatio: aspectRatio, imageSize: resolution, } }, tools: [{googleSearch: {}}], }, }); for (const part of response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, \"base64\"); fs.writeFileSync(\"photosynthesis2.png\", buffer); console.log(\"Image saved as photosynthesis2.png\"); } }` Go`message = \"Update this infographic to be in Spanish. Do not change any other elements of the image.\" aspect_ratio = \"16:9\" // \"1:1\",\"1:4\",\"1:8\",\"2:3\",\"3:2\",\"3:4\",\"4:1\",\"4:3\",\"4:5\",\"5:4\",\"8:1\",\"9:16\",\"16:9\",\"21:9\" resolution = \"2K\" // \"512\", \"1K\", \"2K\", \"4K\" model.GenerationConfig.ImageConfig = &pb.ImageConfig{ AspectRatio: aspect_ratio, ImageSize: resolution, } resp, err = chat.SendMessage(ctx, genai.Text(message)) if err != nil { log.Fatal(err) } for _, part := range resp.Candidates[0].Content.Parts { if txt, ok := part.(genai.Text); ok { fmt.Printf(\"%s\", string(txt)) } else if img, ok := part.(genai.ImageData); ok { err := os.WriteFile(\"photosynthesis_spanish.png\", img.Data, 0644) if err != nil { log.Fatal(err) } } }` Java`String aspectRatio = \"16:9\"; // \"1:1\",\"1:4\",\"1:8\",\"2:3\",\"3:2\",\"3:4\",\"4:1\",\"4:3\",\"4:5\",\"5:4\",\"8:1\",\"9:16\",\"16:9\",\"21:9\" String resolution = \"2K\"; // \"512\", \"1K\", \"2K\", \"4K\" config = GenerateContentConfig.builder() .responseModalities(\"TEXT\", \"IMAGE\") .imageConfig(ImageConfig.builder() .aspectRatio(aspectRatio) .imageSize(resolution) .build()) .build(); response = chat.sendMessage( \"Update this infographic to be in Spanish. \" + \"Do not change any other elements of the image.\", config); for (Part part : response.parts()) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"photosynthesis_spanish.png\"), blob.data().get()); } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class MultiturnImageEditingSpanish { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"Update this infographic to be in Spanish. Do not change any other elements of the image.\" } }, config: new GenerateContentConfig { ResponseModalities = new List { \"TEXT\", \"IMAGE\" }, ImageConfig = new ImageConfig { AspectRatio = \"16:9\", ImageSize = \"2K\" } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"photosynthesis_spanish.png\", imageBytes); Console.WriteLine(\"Image saved as photosynthesis_spanish.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"contents\": [ { \"role\": \"user\", \"parts\": [{\"text\": \"Create a vibrant infographic that explains photosynthesis...\"}] }, { \"role\": \"model\", \"parts\": [{\"inline_data\": {\"mime_type\": \"image/png\", \"data\": \"\"}}] }, { \"role\": \"user\", \"parts\": [{\"text\": \"Update this infographic to be in Spanish. Do not change any other elements of the image.\"}] } ], \"tools\": [{\"google_search\": {}}], \"generationConfig\": { \"responseModalities\": [\"TEXT\", \"IMAGE\"], \"responseFormat\": { \"image\": { \"aspectRatio\": \"16:9\", \"imageSize\": \"2K\" } } } }'` AI-generated infographic of photosynthesis in Spanish New with Gemini 3 image models Gemini 3 offers state-of-the-art image generation and editing models. Gemini 3.1\nFlash Image is optimized for speed and high-volume use-cases, and Gemini 3\nPro Image is optimized for professional asset production.\nDesigned to tackle the most challenging workflows through advanced reasoning,\nthey excel at complex, multi-turn creation and modification tasks. **High-resolution output**: Built-in generation capabilities for 1K, 2K, and 4K visuals.\n **Gemini 3.1 Flash Image** adds the smaller 512 (0.5K) resolution. **Gemini 3.1 Flash Lite Image** only supports 1K resolution. **Advanced text rendering**: Capable of generating legible, stylized text for\ninfographics, menus, diagrams, and marketing assets. **Grounding with Google Search**: The model can use Google Search as a tool to\nverify facts and generate imagery based on real-time data (e.g., current\nweather maps, stock charts, recent events).\n **Not supported by Gemini 3.1 Flash Lite Image model.** **Gemini 3.1 Flash Image** adds the integration of Grounding with Google Search for Images alongside Web Search. **Thinking mode**: The model utilizes a \"thinking\" process to reason through\ncomplex prompts. It generates interim \"thought images\" (visible in the backend\nbut not charged) to refine the composition before producing the final\nhigh-quality output. **Up to 14 reference images**: You can now mix up to 14 reference images to\nproduce the final image. **New aspect ratios**: Gemini 3.1 Flash Lite Image adds `1:1`, `3:2`,\n`2:3`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` aspect ratios. Use up to 14 reference images Gemini 3 image models let you to mix up to 14 reference images. These 14 images\ncan include the following: Gemini 3.1 Flash Lite Image Gemini 3.1 Flash Image Gemini 3 Pro Image Up to 14 images of objects with high-fidelity to include in the final image Up to 10 images of objects with high-fidelity to include in the final image Up to 6 images of objects with high-fidelity to include in the final image N/A Up to 4 images of characters to maintain character consistency Up to 5 images of characters to maintain character consistency N/A N/A Up to 3 images to be used as style references Python`from google import genai from google.genai import types from PIL import Image prompt = \"An office group photo of these people, they are making funny faces.\" aspect_ratio = \"5:4\" # \"1:1\",\"1:4\",\"1:8\",\"2:3\",\"3:2\",\"3:4\",\"4:1\",\"4:3\",\"4:5\",\"5:4\",\"8:1\",\"9:16\",\"16:9\",\"21:9\" resolution = \"2K\" # \"512\", \"1K\", \"2K\", \"4K\" client = genai.Client() response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=[ prompt, Image.open('person1.png'), Image.open('person2.png'), Image.open('person3.png'), Image.open('person4.png'), Image.open('person5.png'), ], config=types.GenerateContentConfig( response_modalities=['TEXT', 'IMAGE'], response_format={\"image\": {aspect_ratio: aspect_ratio, image_size: resolution}}, ) ) for part in response.parts: if part.text is not None: print(part.text) elif image:= part.as_image(): image.save(\"office.png\")` Javascript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const prompt = 'An office group photo of these people, they are making funny faces.'; const aspectRatio = '5:4'; const resolution = '2K'; const contents = [ { text: prompt }, { inlineData: { mimeType: \"image/jpeg\", data: base64ImageFile1, }, }, { inlineData: { mimeType: \"image/jpeg\", data: base64ImageFile2, }, }, { inlineData: { mimeType: \"image/jpeg\", data: base64ImageFile3, }, }, { inlineData: { mimeType: \"image/jpeg\", data: base64ImageFile4, }, }, { inlineData: { mimeType: \"image/jpeg\", data: base64ImageFile5, }, } ]; const response = await ai.models.generateContent({ model: 'gemini-3.1-flash-image', contents: contents, config: { responseModalities: ['TEXT', 'IMAGE'], responseFormat: { image: { aspectRatio: aspectRatio, imageSize: resolution, } }, }, }); for (const part of response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, \"base64\"); fs.writeFileSync(\"image.png\", buffer); console.log(\"Image saved as image.png\"); } } } main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"os\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() model := client.GenerativeModel(\"gemini-3.1-flash-image\") model.GenerationConfig = &pb.GenerationConfig{ ResponseModalities: []pb.ResponseModality{genai.Text, genai.Image}, ImageConfig: &pb.ImageConfig{ AspectRatio: \"5:4\", ImageSize: \"2K\", }, } img1, err := os.ReadFile(\"person1.png\") if err != nil { log.Fatal(err) } img2, err := os.ReadFile(\"person2.png\") if err != nil { log.Fatal(err) } img3, err := os.ReadFile(\"person3.png\") if err != nil { log.Fatal(err) } img4, err := os.ReadFile(\"person4.png\") if err != nil { log.Fatal(err) } img5, err := os.ReadFile(\"person5.png\") if err != nil { log.Fatal(err) } parts := []genai.Part{ genai.Text(\"An office group photo of these people, they are making funny faces.\"), genai.ImageData{MIMEType: \"image/png\", Data: img1}, genai.ImageData{MIMEType: \"image/png\", Data: img2}, genai.ImageData{MIMEType: \"image/png\", Data: img3}, genai.ImageData{MIMEType: \"image/png\", Data: img4}, genai.ImageData{MIMEType: \"image/png\", Data: img5}, } resp, err := model.GenerateContent(ctx, parts...) if err != nil { log.Fatal(err) } for _, part := range resp.Candidates[0].Content.Parts { if txt, ok := part.(genai.Text); ok { fmt.Printf(\"%s\", string(txt)) } else if img, ok := part.(genai.ImageData); ok { err := os.WriteFile(\"office.png\", img.Data, 0644) if err != nil { log.Fatal(err) } } } }` Java`import com.google.genai.Client; import com.google.genai.types.Content; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.ImageConfig; import com.google.genai.types.Part; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class GroupPhoto { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"TEXT\", \"IMAGE\") .imageConfig(ImageConfig.builder() .aspectRatio(\"5:4\") .imageSize(\"2K\") .build()) .build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.1-flash-image\", Content.fromParts( Part.fromText(\"An office group photo of these people, they are making funny faces.\"), Part.fromBytes(Files.readAllBytes(Path.of(\"person1.png\")), \"image/png\"), Part.fromBytes(Files.readAllBytes(Path.of(\"person2.png\")), \"image/png\"), Part.fromBytes(Files.readAllBytes(Path.of(\"person3.png\")), \"image/png\"), Part.fromBytes(Files.readAllBytes(Path.of(\"person4.png\")), \"image/png\"), Part.fromBytes(Files.readAllBytes(Path.of(\"person5.png\")), \"image/png\") ), config); for (Part part : response.parts()) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"office.png\"), blob.data().get()); } } } } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class GroupPhoto { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"An office group photo of these people, they are making funny faces.\" }, new Part { FileData = new FileData { FileUri = \"file:///person1.png\" } }, new Part { FileData = new FileData { FileUri = \"file:///person2.png\" } }, new Part { FileData = new FileData { FileUri = \"file:///person3.png\" } }, new Part { FileData = new FileData { FileUri = \"file:///person4.png\" } }, new Part { FileData = new FileData { FileUri = \"file:///person5.png\" } } }, config: new GenerateContentConfig { ResponseModalities = new List { \"TEXT\", \"IMAGE\" }, ImageConfig = new ImageConfig { AspectRatio = \"5:4\", ImageSize = \"2K\" } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"office.png\", imageBytes); Console.WriteLine(\"Image saved as office.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d \"{ \\\"contents\\\": [{ \\\"parts\\\":[ {\\\"text\\\": \\\"An office group photo of these people, they are making funny faces.\\\"}, {\\\"inline_data\\\": {\\\"mime_type\\\":\\\"image/png\\\", \\\"data\\\": \\\"\\\"}}, {\\\"inline_data\\\": {\\\"mime_type\\\":\\\"image/png\\\", \\\"data\\\": \\\"\\\"}}, {\\\"inline_data\\\": {\\\"mime_type\\\":\\\"image/png\\\", \\\"data\\\": \\\"\\\"}}, {\\\"inline_data\\\": {\\\"mime_type\\\":\\\"image/png\\\", \\\"data\\\": \\\"\\\"}}, {\\\"inline_data\\\": {\\\"mime_type\\\":\\\"image/png\\\", \\\"data\\\": \\\"\\\"}} ] }], \\\"generationConfig\\\": { \\\"responseModalities\\\": [\\\"TEXT\\\", \\\"IMAGE\\\"], \\\"responseFormat\\\": { \\\"image\\\": { \\\"aspectRatio\\\": \\\"5:4\\\", \\\"imageSize\\\": \\\"2K\\\" } } } }\"` AI-generated office group photo Grounding with Google Search Use the [Google Search tool](/gemini-api/docs/google-search) to generate images\nbased on real-time information, such as weather forecasts, stock charts, or\nrecent events. Note that when using Grounding with Google Search with image generation,\nimage-based search results are not passed to the generation model and are\nexcluded from the response (see Grounding with Google Search for images) Python`from google import genai prompt = \"Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day\" aspect_ratio = \"16:9\" # \"1:1\",\"1:4\",\"1:8\",\"2:3\",\"3:2\",\"3:4\",\"4:1\",\"4:3\",\"4:5\",\"5:4\",\"8:1\",\"9:16\",\"16:9\",\"21:9\" client = genai.Client() response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=prompt, config=types.GenerateContentConfig( response_modalities=['Text', 'Image'], response_format={\"image\": {aspect_ratio: aspect_ratio,}}, tools=[{\"google_search\": {}}] ) ) for part in response.parts: if part.text is not None: print(part.text) elif image:= part.as_image(): image.save(\"weather.png\")` Javascript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const prompt = 'Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day'; const aspectRatio = '16:9'; const resolution = '2K'; const response = await ai.models.generateContent({ model: 'gemini-3.1-flash-image', contents: prompt, config: { responseModalities: ['TEXT', 'IMAGE'], responseFormat: { image: { aspectRatio: aspectRatio, imageSize: resolution, } }, tools: [{ googleSearch: {} }] }, }); for (const part of response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, \"base64\"); fs.writeFileSync(\"image.png\", buffer); console.log(\"Image saved as image.png\"); } } } main();` Java`import com.google.genai.Client; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.GoogleSearch; import com.google.genai.types.ImageConfig; import com.google.genai.types.Part; import com.google.genai.types.Tool; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class SearchGrounding { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"TEXT\", \"IMAGE\") .imageConfig(ImageConfig.builder() .aspectRatio(\"16:9\") .build()) .tools(Tool.builder() .googleSearch(GoogleSearch.builder().build()) .build()) .build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.1-flash-image\", \"\"\" Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day \"\"\", config); for (Part part : response.parts()) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"weather.png\"), blob.data().get()); } } } } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class SearchGrounding { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day\" } }, config: new GenerateContentConfig { ResponseModalities = new List { \"TEXT\", \"IMAGE\" }, ImageConfig = new ImageConfig { AspectRatio = \"16:9\" }, Tools = new List { new Tool { GoogleSearch = new GoogleSearch() } } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"weather.png\", imageBytes); Console.WriteLine(\"Image saved as weather.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{\"parts\": [{\"text\": \"Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day\"}]}], \"tools\": [{\"google_search\": {}}], \"generationConfig\": { \"responseModalities\": [\"TEXT\", \"IMAGE\"], \"responseFormat\": { \"image\": {\"aspectRatio\": \"16:9\"} } } }'` AI-generated five day weather chart for San Francisco The response includes `groundingMetadata` which contains the following required\nfields: **`searchEntryPoint`**: Contains the HTML and CSS to render the required\nsearch suggestions. **`groundingChunks`**: Returns the top 3 web sources used to ground the\ngenerated image Grounding with Google Search for images (3.1 Flash) Grounding with Google Search for images allows models to use web images retrieved via\nGoogle Search as visual context for image generation. Image Search is a\nnew search type within the existing Grounding with Google Search tool,\nfunctioning alongside standard Web Search. To enable Image Search, configure the `googleSearch` tool in your API request\nand specify `imageSearch` within the `searchTypes` object. Image Search can be\nused independently or together with Web Search. Note that Grounding with Google Search for images can't be used to search for people. Python`from google import genai prompt = \"A detailed painting of a Timareta butterfly resting on a flower\" client = genai.Client() response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=prompt, config=types.GenerateContentConfig( response_modalities=[\"IMAGE\"], tools=[ types.Tool(google_search=types.GoogleSearch( search_types=types.SearchTypes( web_search=types.WebSearch(), image_search=types.ImageSearch() ) )) ] ) ) # Display grounding sources if available if response.candidates and response.candidates[0].grounding_metadata and response.candidates[0].grounding_metadata.search_entry_point: display(HTML(response.candidates[0].grounding_metadata.search_entry_point.rendered_content))` JavaScript`import { GoogleGenAI } from \"@google/genai\"; async function main() { const ai = new GoogleGenAI({}); const prompt = \"A detailed painting of a Timareta butterfly resting on a flower\"; const response = await ai.models.generateContent({ model: \"gemini-3.1-flash-image\", contents: prompt, config: { responseModalities: [\"IMAGE\"], tools: [ { googleSearch: { searchTypes: { webSearch: {}, imageSearch: {} } } } ] } }); // Display grounding sources if available if (response.candidates && response.candidates[0].groundingMetadata && response.candidates[0].groundingMetadata.searchEntryPoint) { console.log(response.candidates[0].groundingMetadata.searchEntryPoint.renderedContent); } } main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"google.golang.org/genai\" pb \"google.golang.org/genai/schema\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() model := client.GenerativeModel(\"gemini-3.1-flash-image\") model.Tools = []*pb.Tool{ { GoogleSearch: &pb.GoogleSearch{ SearchTypes: &pb.SearchTypes{ WebSearch: &pb.WebSearch{}, ImageSearch: &pb.ImageSearch{}, }, }, }, } model.GenerationConfig = &pb.GenerationConfig{ ResponseModalities: []pb.ResponseModality{genai.Image}, } prompt := \"A detailed painting of a Timareta butterfly resting on a flower\" resp, err := model.GenerateContent(ctx, genai.Text(prompt)) if err != nil { log.Fatal(err) } if resp.Candidates[0].GroundingMetadata != nil && resp.Candidates[0].GroundingMetadata.SearchEntryPoint != nil { fmt.Println(resp.Candidates[0].GroundingMetadata.SearchEntryPoint.RenderedContent) } }` Java`import com.google.genai.Client; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.GoogleSearch; import com.google.genai.types.ImageSearch; import com.google.genai.types.SearchTypes; import com.google.genai.types.Tool; import com.google.genai.types.WebSearch; import java.io.IOException; public class ImageSearchGrounding { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"IMAGE\") .tools(Tool.builder() .googleSearch(GoogleSearch.builder() .searchTypes(SearchTypes.builder() .webSearch(WebSearch.builder().build()) .imageSearch(ImageSearch.builder().build()) .build()) .build()) .build()) .build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.1-flash-image\", \"A detailed painting of a Timareta butterfly resting on a flower\", config); if (response.candidates().isPresent() && !response.candidates().get().isEmpty()) { var candidate = response.candidates().get().get(0); if (candidate.groundingMetadata().isPresent() && candidate.groundingMetadata().get().searchEntryPoint().isPresent()) { System.out.println(candidate.groundingMetadata().get().searchEntryPoint().get().renderedContent().orElse(\"\")); } } } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.Threading.Tasks; public class ImageSearchGrounding { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"A detailed painting of a Timareta butterfly resting on a flower\" } }, config: new GenerateContentConfig { ResponseModalities = new List { \"IMAGE\" }, Tools = new List { new Tool { GoogleSearch = new GoogleSearch { SearchTypes = new SearchTypes { WebSearch = new WebSearch(), ImageSearch = new ImageSearch() } } } } } ); foreach (var candidate in response.Candidates) { if (candidate.GroundingMetadata != null && candidate.GroundingMetadata.SearchEntryPoint != null) { Console.WriteLine(candidate.GroundingMetadata.SearchEntryPoint.RenderedContent); } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{\"parts\": [{\"text\": \"A detailed painting of a Timareta butterfly resting on a flower\"}]}], \"tools\": [{\"google_search\": {\"searchTypes\": {\"webSearch\": {}, \"imageSearch\": {}}}}], \"generationConfig\": { \"responseModalities\": [\"IMAGE\"] } }'` **Display requirements** When you use Image Search within Grounding with Google Search, you must comply\nwith the following conditions: **Source attribution**: You must provide a link to the webpage containing\nthe source image (the \"containing page,\" not the image file itself) in a\nmanner that the user will recognize as a link. **Direct navigation**: If you also choose to display the source images, you\nmust provide a direct, single-click path from the source images to its\ncontaining source webpage. Any other implementation that delays or abstracts\nthe end user's access to the source webpage, including but not limited to\nany multi-click path or the use of an intermediate image viewer, is not\npermitted. **Response** For grounded responses using image search, the API provides clear attribution\nand metadata to link its output to verified sources. Key fields in the\n`groundingMetadata` object include: **`imageSearchQueries`**: The specific queries used by the model for visual\ncontext (image search). **`groundingChunks`**: Contains source information for retrieved results.\nFor image sources, these will be returned as redirect URLs using a new image\nchunk type. This chunk includes: **`uri`**: The web page URL for attribution (the landing page). **`image_uri`**: The direct image URL. **`groundingSupports`**: Provides specific mappings that link the generated\ncontent to its relevant citation source in the chunks. **`searchEntryPoint`**: Includes the \"Google Search\" chip containing\ncompliant HTML and CSS to render Search Suggestions. Video-to-image generation (3.1 Flash and 3.1 Flash Lite) Video-to-image generation allows you to generate new images using a video's context\nas a multimodal reference. This is useful for creating high-quality video thumbnails, cinematic\nposters, summary infographics, or new artwork inspired by a video scene. During generation, the model analyzes the video frames in context (up to the model's input token\nlimit of 131,072 tokens) to extract visual themes and key events, then uses them alongside your text\nprompt to synthesize the output image. You can pass public [YouTube URLs](https://ai.google.dev/gemini-api/docs/video-understanding#youtube)\ndirectly in your API request or upload local video files using the\n[Files API](/gemini-api/docs/files). Python`from google import genai from google.genai import types client = genai.Client() # Pass a public YouTube video URL as part of the contents response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=[ types.Part( file_data=types.FileData(file_uri=\"https://www.youtube.com/watch?v=UTdfxFyOQTI\"), video_metadata=types.VideoMetadata(fps=0.5) ), \"Generate a poster image that captures the key themes of this video.\" ], config=types.GenerateContentConfig( response_modalities=[\"TEXT\", \"IMAGE\"] ) ) # Save the generated image part for part in response.parts: if part.inline_data is not None: image = part.as_image() image.save(\"video_poster.png\") print(\"Image saved as video_poster.png\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const response = await ai.models.generateContent({ model: \"gemini-3.1-flash-image\", contents: [ { fileData: { fileUri: \"https://www.youtube.com/watch?v=UTdfxFyOQTI\", }, videoMetadata: { fps: 0.5 } }, { text: \"Generate a poster image that captures the key themes of this video.\" } ], config: { responseModalities: [\"TEXT\", \"IMAGE\"] } }); 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(\"video_poster.png\", buffer); console.log(\"Image saved as video_poster.png\"); } } } main();` Go`package main import ( \"context\" \"log\" \"os\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } videoPart := genai.NewPartFromURI(\"https://www.youtube.com/watch?v=UTdfxFyOQTI\", \"video/mp4\") videoPart.VideoMetadata = &genai.VideoMetadata{FPS: genai.Ptr(0.5)} parts := []*genai.Part{ videoPart, genai.NewPartFromText(\"Generate a poster image that captures the key themes of this video.\"), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, err := client.Models.GenerateContent( ctx, \"gemini-3.1-flash-image\", contents, &genai.GenerateContentConfig{ ResponseModalities: []string{\"TEXT\", \"IMAGE\"}, }, ) if err != nil { log.Fatal(err) } for _, part := range result.Candidates[0].Content.Parts { if part.InlineData != nil { imageBytes := part.InlineData.Data _ = os.WriteFile(\"video_poster.png\", imageBytes, 0644) log.Println(\"Image saved as video_poster.png\") } } }` Java`import com.google.genai.Client; import com.google.genai.types.Content; import com.google.genai.types.FileData; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.Part; import com.google.genai.types.VideoMetadata; import com.google.common.collect.ImmutableList; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class VideoToImage { public static void main(String[] args) throws IOException { try (Client client = new Client()) { Part videoPart = Part.builder() .fileData(FileData.builder() .fileUri(\"https://www.youtube.com/watch?v=UTdfxFyOQTI\") .build()) .videoMetadata(VideoMetadata.builder() .fps(0.5) .build()) .build(); Part textPart = Part.builder() .text(\"Generate a poster image that captures the key themes of this video.\") .build(); GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"TEXT\", \"IMAGE\") .build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.1-flash-image\", Content.builder() .role(\"user\") .parts(ImmutableList.of(videoPart, textPart)) .build(), config); for (Part part : response.parts()) { if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"video_poster.png\"), blob.data().get()); System.out.println(\"Image saved as video_poster.png\"); } } } } } }` C#`using Google.GenAI; using Google.GenAI.Types; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class VideoToImage { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { FileData = new FileData { FileUri = \"https://www.youtube.com/watch?v=UTdfxFyOQTI\" }, VideoMetadata = new VideoMetadata { Fps = 0.5 } }, new Part { Text = \"Generate a poster image that captures the key themes of this video.\" } }, config: new GenerateContentConfig { ResponseModalities = new List { \"TEXT\", \"IMAGE\" } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"video_poster.png\", imageBytes); Console.WriteLine(\"Image saved as video_poster.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ { \"file_data\": { \"file_uri\": \"https://www.youtube.com/watch?v=UTdfxFyOQTI\" }, \"video_metadata\": { \"fps\": 0.5 } }, {\"text\": \"Generate a poster image that captures the key themes of this video.\"} ] }], \"generationConfig\": { \"responseModalities\": [\"TEXT\", \"IMAGE\"] } }'` AI-generated infographic from a youtube video Generate images up to 4K resolution Gemini 3 image models generate 1K images by default but can also output 2K,\n4K, and 512 (0.5K) (Gemini 3.1 Flash Image only) images. To generate higher\nresolution assets, specify the `image_size` in the `generation_config`. You must use an uppercase 'K' (e.g. 1K, 2K, 4K). The `512` value does not use a 'K' suffix. Lowercase\nparameters (e.g., 1k) will be rejected. Python`from google import genai from google.genai import types prompt = \"Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.\" aspect_ratio = \"1:1\" # \"1:1\",\"1:4\",\"1:8\",\"2:3\",\"3:2\",\"3:4\",\"4:1\",\"4:3\",\"4:5\",\"5:4\",\"8:1\",\"9:16\",\"16:9\",\"21:9\" resolution = \"1K\" # \"512\", \"1K\", \"2K\", \"4K\" client = genai.Client() response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=prompt, config=types.GenerateContentConfig( response_modalities=['TEXT', 'IMAGE'], response_format={\"image\": {aspect_ratio: aspect_ratio, image_size: resolution}}, ) ) for part in response.parts: if part.text is not None: print(part.text) elif image:= part.as_image(): image.save(\"butterfly.png\")` Javascript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const prompt = 'Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.'; const aspectRatio = '1:1'; const resolution = '1K'; const response = await ai.models.generateContent({ model: 'gemini-3.1-flash-image', contents: prompt, config: { responseModalities: ['TEXT', 'IMAGE'], responseFormat: { image: { aspectRatio: aspectRatio, imageSize: resolution, } }, }, }); for (const part of response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, \"base64\"); fs.writeFileSync(\"image.png\", buffer); console.log(\"Image saved as image.png\"); } } } main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"os\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() model := client.GenerativeModel(\"gemini-3.1-flash-image\") model.GenerationConfig = &pb.GenerationConfig{ ResponseModalities: []pb.ResponseModality{genai.Text, genai.Image}, ImageConfig: &pb.ImageConfig{ AspectRatio: \"1:1\", ImageSize: \"1K\", }, } prompt := \"Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.\" resp, err := model.GenerateContent(ctx, genai.Text(prompt)) if err != nil { log.Fatal(err) } for _, part := range resp.Candidates[0].Content.Parts { if txt, ok := part.(genai.Text); ok { fmt.Printf(\"%s\", string(txt)) } else if img, ok := part.(genai.ImageData); ok { err := os.WriteFile(\"butterfly.png\", img.Data, 0644) if err != nil { log.Fatal(err) } } } }` Java`import com.google.genai.Client; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.GoogleSearch; import com.google.genai.types.ImageConfig; import com.google.genai.types.Part; import com.google.genai.types.Tool; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class HiRes { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"TEXT\", \"IMAGE\") .imageConfig(ImageConfig.builder() .aspectRatio(\"16:9\") .imageSize(\"4K\") .build()) .build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.1-flash-image\", \"\"\" Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English. \"\"\", config); for (Part part : response.parts()) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"butterfly.png\"), blob.data().get()); } } } } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class HiRes { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.\" } }, config: new GenerateContentConfig { ResponseModalities = new List { \"TEXT\", \"IMAGE\" }, ImageConfig = new ImageConfig { AspectRatio = \"1:1\", ImageSize = \"1K\" } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"butterfly.png\", imageBytes); Console.WriteLine(\"Image saved as butterfly.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{\"parts\": [{\"text\": \"Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.\"}]}], \"tools\": [{\"google_search\": {}}], \"generationConfig\": { \"responseModalities\": [\"TEXT\", \"IMAGE\"], \"responseFormat\": { \"image\": {\"aspectRatio\": \"1:1\", \"imageSize\": \"1K\"} } } }'` The following is an example image generated from this prompt: AI-generated Da Vinci style anatomical sketch of a dissected Monarch butterfly. Thinking process Gemini 3 image models are thinking models that use a reasoning\nprocess (\"Thinking\") for complex prompts. This feature is enabled by default and\ncannot be disabled in the API. To learn more about the thinking process, see\nthe [Gemini Thinking](/gemini-api/docs/thinking) guide. The model generates up to two interim images to test composition and logic. The\nlast image within Thinking is also the final rendered image. You can check the thoughts that lead to the final image being produced. Python`for part in response.parts: if part.thought: if part.text: print(part.text) elif image:= part.as_image(): image.show()` Javascript`for (const part of response.candidates[0].content.parts) { if (part.thought) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, 'base64'); fs.writeFileSync('image.png', buffer); console.log('Image saved as image.png'); } } }` Java`for (Part part : response.parts()) { if (part.thought().orElse(false)) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"image.png\"), blob.data().get()); System.out.println(\"Image saved as image.png\"); } } } }` C#`foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Thought) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"image.png\", imageBytes); Console.WriteLine(\"Image saved as image.png\"); } } } }` Controlling thinking levels With Gemini 3.1 Flash Image and Gemini 3.1 Flash Lite Image, you can control the\namount of thinking the model\nuses to balance quality and latency. The default `thinkingLevel` is `minimal`,\nand the supported levels are `minimal` and `high`. Setting the\n`thinkingLevel` to `minimal` provides the lowest latency responses. Note that\nminimal thinking does not mean the model uses no thinking at all. You can add the `includeThoughts` boolean to determine whether the model's\ngenerated thoughts are returned in the response, or remain hidden. Python`from google import genai response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=\"A futuristic city built inside a giant glass bottle floating in space\", config=types.GenerateContentConfig( response_modalities=[\"IMAGE\"], thinking_config=types.ThinkingConfig( thinking_level=\"High\", include_thoughts=True ), ) ) for part in response.parts: if part.thought: # Skip outputting thoughts continue if part.text: display(Markdown(part.text)) elif image:= part.as_image(): image.show()` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; async function main() { const ai = new GoogleGenAI({}); const response = await ai.models.generateContent({ model: \"gemini-3.1-flash-image\", contents: \"A futuristic city built inside a giant glass bottle floating in space\", config: { responseModalities: [\"IMAGE\"], thinkingConfig: { thinkingLevel: \"High\", includeThoughts: true }, }, }); for (const part of response.candidates[0].content.parts) { if (part.thought) { // Skip outputting thoughts continue; } if (part.text) { console.log(part.text); } else if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, \"base64\"); fs.writeFileSync(\"image.png\", buffer); console.log(\"Image saved as image.png\"); } } } main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"os\" \"google.golang.org/genai\" pb \"google.golang.org/genai/schema\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() model := client.GenerativeModel(\"gemini-3.1-flash-image\") model.GenerationConfig = &pb.GenerationConfig{ ResponseModalities: []pb.ResponseModality{genai.Image}, ThinkingConfig: &pb.ThinkingConfig{ ThinkingLevel: \"High\", IncludeThoughts: true, }, } prompt := \"A futuristic city built inside a giant glass bottle floating in space\" resp, err := model.GenerateContent(ctx, genai.Text(prompt)) if err != nil { log.Fatal(err) } for _, part := range resp.Candidates[0].Content.Parts { if part.Thought { // Skip outputting thoughts continue } if txt, ok := part.(genai.Text); ok { fmt.Printf(\"%s\", string(txt)) } else if img, ok := part.(genai.ImageData); ok { err := os.WriteFile(\"image.png\", img.Data, 0644) if err != nil { log.Fatal(err) } } } }` Java`import com.google.genai.Client; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.Part; import com.google.genai.types.ThinkingConfig; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ThinkingLevels { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"IMAGE\") .thinkingConfig(ThinkingConfig.builder() .thinkingLevel(\"High\") .includeThoughts(true) .build()) .build(); GenerateContentResponse response = client.models.generateContent( \"gemini-3.1-flash-image\", \"A futuristic city built inside a giant glass bottle floating in space\", config); for (Part part : response.parts()) { if (part.thought().orElse(false)) { // Skip outputting thoughts continue; } if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"image.png\"), blob.data().get()); System.out.println(\"Image saved as image.png\"); } } } } } }` C#`using Google.GenAI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public class ThinkingLevels { public static async Task Main(string[] args) { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = \"A futuristic city built inside a giant glass bottle floating in space\" } }, config: new GenerateContentConfig { ResponseModalities = new List { \"IMAGE\" }, ThinkingConfig = new ThinkingConfig { ThinkingLevel = \"High\", IncludeThoughts = true } } ); foreach (var candidate in response.Candidates) { foreach (var part in candidate.Content.Parts) { if (part.Thought) { // Skip outputting thoughts continue; } if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { var imageBytes = Convert.FromBase64String(part.InlineData.Data); await File.WriteAllBytesAsync(\"image.png\", imageBytes); Console.WriteLine(\"Image saved as image.png\"); } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{\"parts\": [{\"text\": \"A futuristic city built inside a giant glass bottle floating in space\"}]}], \"generationConfig\": { \"responseModalities\": [\"IMAGE\"], \"thinkingConfig\": { \"thinkingLevel\": \"High\", \"includeThoughts\": true } } }'` Note that thinking tokens are billed regardless of whether `includeThoughts` is\nset to `true` or `false`, as the thinking process always\nhappens by default whether you view the process or not. Thought signatures Thought signatures are encrypted representations of the\nmodel's internal thought process and are used to preserve reasoning context\nacross multi-turn interactions. All responses include a `thought_signature`\nfield. As a general rule, if you receive a thought signature in a model\nresponse, you should pass it back exactly as received when sending the\nconversation history in the next turn. Failure to circulate thought signatures\nmay cause the response to fail. Check the [thought signature](/gemini-api/docs/thought-signatures)\ndocumentation for more explanations of signatures overall. Here is how thought signatures work: All `inline_data` parts with image `mimetype` which are part of the response\nshould have signature. If there are some text parts at the beginning (before any image) right after\nthe thoughts, the first text part should also have a signature. If `inline_data` parts with image `mimetype` are part of thoughts, they won't\nhave signatures. The following code shows an example of where thought signatures are included: `[ { \"inline_data\": { \"data\": \"\", \"mime_type\": \"image/png\" }, \"thought\": true // Thoughts don't have signatures }, { \"inline_data\": { \"data\": \"\", \"mime_type\": \"image/png\" }, \"thought\": true // Thoughts don't have signatures }, { \"inline_data\": { \"data\": \"\", \"mime_type\": \"image/png\" }, \"thought\": true // Thoughts don't have signatures }, { \"text\": \"Here is a step-by-step guide to baking macarons, presented in three separate images.\\n\\n### Step 1: Piping the Batter\\n\\nThe first step after making your macaron batter is to pipe it onto a baking sheet. This requires a steady hand to create uniform circles.\\n\\n\", \"thought_signature\": \"\" // The first non-thought part always has a signature }, { \"inline_data\": { \"data\": \"\", \"mime_type\": \"image/png\" }, \"thought_signature\": \"\" // All image parts have a signatures }, { \"text\": \"\\n\\n### Step 2: Baking and Developing Feet\\n\\nOnce piped, the macarons are baked in the oven. A key sign of a successful bake is the development of \\\"feet\\\"—the ruffled edge at the base of each macaron shell.\\n\\n\" // Follow-up text parts don't have signatures }, { \"inline_data\": { \"data\": \"\", \"mime_type\": \"image/png\" }, \"thought_signature\": \"\" // All image parts have a signatures }, { \"text\": \"\\n\\n### Step 3: Assembling the Macaron\\n\\nThe final step is to pair the cooled macaron shells by size and sandwich them together with your desired filling, creating the classic macaron dessert.\\n\\n\" }, { \"inline_data\": { \"data\": \"\", \"mime_type\": \"image/png\" }, \"thought_signature\": \"\" // All image parts have a signatures } ]` Other image generation modes Gemini supports other image interaction modes based on prompt structure and\ncontext, including: **Text to image(s) and text (interleaved):** Outputs images with related text.\n Example prompt: \"Generate an illustrated recipe for a paella.\" **Image(s) and text to image(s) and text (interleaved)**: Uses input images and text to create new related images and text.\n Example prompt: (With an image of a furnished room) \"What other color sofas would work in my space? can you update the image?\" Generate images in batch If you need to generate a lot of images, you can use the\n[Batch API](/gemini-api/docs/batch-api). You get higher\n[rate limits](/gemini-api/docs/rate-limits) in exchange for a turnaround of up\nto 24 hours. Check the [Batch API image generation documentation](/gemini-api/docs/batch-api#image-generation) and the [cookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb)\nfor Batch API image examples and code. Prompting guide and strategies Mastering image generation starts with one fundamental principle: **Describe the scene, don't just list keywords.**\nThe model's core strength is its deep language understanding. A narrative,\ndescriptive paragraph will almost always produce a better, more coherent image\nthan a list of disconnected words. Prompts for generating images The following strategies will help you create effective prompts to\ngenerate exactly the images you're looking for. Photography For realistic images, use photography terms. Mention camera angles, lens types,\nlighting, and fine details to guide the model toward a realistic result. **Prompt** **Generated output** A photo of a close-up portrait of an elderly Japanese ceramicist with deep, sun-etched wrinkles and a warm, knowing smile. He is carefully inspecting a freshly glazed tea bowl. The setting is his rustic, sun-drenched workshop. The scene is illuminated by soft, golden hour light streaming through a window, highlighting the fine texture of the clay. Captured with an 85mm portrait lens, resulting in a soft, blurred background (bokeh). The overall mood is serene and masterful. Vertical portrait orientation. Stylized illustrations and stickers To create stickers, icons, or assets, be explicit about the style and request a\nwhite background. **Prompt** **Generated output** A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white. Accurate text in images Gemini excels at rendering text. Be clear about the text, the font style\n(descriptively), and the overall design. Use Gemini 3 Pro Image for\nprofessional asset production. **Prompt** **Generated output** Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way. Product mockups and commercial photography Perfect for creating clean, professional product shots for ecommerce,\nadvertising, or branding. **Prompt** **Generated output** A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image. Minimalist and negative space design Excellent for creating backgrounds for websites, presentations, or marketing\nmaterials where text will be overlaid. **Prompt** **Generated output** A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image. Sequential art (comic panel / storyboard) Builds on character consistency and scene description to create panels for\nvisual storytelling. For accuracy with text and storytelling ability, these\nprompts work best with Gemini 3.1 Pro and Gemini 3.1 Flash Image. **Prompt** **Generated output** **Input image:** Input image **Prompt:** Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene. Grounding with Google Search Use Google Search to generate images based on recent or real-time information.\nThis is useful for news, weather, and other time-sensitive topics. **Prompt** **Generated output** Make a simple but stylish graphic of last night's Arsenal game in the Champion's League Prompts for editing images These examples show how to provide images alongside your text prompts for\nediting, composition, and style transfer. Adding and removing elements Provide an image and describe your change. The model will match the original\nimage's style, lighting, and perspective. **Prompt** **Generated output** **Input image:** Input image **Prompt:** Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and matches the soft lighting of the photo. Inpainting (semantic masking) Conversationally define a \"mask\" to edit a specific part of an image while\nleaving the rest untouched. **Prompt** **Generated output** **Input image:** Input image **Prompt:** Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged. Style transfer Provide an image and ask the model to recreate its content in a different\nartistic style. **Prompt** **Generated output** **Input image:** Input image **Prompt:** Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows. Advanced composition: combining multiple images Provide multiple images as context to create a new, composite scene. This is\nperfect for product mockups or creative collages. **Prompt** **Generated output** **Input images:** Input 1: Dress Input 2: Model **Prompt:** Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment. High-fidelity detail preservation To ensure critical details (like a face or logo) are preserved during an edit,\ndescribe them in great detail along with your edit request. **Prompt** **Generated output** **Input images:** Input 1: Woman Input 2: Logo **Prompt:** Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt. Bring something to life Upload a rough sketch or drawing and ask the model to refine it into a finished image. **Prompt** **Generated output** **Input image:** Rough sketch of a car **Prompt:** Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting. Character consistency: 360 view You can generate 360-degree views of a character by iteratively prompting for\ndifferent angles. For best results, include previously generated images in\nsubsequent prompts to maintain consistency. For complex poses, include a\nreference image of the desired pose. **Prompt** **Generated output** **Input image:** Original image **Prompt:** A studio portrait of this man against white, in profile looking right Man in white glasses looking right Man in white glasses looking forward Best practices To elevate your results from good to great, incorporate these professional\nstrategies into your workflow. **Be hyper-specific:** The more detail you provide, the more control you\nhave. Instead of \"fantasy armor,\" describe it: \"ornate elven plate armor, etched\nwith silver leaf patterns, with a high collar and pauldrons shaped like falcon\nwings.\" **Provide context and intent:** Explain the *purpose* of the image. The\nmodel's understanding of context will influence the final output. For example,\n\"Create a logo for a high-end, minimalist skincare brand\" will yield better\nresults than just \"Create a logo.\" **Iterate and refine:** Don't expect a perfect image on the first try. Use\nthe conversational nature of the model to make small changes. Follow up with\nprompts like, \"That's great, but can you make the lighting a bit warmer?\" or\n\"Keep everything the same, but change the character's expression to be more\nserious.\" **Use step-by-step instructions:** For complex scenes with many elements,\nbreak your prompt into steps. \"First, create a background of a serene, misty\nforest at dawn. Then, in the foreground, add a moss-covered ancient stone altar.\nFinally, place a single, glowing sword on top of the altar.\" **Use \"semantic negative prompts\":** Instead of saying \"no cars,\" describe\nthe desired scene positively: \"an empty, deserted street with no signs of\ntraffic.\" **Control the camera:** Use photographic and cinematic language to control\nthe composition. Terms like `wide-angle shot`, `macro shot`, `low-angle\nperspective`. Limitations For best performance, use the following languages: EN, ar-EG, de-DE, es-MX,\nfr-FR, hi-IN, id-ID, it-IT, ja-JP, ko-KR, pt-BR, ru-RU, ua-UA, vi-VN, zh-CN. Image generation does not support audio inputs. Video inputs are only supported for Gemini 3.1 Flash Image and Gemini 3.1 Flash Lite Image. The model won't always follow the exact number of image outputs that the\nuser explicitly asks for. `gemini-2.5-flash-image` works best with up to 3 images as input, while\n`gemini-3-pro-image` supports 5 images with high fidelity, and up to\n14 images in total. `gemini-3.1-flash-image` supports character\nresemblance of up to 4 characters and the fidelity of up to 10 objects in a\nsingle workflow. When generating text for an image, Gemini works best if you first generate\nthe text and then ask for an image with the text. `gemini-3.1-flash-image` Grounding with Google Search does not support using real-world images of people from web search at this time. All generated images include a [SynthID watermark](/responsible/docs/safeguards/synthid). Optional configurations You can optionally configure the response modalities and aspect ratio of the\nmodel's output in the `config` field of `generate_content` calls. Output types The model defaults to returning text and image responses\n(i.e. `response_modalities=['Text', 'Image']`).\nYou can configure the response to return only images without text using\n`response_modalities=['Image']`. Python`response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=[prompt], config=types.GenerateContentConfig( response_modalities=['Image'] ) )` JavaScript`const response = await ai.models.generateContent({ model: \"gemini-3.1-flash-image\", contents: prompt, config: { responseModalities: ['Image'] } });` Go`result, _ := client.Models.GenerateContent( ctx, \"gemini-3.1-flash-image\", genai.Text(\"Create a picture of a nano banana dish in a \" + \" fancy restaurant with a Gemini theme\"), &genai.GenerateContentConfig{ ResponseModalities: \"Image\", }, )` Java`response = client.models.generateContent( \"gemini-3.1-flash-image\", prompt, GenerateContentConfig.builder() .responseModalities(\"IMAGE\") .build());` C#`var response = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = prompt } }, config: new GenerateContentConfig { ResponseModalities = new List { \"IMAGE\" } } );` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme\"} ] }], \"generationConfig\": { \"responseModalities\": [\"Image\"] } }'` Aspect ratios and image size The model defaults to matching the output image size to that of your input\nimage, or otherwise generates 1:1 squares.\nYou can control the aspect ratio of the output image using the `aspect_ratio`\nfield under `response_format` in the response request, shown here: Python`# For gemini-2.5-flash-image response = client.models.generate_content( model=\"gemini-2.5-flash-image\", contents=[prompt], config=types.GenerateContentConfig( response_format={\"image\": {aspect_ratio: \"16:9\",}} ) ) # For gemini-3.1-flash-image and gemini-3-pro-image response = client.models.generate_content( model=\"gemini-3.1-flash-image\", contents=[prompt], config=types.GenerateContentConfig( response_format={\"image\": {aspect_ratio: \"16:9\", image_size: \"2K\",}} ) )` JavaScript`// For gemini-2.5-flash-image const response = await ai.models.generateContent({ model: \"gemini-2.5-flash-image\", contents: prompt, config: { responseFormat: { image: { aspectRatio: \"16:9\", } }, } }); // For gemini-3.1-flash-image and gemini-3-pro-image const response_gemini3 = await ai.models.generateContent({ model: \"gemini-3.1-flash-image\", contents: prompt, config: { responseFormat: { image: { aspectRatio: \"16:9\", imageSize: \"2K\", } }, } });` Go`// For gemini-2.5-flash-image result, _ := client.Models.GenerateContent( ctx, \"gemini-2.5-flash-image\", genai.Text(\"Create a picture of a nano banana dish in a \" + \" fancy restaurant with a Gemini theme\"), &genai.GenerateContentConfig{ ImageConfig: &genai.ImageConfig{ AspectRatio: \"16:9\", }, } ) // For gemini-3.1-flash-image and gemini-3-pro-image result_gemini3, _ := client.Models.GenerateContent( ctx, \"gemini-3.1-flash-image\", genai.Text(\"Create a picture of a nano banana dish in a \" + \" fancy restaurant with a Gemini theme\"), &genai.GenerateContentConfig{ ImageConfig: &genai.ImageConfig{ AspectRatio: \"16:9\", ImageSize: \"2K\", }, } )` Java`// For gemini-2.5-flash-image response = client.models.generateContent( \"gemini-2.5-flash-image\", prompt, GenerateContentConfig.builder() .imageConfig(ImageConfig.builder() .aspectRatio(\"16:9\") .build()) .build()); // For gemini-3.1-flash-image and gemini-3-pro-image response_gemini3 = client.models.generateContent( \"gemini-3.1-flash-image\", prompt, GenerateContentConfig.builder() .imageConfig(ImageConfig.builder() .aspectRatio(\"16:9\") .imageSize(\"2K\") .build()) .build());` C#`// For gemini-2.5-flash-image var response = await client.Models.GenerateContentAsync( model: \"gemini-2.5-flash-image\", contents: new List { new Part { Text = prompt } }, config: new GenerateContentConfig { ImageConfig = new ImageConfig { AspectRatio = \"16:9\" } } ); // For gemini-3.1-flash-image and gemini-3-pro-image var response_gemini3 = await client.Models.GenerateContentAsync( model: \"gemini-3.1-flash-image\", contents: new List { new Part { Text = prompt } }, config: new GenerateContentConfig { ImageConfig = new ImageConfig { AspectRatio = \"16:9\", ImageSize = \"2K\" } } );` REST`# For gemini-2.5-flash-image\ncurl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-2.5-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme\"} ] }], \"generationConfig\": { \"responseFormat\": { \"image\": { \"aspectRatio\": \"16:9\" } } } }' # For gemini-3-pro-image\ncurl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme\"} ] }], \"generationConfig\": { \"responseFormat\": { \"image\": { \"aspectRatio\": \"16:9\", \"imageSize\": \"2K\" } } } }'` The different ratios available and the size of the image generated are listed in\nthe following tables: 3.1 Flash Image Aspect ratio 512 resolution 0.5K tokens 1K resolution 1K tokens 2K resolution 2K tokens 4K resolution 4K tokens **1:1** 512x512 747 1024x1024 1120 2048x2048 1680 4096x4096 2520 **1:4** 256x1024 747 512x2048 1120 1024x4096 1680 2048x8192 2520 **1:8** 192x1536 747 384x3072 1120 768x6144 1680 1536x12288 2520 **2:3** 424x632 747 848x1264 1120 1696x2528 1680 3392x5056 2520 **3:2** 632x424 747 1264x848 1120 2528x1696 1680 5056x3392 2520 **3:4** 448x600 747 896x1200 1120 1792x2400 1680 3584x4800 2520 **4:1** 1024x256 747 2048x512 1120 4096x1024 1680 8192x2048 2520 **4:3** 600x448 747 1200x896 1120 2400x1792 1680 4800x3584 2520 **4:5** 464x576 747 928x1152 1120 1856x2304 1680 3712x4608 2520 **5:4** 576x464 747 1152x928 1120 2304x1856 1680 4608x3712 2520 **8:1** 1536x192 747 3072x384 1120 6144x768 1680 12288x1536 2520 **9:16** 384x688 747 768x1376 1120 1536x2752 1680 3072x5504 2520 **16:9** 688x384 747 1376x768 1120 2752x1536 1680 5504x3072 2520 **21:9** 792x168 747 1584x672 1120 3168x1344 1680 6336x2688 2520 3.1 Flash Lite Image Aspect ratio 512 resolution 0.5K tokens 1K resolution 1K tokens **1:1** 512x512 747 1024x1024 1120 **1:4** 256x1024 747 512x2048 1120 **1:8** 192x1536 747 384x3072 1120 **2:3** 424x632 747 848x1264 1120 **3:2** 632x424 747 1264x848 1120 **3:4** 448x600 747 896x1200 1120 **4:1** 1024x256 747 2048x512 1120 **4:3** 600x448 747 1200x896 1120 **4:5** 464x576 747 928x1152 1120 **5:4** 576x464 747 1152x928 1120 **8:1** 1536x192 747 3072x384 1120 **9:16** 384x688 747 768x1376 1120 **16:9** 688x384 747 1376x768 1120 **21:9** 792x168 747 1584x672 1120 3.1 Pro Image Aspect ratio 1K resolution 1K tokens 2K resolution 2K tokens 4K resolution 4K tokens **1:1** 1024x1024 1120 2048x2048 1120 4096x4096 2000 **2:3** 848x1264 1120 1696x2528 1120 3392x5056 2000 **3:2** 1264x848 1120 2528x1696 1120 5056x3392 2000 **3:4** 896x1200 1120 1792x2400 1120 3584x4800 2000 **4:3** 1200x896 1120 2400x1792 1120 4800x3584 2000 **4:5** 928x1152 1120 1856x2304 1120 3712x4608 2000 **5:4** 1152x928 1120 2304x1856 1120 4608x3712 2000 **9:16** 768x1376 1120 1536x2752 1120 3072x5504 2000 **16:9** 1376x768 1120 2752x1536 1120 5504x3072 2000 **21:9** 1584x672 1120 3168x1344 1120 6336x2688 2000 Gemini 2.5 Flash Image Aspect ratio Resolution Tokens 1:1 1024x1024 1290 2:3 832x1248 1290 3:2 1248x832 1290 3:4 864x1184 1290 4:3 1184x864 1290 4:5 896x1152 1290 5:4 1152x896 1290 9:16 768x1344 1290 16:9 1344x768 1290 21:9 1536x672 1290 Model selection Choose the model best suited for your specific use case. **Gemini 3.1 Flash Image (Nano Banana 2)** should be your\ngo-to image generation model, as the best all around performance and\nintelligence to cost and latency balance. Check the model [pricing](/gemini-api/docs/pricing#gemini-3.1-flash-image) and [capabilities](/gemini-api/docs/models/gemini-3.1-flash-image) page for more\ndetails. **Gemini 3.1 Flash Lite Image (Nano Banana 2 Lite)** is designed as\nthe efficiency specialist of the image generation family, offering\nultra-low latency and cost-effective image generation and editing.\nCheck the model [pricing](/gemini-api/docs/pricing#gemini-3.1-flash-lite-image)\nand [capabilities](/gemini-api/docs/models/gemini-3.1-flash-lite-image) page\nfor more details. **Gemini 3 Pro Image (Nano Banana Pro)** is designed for\nprofessional asset production and complex instructions. This model features\nreal-world grounding using Google Search, a default \"Thinking\" process that\nrefines composition prior to generation, and can generate images of up to 4K\nresolutions. Check the model [pricing](/gemini-api/docs/pricing#gemini-3-pro-image) and [capabilities](/gemini-api/docs/models/gemini-3-pro-image) page for more\ndetails. **Gemini 2.5 Flash Image (Nano Banana)** is designed for speed and\nefficiency. This model is optimized for high-volume, low-latency tasks and\ngenerates images at 1024px resolution. Check the model [pricing](/gemini-api/docs/pricing#gemini-2.5-flash-image) and\n[capabilities](/gemini-api/docs/models/gemini-2.5-flash-image) page for more\ndetails. When to use Imagen In addition to using Gemini's built-in image generation capabilities, you can\nalso access [Imagen](/gemini-api/docs/imagen), our specialized image generation\nmodel, through the Gemini API. Plan to migrate before the shutdown date. What's next Find more examples and code samples in the [cookbook guide](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_Started_Nano_Banana.ipynb). Check out the [Veo guide](/gemini-api/docs/video) to learn how to generate\nvideos with the Gemini API. To learn more about Gemini models, see [Gemini models](/gemini-api/docs/models/gemini). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-03 UTC.", "znaku_textu": 92831, "slov": 12063, "odkazu": 155, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:19", "sha256": "53522455ef989d30d2295b99e9cd1c75061a7948902536a78f13ec3ad19d37d3", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/apps/bundled/pet_passport", "https://aistudio.google.com/apps?features=nano_banana_2", "https://aistudio.google.com/apps?features=nano_banana_2%2Csearch_grounding", "https://policies.google.com/terms/generative-ai/use-policy", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_Started_Nano_Banana.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/image-understanding", "titulek": "Image understanding | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Image understanding", "popis": "Get started building with Gemini's multimodal capabilities in the Gemini API", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/image-understanding", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Image understanding  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Get started building with Gemini's multimodal capabilities in the Gemini API", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/image-understanding", "og:image": "https://ai.google.dev/static/site-assets/images/vision.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Image understanding"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Image understanding", "item": "https://ai.google.dev/gemini-api/docs/generate-content/image-understanding"}]}], "drobecky": ["Generate Content API", "Image understanding"], "osnova": [{"uroven": 1, "text": "Image understanding"}, {"uroven": 2, "text": "Passing images to Gemini"}, {"uroven": 3, "text": "Passing inline image data"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Uploading images using the File API"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Prompting with multiple images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Object detection"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Supported image formats"}, {"uroven": 2, "text": "Capabilities"}, {"uroven": 2, "text": "Limitations and key technical information"}, {"uroven": 3, "text": "File limit"}, {"uroven": 3, "text": "Token calculation"}, {"uroven": 3, "text": "Media resolution"}, {"uroven": 2, "text": "Tips and best practices"}, {"uroven": 2, "text": "What's next"}], "markdown": "Image understanding Gemini models are built to be multimodal from the ground up, unlocking a wide\nrange of image processing and computer vision tasks including but not limited to\nimage captioning, classification, and visual question answering without having\nto train specialized ML models. In addition to their general multimodal capabilities, Gemini models offer\n**enhanced accuracy** for specific use cases like object detection, through additional\ntraining. Passing images to Gemini You can provide images as input to Gemini using two methods: Passing inline image data: Ideal for smaller files (total request\nsize less than 20MB, including prompts). Uploading images using the File API: Recommended for larger files or for\nreusing images across multiple requests. Passing inline image data You can pass inline image data in the\nrequest to `generateContent`. You can provide image data as Base64 encoded\nstrings or by reading local files directly (depending on the language). The following example shows how to read an image from a local file and pass\nit to `generateContent` API for processing. Python`from google import genai from google.genai import types with open('path/to/small-sample.jpg', 'rb') as f: image_bytes = f.read() client = genai.Client() response = client.models.generate_content( model='gemini-3.8-flash', contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/jpeg', ), 'Caption this image.' ] ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const ai = new GoogleGenAI({}); const base64ImageFile = fs.readFileSync(\"path/to/small-sample.jpg\", { encoding: \"base64\", }); const contents = [ { inlineData: { mimeType: \"image/jpeg\", data: base64ImageFile, }, }, { text: \"Caption this image.\" }, ]; const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: contents, }); console.log(response.text);` Go`bytes, _ := os.ReadFile(\"path/to/small-sample.jpg\") parts := []*genai.Part{ genai.NewPartFromBytes(bytes, \"image/jpeg\"), genai.NewPartFromText(\"Caption this image.\"), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text())` REST`IMG_PATH=\"/path/to/your/image1.jpg\" if [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then B64FLAGS=\"--input\" else B64FLAGS=\"-w0\" fi\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-H 'Content-Type: application/json' \\\n-X POST \\\n-d '{ \"contents\": [{ \"parts\":[ { \"inline_data\": { \"mime_type\":\"image/jpeg\", \"data\": \"'\"$(base64 $B64FLAGS $IMG_PATH)\"'\" } }, {\"text\": \"Caption this image.\"}, ] }] }' 2> /dev/null` You can also fetch an image from a URL, convert it to bytes, and pass it to\n`generateContent` as shown in the following examples. Python`from google import genai from google.genai import types import requests image_path = \"https://goo.gle/instrument-img\" image_bytes = requests.get(image_path).content image = types.Part.from_bytes( data=image_bytes, mime_type=\"image/jpeg\" ) client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[\"What is this image?\", image], ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; async function main() { const ai = new GoogleGenAI({}); 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.8-flash\", contents: [ { inlineData: { mimeType: 'image/jpeg', data: base64ImageData, }, }, { text: \"Caption this image.\" } ], }); console.log(result.text); } main();` Go`package main import ( \"context\" \"fmt\" \"os\" \"io\" \"net/http\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } // Download the image. imageResp, _ := http.Get(\"https://goo.gle/instrument-img\") imageBytes, _ := io.ReadAll(imageResp.Body) parts := []*genai.Part{ genai.NewPartFromBytes(imageBytes, \"image/jpeg\"), genai.NewPartFromText(\"Caption this image.\"), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` REST`IMG_URL=\"https://goo.gle/instrument-img\" MIME_TYPE=$(curl -sIL \"$IMG_URL\" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\\r$//' | head -n 1) if [[ -z \"$MIME_TYPE\" || ! \"$MIME_TYPE\" == image/* ]]; then MIME_TYPE=\"image/jpeg\" fi # Check for macOS if [[ \"$(uname)\" == \"Darwin\" ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -b 0) elif [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64) else IMAGE_B64=$(curl -sL \"$IMG_URL\" | base64 -w0) fi\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ { \"inline_data\": { \"mime_type\":\"'\"$MIME_TYPE\"'\", \"data\": \"'\"$IMAGE_B64\"'\" } }, {\"text\": \"Caption this image.\"} ] }] }' 2> /dev/null` Uploading images using the File API For large files or to be able to use the same image file repeatedly, use the\nFiles API. The following code uploads an image file and then uses the file in a\ncall to `generateContent`. See the [Files API guide](/gemini-api/docs/files) for\nmore information and examples. Python`from google import genai client = genai.Client() my_file = client.files.upload(file=\"path/to/sample.jpg\") response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[my_file, \"Caption this image.\"], ) print(response.text)` JavaScript`import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function main() { const myfile = await ai.files.upload({ file: \"path/to/sample.jpg\", config: { mimeType: \"image/jpeg\" }, }); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: createUserContent([ createPartFromUri(myfile.uri, myfile.mimeType), \"Caption this image.\", ]), }); console.log(response.text); } await main();` 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) } uploadedFile, _ := client.Files.UploadFromPath(ctx, \"path/to/sample.jpg\", nil) parts := []*genai.Part{ genai.NewPartFromText(\"Caption this image.\"), genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text()) }` REST`IMAGE_PATH=\"path/to/sample.jpg\" MIME_TYPE=$(file -b --mime-type \"${IMAGE_PATH}\") NUM_BYTES=$(wc -c < \"${IMAGE_PATH}\") DISPLAY_NAME=IMAGE\n\ntmp_header_file=upload-header.tmp\n\n# Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file.\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -D upload-header.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME}'}}\" 2> /dev/null\n\nupload_url=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file}\" # Upload the actual bytes.\ncurl \"${upload_url}\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Length: ${NUM_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${IMAGE_PATH}\" 2> /dev/null > file_info.json\n\nfile_uri=$(jq -r \".file.uri\" file_info.json) echo file_uri=$file_uri # Now generate content using that file\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"file_data\":{\"mime_type\": \"'\"${MIME_TYPE}\"'\", \"file_uri\": \"'\"${file_uri}\"'\"}}, {\"text\": \"Caption this image.\"}] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` Prompting with multiple images You can provide multiple images in a single prompt by including multiple image\n`Part` objects in the `contents` array. These can be a mix of inline data\n(local files or URLs) and File API references. Python`from google import genai from google.genai import types client = genai.Client() # Upload the first image image1_path = \"path/to/image1.jpg\" uploaded_file = client.files.upload(file=image1_path) # Prepare the second image as inline data image2_path = \"path/to/image2.png\" with open(image2_path, 'rb') as f: img2_bytes = f.read() # Create the prompt with text and multiple images response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=[ \"What is different between these two images?\", uploaded_file, # Use the uploaded file reference types.Part.from_bytes( data=img2_bytes, mime_type='image/png' ) ] ) print(response.text)` JavaScript`import { GoogleGenAI, createUserContent, createPartFromUri, } from \"@google/genai\"; import * as fs from \"node:fs\"; const ai = new GoogleGenAI({}); async function main() { // Upload the first image const image1_path = \"path/to/image1.jpg\"; const uploadedFile = await ai.files.upload({ file: image1_path, config: { mimeType: \"image/jpeg\" }, }); // Prepare the second image as inline data const image2_path = \"path/to/image2.png\"; const base64Image2File = fs.readFileSync(image2_path, { encoding: \"base64\", }); // Create the prompt with text and multiple images const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: createUserContent([ \"What is different between these two images?\", createPartFromUri(uploadedFile.uri, uploadedFile.mimeType), { inlineData: { mimeType: \"image/png\", data: base64Image2File, }, }, ]), }); console.log(response.text); } await main();` Go`// Upload the first image image1Path := \"path/to/image1.jpg\" uploadedFile, _ := client.Files.UploadFromPath(ctx, image1Path, nil) // Prepare the second image as inline data image2Path := \"path/to/image2.jpeg\" imgBytes, _ := os.ReadFile(image2Path) parts := []*genai.Part{ genai.NewPartFromText(\"What is different between these two images?\"), genai.NewPartFromBytes(imgBytes, \"image/jpeg\"), genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, _ := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, nil, ) fmt.Println(result.Text())` REST`# Upload the first image IMAGE1_PATH=\"path/to/image1.jpg\" MIME1_TYPE=$(file -b --mime-type \"${IMAGE1_PATH}\") NUM1_BYTES=$(wc -c < \"${IMAGE1_PATH}\") DISPLAY_NAME1=IMAGE1\n\ntmp_header_file1=upload-header1.tmp\n\ncurl \"https://generativelanguage.googleapis.com/upload/v1beta/files\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -D upload-header1.tmp \\ -H \"X-Goog-Upload-Protocol: resumable\" \\ -H \"X-Goog-Upload-Command: start\" \\ -H \"X-Goog-Upload-Header-Content-Length: ${NUM1_BYTES}\" \\ -H \"X-Goog-Upload-Header-Content-Type: ${MIME1_TYPE}\" \\ -H \"Content-Type: application/json\" \\ -d \"{'file': {'display_name': '${DISPLAY_NAME1}'}}\" 2> /dev/null\n\nupload_url1=$(grep -i \"x-goog-upload-url: \" \"${tmp_header_file1}\" | cut -d\" \" -f2 | tr -d \"\\r\")\nrm \"${tmp_header_file1}\"\n\ncurl \"${upload_url1}\" \\ -H \"Content-Length: ${NUM1_BYTES}\" \\ -H \"X-Goog-Upload-Offset: 0\" \\ -H \"X-Goog-Upload-Command: upload, finalize\" \\ --data-binary \"@${IMAGE1_PATH}\" 2> /dev/null > file_info1.json\n\nfile1_uri=$(jq \".file.uri\" file_info1.json) echo file1_uri=$file1_uri # Prepare the second image (inline) IMAGE2_PATH=\"path/to/image2.png\" MIME2_TYPE=$(file -b --mime-type \"${IMAGE2_PATH}\") if [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then B64FLAGS=\"--input\" else B64FLAGS=\"-w0\" fi IMAGE2_BASE64=$(base64 $B64FLAGS $IMAGE2_PATH) # Now generate content using both images\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ {\"text\": \"What is different between these two images?\"}, {\"file_data\":{\"mime_type\": \"'\"${MIME1_TYPE}\"'\", \"file_uri\": '$file1_uri'}}, { \"inline_data\": { \"mime_type\":\"'\"${MIME2_TYPE}\"'\", \"data\": \"'\"$IMAGE2_BASE64\"'\" } } ] }] }' 2> /dev/null > response.json\n\ncat response.json\necho\n\njq \".candidates[].content.parts[].text\" response.json` Object detection Models are trained to detect objects in an\nimage and get their bounding box coordinates. The coordinates, relative to image\ndimensions, scale to [0, 1000]. You need to descale these coordinates based on\nyour original image size. Python`from google import genai from google.genai import types from PIL import Image import json client = genai.Client() prompt = \"Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000.\" image = Image.open(\"/path/to/image.png\") config = types.GenerateContentConfig( response_mime_type=\"application/json\" ) response = client.models.generate_content(model=\"gemini-3.8-flash\", contents=[image, prompt], config=config ) width, height = image.size bounding_boxes = json.loads(response.text) converted_bounding_boxes = [] for bounding_box in bounding_boxes: abs_y1 = int(bounding_box[\"box_2d\"][0]/1000 * height) abs_x1 = int(bounding_box[\"box_2d\"][1]/1000 * width) abs_y2 = int(bounding_box[\"box_2d\"][2]/1000 * height) abs_x2 = int(bounding_box[\"box_2d\"][3]/1000 * width) converted_bounding_boxes.append([abs_x1, abs_y1, abs_x2, abs_y2]) print(\"Image size: \", width, height) print(\"Bounding boxes:\", converted_bounding_boxes)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const ai = new GoogleGenAI({}); const base64ImageFile = fs.readFileSync(\"/path/to/image.png\", { encoding: \"base64\", }); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: [ { inlineData: { mimeType: \"image/png\", data: base64ImageFile, }, }, \"Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000.\" ], config: { responseMimeType: \"application/json\", }, }); const boundingBoxes = JSON.parse(response.text); console.log(boundingBoxes); // To convert normalized coordinates to absolute pixels: // const absY1 = (boundingBoxes[0].box_2d[0] / 1000) * imageHeight; // const absX1 = (boundingBoxes[0].box_2d[1] / 1000) * imageWidth;` Go`package main import ( \"context\" \"encoding/json\" \"fmt\" \"image\" _ \"image/png\" // Register PNG decoder \"log\" \"os\" \"google.golang.org/genai\" ) type BoundingBox struct { Box2D []int `json:\"box_2d\"` Label string `json:\"label\"` } func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } imagePath := \"/path/to/image.png\" // Open the image to get dimensions file, err := os.Open(imagePath) if err != nil { log.Fatal(err) } defer file.Close() imgConfig, _, err := image.DecodeConfig(file) if err != nil { log.Fatal(err) } width := imgConfig.Width height := imgConfig.Height // Read image bytes imageBytes, err := os.ReadFile(imagePath) if err != nil { log.Fatal(err) } prompt := \"Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000.\" parts := []*genai.Part{ genai.NewPartFromBytes(imageBytes, \"image/png\"), genai.NewPartFromText(prompt), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } config := &genai.GenerateContentConfig{ ResponseMIMEType: \"application/json\", } result, err := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", contents, config, ) if err != nil { log.Fatal(err) } var boundingBoxes []BoundingBox err = json.Unmarshal([]byte(result.Text()), &boundingBoxes) if err != nil { log.Fatal(err) } fmt.Printf(\"Image size: %d %d\\n\", width, height) fmt.Println(\"Bounding boxes:\") for _, box := range boundingBoxes { if len(box.Box2D) == 4 { absY1 := int(float64(box.Box2D[0]) / 1000.0 * float64(height)) absX1 := int(float64(box.Box2D[1]) / 1000.0 * float64(width)) absY2 := int(float64(box.Box2D[2]) / 1000.0 * float64(height)) absX2 := int(float64(box.Box2D[3]) / 1000.0 * float64(width)) fmt.Printf(\"- %s: [%d, %d, %d, %d]\\n\", box.Label, absX1, absY1, absX2, absY2) } } }` REST`IMG_PATH=\"/path/to/image.png\" if [[ \"$(base64 --version 2>&1)\" = *\"FreeBSD\"* ]]; then B64FLAGS=\"--input\" else B64FLAGS=\"-w0\" fi\n\ncurl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\":[ { \"inline_data\": { \"mime_type\":\"image/png\", \"data\": \"'\"$(base64 $B64FLAGS $IMG_PATH)\"'\" } }, {\"text\": \"Detect the all of the prominent items in the image. The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000.\"} ] }], \"generationConfig\": { \"responseMimeType\": \"application/json\" } }' 2> /dev/null` For more examples, check following notebooks in the [Gemini Cookbook](https://github.com/google-gemini/cookbook): [2D spatial understanding notebook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Spatial_understanding.ipynb) [Experimental 3D pointing notebook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/Spatial_understanding_3d.ipynb) Supported image formats Gemini supports the following image format MIME types: PNG - `image/png` JPEG - `image/jpeg` WEBP - `image/webp` HEIC - `image/heic` HEIF - `image/heif` To learn about other file input methods, see the\n[File input methods](/gemini-api/docs/file-input-methods) guide. Capabilities All Gemini model versions are multimodal and can be utilized in a wide range of\nimage processing and computer vision tasks including but not limited to image captioning,\nvisual question and answering, image classification, and object detection. Gemini can reduce the need to use specialized ML models depending on your quality and performance requirements. The latest model versions are specifically trained improve accuracy of\nspecialized tasks in addition to generic capabilities, like enhanced \nobject detection. Limitations and key technical information File limit Gemini models support a maximum of 3,600 image files per request. Token calculation 258 tokens if both dimensions <= 384 pixels.\nLarger images are tiled into 768x768 pixel tiles, each costing 258 tokens. A rough formula for calculating the number of tiles is as follows: Calculate the crop unit size which is roughly: floor(min(width, height) / 1.5). Divide each dimension by the crop unit size and multiply together to get the\nnumber of tiles. For example, for an image of dimensions 960x540 would have a crop unit size\nof 360. Divide each dimension by 360 and the number of tile is 3 * 2 = 6. Media resolution Gemini 3 introduces granular control over multimodal vision processing with the\n`media_resolution` parameter. The `media_resolution` parameter determines the\n**maximum number of tokens allocated per input image or video frame.**\nHigher resolutions improve the model's ability to\nread fine text or identify small details, but increase token usage and latency. For more details about the parameter and how it can impact token calculations,\nsee the [media resolution](/gemini-api/docs/generate-content/media-resolution) guide. Tips and best practices Verify that images are correctly rotated. Use clear, non-blurry images. When using a single image with text, place the text prompt *after* the image part in the `contents` array. What's next This guide shows you how to upload image files and generate text outputs from image\ninputs. To learn more, see the following resources: [Files API](/gemini-api/docs/files): Learn more about uploading and managing files for use with Gemini. [System instructions](/gemini-api/docs/text-generation#system-instructions):\nSystem instructions let you steer the behavior of the model based on your\nspecific needs and use cases. [File prompting strategies](/gemini-api/docs/files#prompt-guide): The\nGemini API supports prompting with text, image, audio, and video data, also\nknown as multimodal prompting. [Safety guidance](/gemini-api/docs/safety-guidance): Sometimes generative\nAI models produce unexpected outputs, such as outputs that are inaccurate,\nbiased, or offensive. Post-processing and human evaluation are essential to\nlimit the risk of harm from such outputs. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 21291, "slov": 2676, "odkazu": 131, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:24", "sha256": "0817f5f789140c45ecb6a56ab1707e372776ac315834c9217a92a5e3d27bd980", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Spatial_understanding.ipynb", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/Spatial_understanding_3d.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/latest-model", "titulek": "What's new in Gemini 3.8 Flash | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "What's new in Gemini 3.8 Flash", "popis": "Learn about what's new in the latest Gemini models, including model capabilities, API changes, and migration guidance.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/latest-model", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "What's new in Gemini 3.8 Flash  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Learn about what's new in the latest Gemini models, including model capabilities, API changes, and migration guidance.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/latest-model", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "What's new in Gemini 3.8 Flash"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "What&#39;s new in Gemini 3.8 Flash", "item": "https://ai.google.dev/gemini-api/docs/generate-content/latest-model"}]}], "drobecky": ["Generate Content API", "What&#39;s new in Gemini 3.8 Flash"], "osnova": [{"uroven": 1, "text": "What's new in Gemini 3.8 Flash"}, {"uroven": 2, "text": "New model"}, {"uroven": 2, "text": "Quickstart"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "What's new in Gemini 3.8 Flash"}, {"uroven": 2, "text": "Understanding reasoning levels"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Updated Antigravity agent"}, {"uroven": 2, "text": "Migration checklist"}, {"uroven": 3, "text": "Migrate to gemini-3.8-flash"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "Next steps"}], "markdown": "What's new in Gemini 3.8 Flash [See all models](/gemini-api/docs/models) Gemini 3.8 Flash (`gemini-3.8-flash`) is generally available (GA) and ready for production use. It is our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows. This guide explains what's new in Gemini 3.8 Flash, API changes, code examples, and migration guidance. New model Model Model ID Default thinking level Pricing Description Gemini 3.8 Flash `gemini-3.8-flash` `medium` 3.8 Flash is available through the end of year at an introductory price of $0.75/1M input tokens and $3.75/1M output tokens; see [pricing](/gemini-api/docs/pricing) for more details. Our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows. Gemini 3.8 Flash supports a 1M token context window, 64k max output tokens, tunable thinking levels (`low`, `medium`, `high`), and the same suite of built-in tools. For complete specs, see the [Gemini 3.8 Flash model page](/gemini-api/docs/models/gemini-3.8-flash). For introductory pricing details, see the pricing section below or the [pricing page](/gemini-api/docs/pricing#gemini-3.8-flash). Quickstart Python`from google import genai client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Write a three.js script that renders a realistic 3D black hole.\" ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Write a three.js script that renders a realistic 3D black hole.\", }); console.log(response.text);` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\": [{\"text\": \"Write a three.js script that renders a realistic 3D black hole.\"}] }] }'` What's new in Gemini 3.8 Flash **Long-horizon software engineering:** Delivers strong results on real-world coding benchmarks, complex multi-file refactoring, and deterministic tool execution. See the [evaluation methodology](https://deepmind.google/models/evals-methodology/gemini-3-8-flash/) for details. **Autonomous agents:** Lets you build resilient multi-step planning and tool orchestration workflows, substantially reducing failed loops and errors. **Complex enterprise workflows:** Delivers superior accuracy, deep reasoning, and high factual rigor across demanding domain tasks and large-scale data pipelines. **Default model for Managed Agents:** The default agent for managed agents: the [Antigravity agent](/gemini-api/docs/antigravity-agent), now uses Gemini 3.8 Flash. The [Antigravity SDK](https://antigravity.google/docs/sdk/overview/) also uses Gemini 3.8 Flash by default. **Introductory pricing:** Gemini 3.8 Flash is available at an introductory rate of $0.75/1M input tokens and $3.75/1M output tokens through December 31, 2026. Standard pricing of $1.50/1M input tokens and $7.50/1M output tokens takes effect January 1, 2027. Gemini 3.8 Flash can use more tokens on longer running and complex tasks, by design. To deliver higher-quality results on difficult, multi-step goals, the model takes smaller reasoning steps, calls tools iteratively, and verifies its work along the way. Not every workflow needs this level of verification. For everyday tasks, you can lower the reasoning effort to reduce token consumption. Alternatively, Gemini 3.7 Flash remains fully supported. Understanding reasoning levels Gemini 3.8 Flash gives you flexible control over latency and intelligence by adjusting the model's thinking level: **Low thinking effort**: Reduces time-to-answer for latency-critical tasks like incident response pipelines, real-time chat, writing drafts, and fast data analysis. **Medium (default):** Best quality for most tasks. Recommended for complex code and agentic use cases, providing higher first-pass accuracy. **High thinking effort**: Maximizes the model's reasoning and tool orchestration capabilities. Best for deep reasoning, mathematics, and difficult multi-step tasks. The following example sets `thinking_level` to `medium` for a complex code analysis request: Python`from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Analyze this payment processing pipeline for race conditions during retry attempts and rewrite the transaction locks safely.\", config=types.GenerateContentConfig( thinking_config=types.ThinkingConfig( thinking_level=\"medium\" # Balanced reasoning effort for complex tasks ), ), ) print(response.text)` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Analyze this payment processing pipeline for race conditions during retry attempts and rewrite the transaction locks safely.\", config: { thinkingConfig: { thinkingLevel: \"medium\", // Balanced reasoning effort for complex tasks }, }, }); console.log(response.text);` REST`curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -X POST \\ -d '{ \"contents\": [{ \"parts\": [{\"text\": \"Analyze this payment processing pipeline for race conditions during retry attempts and rewrite the transaction locks safely.\"}] }], \"generationConfig\": { \"thinkingConfig\": { \"thinkingLevel\": \"medium\" } } }'` Updated Antigravity agent Migration checklist ``/gemini-api-dev migrate my app to Gemini 3.8 Flash`` Migrate to gemini-3.8-flash **Update Model ID:** Change your target model string to `gemini-3.8-flash`. **Remove deprecated sampling parameters:** Strip `temperature`, `top_p`, and `top_k` from generation configs. Replace `thinking_budget` with the string enum `thinking_level`. Note that `minimal` is not supported on 3.8 Flash. Remove `candidate_count` (unsupported in Gemini 3 and later). **Enforce turn validation rules:** Remove prefilled model turns. Ensure the final user turn contains non-empty text. **Audit function calling:** Place multimodal assets inside the response payload. Format inline instructions using `\\n\\n`. If you see `Malformed_Function_Call` errors tied to pre-tool text, see [Workarounds for pre-tool text requirements](/gemini-api/docs/generate-content/function-calling#workarounds-for-pre-tool-text-requirements). Only if using generateContent API: Ensure all `FunctionResponse` objects include `call_id` and `name`. **Baseline Gemini 3 requirements:** For SDK updates and thought signature preservation, see the [Gemini 3.5 Migration Checklist](/gemini-api/docs/generate-content/whats-new-gemini-3.5#migration). Pricing Take advantage of introductory pricing across Google AI Studio and Gemini Enterprise Agent Platform through December 31, 2026 for Gemini 3.8 Flash, Gemini 3.7 Flash, and Gemini 3.6 Flash. Standard pricing takes effect January 1, 2027. For complete pricing tiers, see the [pricing page](/gemini-api/docs/pricing#gemini-3.8-flash). Next steps Review API specs on the [Models Overview](/gemini-api/docs/models). Explore multi-agent orchestration in the [Interactions API Overview](/gemini-api/docs/interactions-overview). Test and refine prompts in [Google AI Studio](https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-03 UTC.", "znaku_textu": 7968, "slov": 1061, "odkazu": 131, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:34", "sha256": "b8481effa0dd66e376a3dcd2b34f9f1fa98e5bb889a74f37cf0353120f28b330", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://deepmind.google/models/evals-methodology/gemini-3-8-flash/", "https://antigravity.google/docs/sdk/overview/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/maps-grounding", "titulek": "Grounding with Google Maps | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Grounding with Google Maps", "popis": "Ground your model's responses in rich, real-world data from Google Maps to provide factually accurate, location-aware answers", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/maps-grounding", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Grounding with Google Maps  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Ground your model's responses in rich, real-world data from Google Maps to provide factually accurate, location-aware answers", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/maps-grounding", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Grounding with Google Maps"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Grounding with Google Maps", "item": "https://ai.google.dev/gemini-api/docs/generate-content/maps-grounding"}]}], "drobecky": ["Generate Content API", "Grounding with Google Maps"], "osnova": [{"uroven": 1, "text": "Grounding with Google Maps"}, {"uroven": 2, "text": "Get started"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How Grounding with Google Maps works"}, {"uroven": 2, "text": "Why and when to use Grounding with Google Maps"}, {"uroven": 2, "text": "API methods and parameters"}, {"uroven": 3, "text": "JSON"}, {"uroven": 3, "text": "JSON"}, {"uroven": 3, "text": "Understanding the grounding response"}, {"uroven": 3, "text": "JSON"}, {"uroven": 2, "text": "Use cases"}, {"uroven": 3, "text": "Handling place-specific questions"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Providing location-based personalization"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "Assisting with itinerary planning"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Service usage requirements"}, {"uroven": 3, "text": "Inform the user about the use of Google Maps sources"}, {"uroven": 3, "text": "Display Google Maps sources with Google Maps links"}, {"uroven": 3, "text": "Google Maps text attribution guidelines"}, {"uroven": 4, "text": "Example CSS"}, {"uroven": 3, "text": "CSS"}, {"uroven": 3, "text": "Place ID and review ID"}, {"uroven": 3, "text": "Prohibited activity and territory"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "Pricing and rate limits"}, {"uroven": 2, "text": "Supported models"}, {"uroven": 2, "text": "Supported tool combinations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Grounding with Google Maps Grounding with Google Maps connects the generative capabilities of Gemini with\nthe rich, factual, and up-to-date data of Google Maps. This feature enables\ndevelopers to easily incorporate location-aware functionality into their\napplications. When a user query has a context related to Maps data, the Gemini\nmodel leverages Google Maps to provide factually accurate and fresh answers that\nare relevant to the user's specified location or general area. **Accurate, location-aware responses:** Leverage Google Maps' extensive and\ncurrent data for geographically specific queries. **Enhanced personalization:** Tailor recommendations and information based\non user-provided locations. Get started This example demonstrates how to integrate Grounding with Google Maps into your\napplication to provide accurate, location-aware responses to user queries. The\nprompt asks for local recommendations with an optional user location, enabling\nthe Gemini model to use Google Maps data. Python`from google import genai from google.genai import types client = genai.Client() prompt = \"What are the best Italian restaurants within a 15-minute walk from here?\" response = client.models.generate_content( model='gemini-3.8-flash', contents=prompt, config=types.GenerateContentConfig( # Turn on grounding with Google Maps tools=[types.Tool(google_maps=types.GoogleMaps())], # Optionally provide the relevant location context (this is in Los Angeles) tool_config=types.ToolConfig(retrieval_config=types.RetrievalConfig( lat_lng=types.LatLng( latitude=34.050481, longitude=-118.248526))), ), ) print(\"Generated Response:\") print(response.text) if grounding := response.candidates[0].grounding_metadata: if grounding.grounding_chunks: print('-' * 40) print(\"Sources:\") for chunk in grounding.grounding_chunks: print(f'- [{chunk.maps.title}]({chunk.maps.uri})')` JavaScript`import { GoogleGenAI } from \"@google/genai\"; const ai = new GoogleGenAI({}); async function generateContentWithMapsGrounding() { const response = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"What are the best Italian restaurants within a 15-minute walk from here?\", config: { // Turn on grounding with Google Maps tools: [{ googleMaps: {} }], toolConfig: { retrievalConfig: { // Optionally provide the relevant location context (this is in Los Angeles) latLng: { latitude: 34.050481, longitude: -118.248526, }, }, }, }, }); console.log(\"Generated Response:\"); console.log(response.text); const grounding = response.candidates[0]?.groundingMetadata; if (grounding?.groundingChunks) { console.log(\"-\".repeat(40)); console.log(\"Sources:\"); for (const chunk of grounding.groundingChunks) { if (chunk.maps) { console.log(`- [${chunk.maps.title}](${chunk.maps.uri})`); } } } } generateContentWithMapsGrounding();` REST`curl -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent' \\ -H 'Content-Type: application/json' \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"contents\": [{ \"role\": \"user\", \"parts\": [{ \"text\": \"What are the best Italian restaurants within a 15-minute walk from here?\" }] }], \"tools\": [{\"googleMaps\": {}}], \"toolConfig\": { \"retrievalConfig\": { \"latLng\": {\"latitude\": 34.050481, \"longitude\": -118.248526} } } }'` How Grounding with Google Maps works Grounding with Google Maps integrates the Gemini API with the Google Geo\necosystem by using the Maps API as a grounding source. When a user's query\ncontains geographical context, the Gemini model can invoke the Grounding with\nGoogle Maps tool. The model can then generate responses grounded in Google Maps\ndata relevant to the provided location. The process typically involves: **User query:** A user submits a query to your application, potentially\nincluding geographical context (e.g., \"coffee shops near me,\" \"museums in\nSan Francisco\"). **Tool invocation:** The Gemini model, recognizing the geographical intent,\ninvokes the Grounding with Google Maps tool. This tool can optionally be\nprovided with the user's `latitude` and `longitude`. The tool is a textual\nsearch tool and behaves similarly to searching on Maps, in that local\nqueries (\"near me\") will use the coordinates, while specific or non-local\nqueries are unlikely to be influenced by the explicit location. **Data retrieval:** The Grounding with Google Maps service queries Google\nMaps for relevant information (e.g., places, reviews, photos, addresses,\nopening hours). **Grounded generation:** The retrieved Maps data is used to inform the\nGemini model's response, ensuring factual accuracy and relevance. **Response:** The model returns a text response, which\nincludes citations to Google Maps sources. Why and when to use Grounding with Google Maps Grounding with Google Maps is ideal for applications that require accurate,\nup-to-date, and location-specific information. It enhances the user experience\nby providing relevant and personalized content backed by Google Maps' extensive\ndatabase of over 250 million places worldwide. You should use Grounding with Google Maps when your application needs to: Provide complete and accurate responses to geo-specific questions. Build conversational trip planners and local guides. Recommend points of interest based on\nlocation and user preferences like restaurants or shops. Create location-aware experiences for social, retail, or food delivery\nservices. Grounding with Google Maps excels in use cases where proximity and current\nfactual data are critical, such as finding the \"best coffee shop near me\" or\ngetting directions. API methods and parameters Grounding with Google Maps is exposed through the Gemini API as a tool within\nthe [`generateContent`](/api/generate-content) method. You enable and configure\nGrounding with Google Maps by including a\n[`googleMaps`](/api/caching#GoogleMaps) object in the `tools` parameter of your\nrequest. JSON`{ \"contents\": [{ \"parts\": [ {\"text\": \"Restaurants near Times Square.\"} ] }], \"tools\": { \"googleMaps\": {} } }` Additionally, the tool supports passing the contextual location as `toolConfig`. JSON`{ \"contents\": [{ \"parts\": [ {\"text\": \"Restaurants near here.\"} ] }], \"tools\": { \"googleMaps\": {} }, \"toolConfig\": { \"retrievalConfig\": { \"latLng\": { \"latitude\": 40.758896, \"longitude\": -73.985130 } } } }` Understanding the grounding response When a response is successfully grounded with Google Maps data, the response\nincludes a [`groundingMetadata`](/api/generate-content#GroundingMetadata) field.\nThis structured data is essential for verifying claims and building a rich\ncitation experience in your application, as well as meeting the service usage\nrequirements. JSON`{ \"candidates\": [ { \"content\": { \"parts\": [ { \"text\": \"CanteenM is an American restaurant with...\" } ], \"role\": \"model\" }, \"groundingMetadata\": { \"groundingChunks\": [ { \"maps\": { \"uri\": \"https://maps.google.com/?cid=13100894621228039586\", \"title\": \"Heaven on 7th Marketplace\", \"placeId\": \"places/ChIJ0-zA1vBZwokRon0fGj-6z7U\" }, // repeated ... } ], \"groundingSupports\": [ { \"segment\": { \"startIndex\": 0, \"endIndex\": 79, \"text\": \"CanteenM is an American restaurant with a 4.6-star rating and is open 24 hours.\" }, \"groundingChunkIndices\": [0] }, // repeated ... ], \"webSearchQueries\": [ \"restaurants near me\" ] } } ] }` The Gemini API returns the following information with the\n[`groundingMetadata`](/api/generate-content#GroundingMetadata): `groundingChunks`: Array of objects containing the `maps` sources (`uri`,\n`placeId` and `title`). `groundingSupports`: Array of chunks to connect model response text to the\nsources in `groundingChunks`. Each chunk links a text span (defined by\n`startIndex` and `endIndex`) to one or more `groundingChunkIndices`. This is\nthe key to building inline citations. For a code snippet showing how to render inline citations in text, see [the\nexample](https://ai.google.dev/gemini-api/docs/google-search#attributing_sources_with_inline_citations)\nin the Grounding with Google Search docs. Use cases Grounding with Google Maps supports a variety of location-aware use cases. The\nfollowing examples demonstrate how different prompts and parameters can leverage\nGrounding with Google Maps. Information in the Google Maps Grounded Results may\ndiffer from actual conditions. Handling place-specific questions Ask detailed questions about a specific place to get answers based on Google\nuser reviews and other Maps data. Python`from google import genai from google.genai import types client = genai.Client() prompt = \"Is there a cafe near the corner of 1st and Main that has outdoor seating?\" response = client.models.generate_content( model='gemini-3.8-flash', contents=prompt, config=types.GenerateContentConfig( # Turn on the Maps tool tools=[types.Tool(google_maps=types.GoogleMaps())], # Provide the relevant location context (this is in Los Angeles) tool_config=types.ToolConfig(retrieval_config=types.RetrievalConfig( lat_lng=types.LatLng( latitude=34.050481, longitude=-118.248526))), ), ) print(\"Generated Response:\") print(response.text) if grounding := response.candidates[0].grounding_metadata: if chunks := grounding.grounding_chunks: print('-' * 40) print(\"Sources:\") for chunk in chunks: print(f'- [{chunk.maps.title}]({chunk.maps.uri})') ```` Javascript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); async function run() { const prompt = \"Is there a cafe near the corner of 1st and Main that has outdoor seating?\"; const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: prompt, config: { // Turn on the Maps tool tools: [{googleMaps: {}}], // Provide the relevant location context (this is in Los Angeles) toolConfig: { retrievalConfig: { latLng: { latitude: 34.050481, longitude: -118.248526 } } } }, }); console.log(\"Generated Response:\"); console.log(response.text); const chunks = response.candidates[0].groundingMetadata?.groundingChunks; if (chunks) { console.log('-'.repeat(40)); console.log(\"Sources:\"); for (const chunk of chunks) { if (chunk.maps) { console.log(`- [${chunk.maps.title}](${chunk.maps.uri})`); } } } } run();` REST`curl -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent' \\ -H 'Content-Type: application/json' \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"contents\": [{ \"role\": \"user\", \"parts\": [{ \"text\": \"Is there a cafe near the corner of 1st and Main that has outdoor seating?\" }] }], \"tools\": [{\"googleMaps\": {}}], \"toolConfig\": { \"retrievalConfig\": { \"latLng\": {\"latitude\": 34.050481, \"longitude\": -118.248526} } } }'` Providing location-based personalization Get recommendations tailored to a user's preferences and a specific geographical\narea. Python`from google import genai from google.genai import types client = genai.Client() prompt = \"Which family-friendly restaurants near here have the best playground reviews?\" response = client.models.generate_content( model='gemini-3.8-flash', contents=prompt, config=types.GenerateContentConfig( tools=[types.Tool(google_maps=types.GoogleMaps())], tool_config=types.ToolConfig(retrieval_config=types.RetrievalConfig( # Provide the location as context; this is Austin, TX. lat_lng=types.LatLng( latitude=30.2672, longitude=-97.7431))), ), ) print(\"Generated Response:\") print(response.text) if grounding := response.candidates[0].grounding_metadata: if chunks := grounding.grounding_chunks: print('-' * 40) print(\"Sources:\") for chunk in chunks: print(f'- [{chunk.maps.title}]({chunk.maps.uri})')` Javascript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); async function run() { const prompt = \"Which family-friendly restaurants near here have the best playground reviews?\"; const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: prompt, config: { tools: [{googleMaps: {}}], toolConfig: { retrievalConfig: { // Provide the location as context; this is Austin, TX. latLng: { latitude: 30.2672, longitude: -97.7431 } } } }, }); console.log(\"Generated Response:\"); console.log(response.text); const chunks = response.candidates[0].groundingMetadata?.groundingChunks; if (chunks) { console.log('-'.repeat(40)); console.log(\"Sources:\"); for (const chunk of chunks) { if (chunk.maps) { console.log(`- [${chunk.maps.title}](${chunk.maps.uri})`); } } } } run();` REST`curl -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent' \\ -H 'Content-Type: application/json' \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"contents\": [{ \"role\": \"user\", \"parts\": [{ \"text\": \"Which family-friendly restaurants near here have the best playground reviews?\" }], }], \"tools\": [{\"googleMaps\": {}}], \"toolConfig\": { \"retrievalConfig\": { \"latLng\": {\"latitude\": 30.2672, \"longitude\": -97.7431} } } }'` Assisting with itinerary planning Generate multi-day plans with directions and information about various\nlocations, perfect for travel applications. Python`from google import genai from google.genai import types client = genai.Client() prompt = \"Plan a day in San Francisco for me. I want to see the Golden Gate Bridge, visit a museum, and have a nice dinner.\" response = client.models.generate_content( model='gemini-3.8-flash', contents=prompt, config=types.GenerateContentConfig( tools=[types.Tool(google_maps=types.GoogleMaps())], tool_config=types.ToolConfig(retrieval_config=types.RetrievalConfig( # Provide the location as context, this is in San Francisco. lat_lng=types.LatLng( latitude=37.78193, longitude=-122.40476))), ), ) print(\"Generated Response:\") print(response.text) if grounding := response.candidates[0].grounding_metadata: if grounding.grounding_chunks: print('-' * 40) print(\"Sources:\") for chunk in grounding.grounding_chunks: print(f'- [{chunk.maps.title}]({chunk.maps.uri})')` Javascript`import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({}); async function run() { const prompt = \"Plan a day in San Francisco for me. I want to see the Golden Gate Bridge, visit a museum, and have a nice dinner.\"; const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: prompt, config: { tools: [{googleMaps: {}}], toolConfig: { retrievalConfig: { // Provide the location as context, this is in San Francisco. latLng: { latitude: 37.78193, longitude: -122.40476 } } } }, }); console.log(\"Generated Response:\"); console.log(response.text); const groundingMetadata = response.candidates[0]?.groundingMetadata; if (groundingMetadata) { if (groundingMetadata.groundingChunks) { console.log('-'.repeat(40)); console.log(\"Sources:\"); for (const chunk of groundingMetadata.groundingChunks) { if (chunk.maps) { console.log(`- [${chunk.maps.title}](${chunk.maps.uri})`); } } } } } run();` REST`curl -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent' \\ -H 'Content-Type: application/json' \\ -H \"x-goog-api-key: ${GEMINI_API_KEY}\" \\ -d '{ \"contents\": [{ \"role\": \"user\", \"parts\": [{ \"text\": \"Plan a day in San Francisco for me. I want to see the Golden Gate Bridge, visit a museum, and have a nice dinner.\" }] }], \"tools\": [{\"googleMaps\": {}}], \"toolConfig\": { \"retrievalConfig\": { \"latLng\": {\"latitude\": 37.78193, \"longitude\": -122.40476} } } }'` Service usage requirements This section describes the service usage requirements for Grounding with Google\nMaps. Inform the user about the use of Google Maps sources With each Google Maps Grounded result, you'll receive sources in\n`groundingChunks` that support each response. The following metadata is also\nreturned: source uri title ID When presenting results from Grounding with Google Maps, you must specify the\nassociated Google Maps sources, and inform your users of the following: The Google Maps sources must immediately follow the generated content that\nthe sources support. This generated content is also referred to as Google\nMaps Grounded Result. The Google Maps sources must be viewable within one user interaction. Display Google Maps sources with Google Maps links For each source in `groundingChunks` and in\n`grounding_chunks.maps.placeAnswerSources.reviewSnippets`, a link preview must\nbe generated following these requirements: Attribute each source to Google Maps following the Google Maps text\nattribution guidelines. Display the source title provided in the response. Link to the source using the `uri` or `googleMapsUri` from the response. These images show the minimum requirements for displaying the sources and Google\nMaps links. You can collapse the view of the sources. Optional: Enhance the link preview with additional content, such as: A [Google Maps favicon](https://www.google.com/images/branding/product/ico/web_maps_icon_32dp.ico)\nis inserted before the Google Maps text attribution. A photo from the source URL (`og:image`). For more information about some of our Google Maps data providers and their\nlicense terms, see the [Google Maps and Google Earth legal notices](https://www.google.com/help/legalnotices_maps/). Google Maps text attribution guidelines When you attribute sources to Google Maps in text, follow these guidelines: Don't modify the text Google Maps in any way:\n Don't change the capitalization of Google Maps. Don't wrap Google Maps onto multiple lines. Don't localize Google Maps into another language. Prevent browsers from translating Google Maps by using the HTML\nattribute translate=\"no\". Style Google Maps text as described in the following table: Property Style `Font family` Roboto. Loading the font is optional. `Fallback font family` Any sans serif body font already used in your product or \"Sans-Serif\" to invoke the default system font `Font style` Normal `Font weight` 400 `Font color` White, black (#1F1F1F), or gray (#5E5E5E). Maintain accessible (4.5:1) contrast against the background. `Font size` Minimum font size: 12sp Maximum font size: 16sp To learn about sp, see Font size units on the [Material Design website](https://m3.material.io/styles/typography/type-scale-tokens#3f4488e7-3b74-45b0-a143-9d6afa4d62dc). `Spacing` Normal Example CSS The following CSS renders Google Maps with the appropriate typographic style and\ncolor on a white or light background. CSS`@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');\n\n.GMP-attribution {\n\nfont-family: Roboto, Sans-Serif;\nfont-style: normal;\nfont-weight: 400;\nfont-size: 1rem;\nletter-spacing: normal;\nwhite-space: nowrap;\ncolor: #5e5e5e; }` Place ID and review ID The Google Maps data includes place ID and review ID. You might\ncache, store, and export the following response data: `placeId` `reviewId` The restrictions against caching in the Grounding with Google Maps Terms don't\napply. Prohibited activity and territory Grounding with Google Maps has additional restrictions for certain content and\nactivities to maintain a safe and reliable platform. In addition to the usage\nrestrictions in the [Terms](/gemini-api/terms#grounding-with-google-maps): You won't use Grounding with Google Maps for high risk activities including\nemergency response services. You won't distribute or market your application that offers Grounding with\nGoogle Maps in a Prohibited Territory. For more information, see\n[Google Maps Platform Prohibited Territories](https://cloud.google.com/maps-platform/terms/maps-prohibited-territories).\nThe list of Prohibited Territories may be updated from time to time. Best practices **Provide user location:** For the most relevant and personalized responses,\nalways include the `user_location` (latitude and longitude) in your\n`googleMapsGrounding` configuration when the user's location is known. **Inform End-Users:** Clearly inform your end-users that Google Maps\ndata is being used to answer their queries, especially when the tool is\nenabled. **Monitor Latency:** For conversational applications, ensure that the P95\nlatency for grounded responses remains within acceptable thresholds to\nmaintain a smooth user experience. **Toggle Off When Not Needed:** Grounding with Google Maps is off by\ndefault. Only enable it (`\"tools\": [{\"googleMaps\": {}}]`) when a query has a\nclear geographical context, to optimize performance and cost. Limitations **Geographical Scope:** Grounding with Google Maps is globally available **Model Support:** See the Supported models section. **Multimodal Inputs/Outputs:** Grounding with Google Maps does not currently\nsupport multimodal inputs or outputs beyond text. **Default State:** The Grounding with Google Maps tool is off by default.\nYou must explicitly enable it in your API requests. Pricing and rate limits Grounding with Google Maps pricing is based on queries. The current rate is\n**$25 / 1K grounded prompts**. The free tier also has up to 500 requests per day\navailable. A request is only counted towards the quota when\na prompt successfully returns at least one Google Maps grounded result (i.e.,\nresults containing at least one Google Maps source). If multiple queries are\nsent to Google Maps from a single request, it counts as one request towards the\nrate limit. For detailed pricing information, see the [Gemini API pricing page](/gemini-api/docs/pricing). Supported models The following models support Grounding with Google Maps: Model Grounding with Google Maps [Gemini 3.8 Flash](/gemini-api/docs/models/gemini-3.8-flash) ✔️ [Gemini 3.7 Flash](/gemini-api/docs/models/gemini-3.7-flash) ✔️ [Gemini 3.6 Flash](/gemini-api/docs/models/gemini-3.6-flash) ✔️ [Gemini 3.5 Flash-Lite](/gemini-api/docs/models/gemini-3.5-flash-lite) ✔️ [Gemini 3.5 Flash](/gemini-api/docs/models/gemini-3.5-flash) ✔️ [Gemini 3.1 Pro Preview](/gemini-api/docs/models/gemini-3.1-pro-preview) ✔️ [Gemini 3.1 Flash-Lite](/gemini-api/docs/models/gemini-3.1-flash-lite) ✔️ [Gemini 3 Flash Preview](/gemini-api/docs/models/gemini-3-flash-preview) ✔️ [Gemini 2.5 Pro](/gemini-api/docs/models/gemini-2.5-pro) ✔️ [Gemini 2.5 Flash](/gemini-api/docs/models/gemini-2.5-flash) ✔️ [Gemini 2.5 Flash-Lite](/gemini-api/docs/models/gemini-2.5-flash-lite) ✔️ Supported tool combinations You can use Grounding with Google Maps with other built-in tools like\n[Grounding with Google Search](/gemini-api/docs/google-search) (supported on\nGemini 3.5 Flash and later models) to power more complex use cases. Gemini 3\nmodels also support combining these built-in tools with custom tools (function\ncalling). Learn more on the\n[tool combinations](/gemini-api/docs/tool-combination) page. What's next Try the [Grounding with Google Search in the Gemini API\nCookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Search_Grounding.ipynb). Learn about other [available tools](/gemini-api/docs/tools). To learn more about responsible AI best practices and Gemini API's safety\nfilters, see [the Safety settings guide](/gemini-api/docs/safety-settings). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 23098, "slov": 3033, "odkazu": 147, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:04", "sha256": "8286514d101df91e55b03eac36dd61a30e44d34dfec1d0f6f28db21904cdfae5", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://www.google.com/images/branding/product/ico/web_maps_icon_32dp.ico", "https://www.google.com/help/legalnotices_maps/", "https://m3.material.io/styles/typography/type-scale-tokens", "https://cloud.google.com/maps-platform/terms/maps-prohibited-territories", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Search_Grounding.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/media-resolution", "titulek": "Media resolution | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Media resolution", "popis": "Learn about how to use media resolutions with multimodal inputs.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/media-resolution", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Media resolution  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Learn about how to use media resolutions with multimodal inputs.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/media-resolution", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Media resolution"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Media resolution", "item": "https://ai.google.dev/gemini-api/docs/generate-content/media-resolution"}]}], "drobecky": ["Generate Content API", "Media resolution"], "osnova": [{"uroven": 1, "text": "Media resolution"}, {"uroven": 2, "text": "Per-part media resolution (Gemini 3 only)"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Global media resolution"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Javascript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Available resolution values"}, {"uroven": 2, "text": "Token counts"}, {"uroven": 2, "text": "Choosing the right resolution"}, {"uroven": 2, "text": "Relationship with video processing modes"}, {"uroven": 2, "text": "Version compatibility summary"}, {"uroven": 2, "text": "Next steps"}], "markdown": "Media resolution The `media_resolution` parameter controls how the Gemini API processes media inputs like images, videos, and PDF documents by determining the **maximum number of tokens** allocated for media inputs, allowing you to balance response quality against latency and cost. For different settings, default values and how they correspond to tokens, see the Token counts section. You can configure media resolution in two ways: [Per part](/gemini-api/docs/media-resolution#per-part-media-resolution) (Gemini 3 only) [Globally](/gemini-api/docs/media-resolution#global-media-resolution) for an entire `generateContent` request (all multimodal models) Per-part media resolution (Gemini 3 only) Gemini 3 allows you to set media resolution for individual media objects within your request, offering fine-grained optimisation of token usage. You can mix resolution levels in a single request. For example, using high resolution for a complex diagram and low resolution for a simple contextual image. This setting overrides any global configuration for a specific part. For default settings, see [Token counts](/gemini-api/docs/media-resolution#token-counts) section. Python`from google import genai from google.genai import types # The media_resolution parameter for parts is available in the v1beta API version. client = genai.Client( http_options={ 'api_version': 'v1beta', } ) # Replace with your image data with open('path/to/image1.jpg', 'rb') as f: image_bytes_1 = f.read() # Create parts with different resolutions image_part_high = types.Part.from_bytes( data=image_bytes_1, mime_type='image/jpeg', media_resolution=types.MediaResolution.MEDIA_RESOLUTION_HIGH ) model_name = 'gemini-3.1-pro-preview' response = client.models.generate_content( model=model_name, contents=[\"Describe these images:\", image_part_high] ) print(response.text)` Javascript`// Example: Setting per-part media resolution in JavaScript import { GoogleGenAI, MediaResolution, Part } from '@google/genai'; import * as fs from 'fs'; import { Buffer } from 'buffer'; // Node.js const ai = new GoogleGenAI({ httpOptions: { apiVersion: 'v1beta' } }); // Helper function to convert local file to a Part object function fileToGenerativePart(path, mimeType, mediaResolution) { return { inlineData: { data: Buffer.from(fs.readFileSync(path)).toString('base64'), mimeType }, mediaResolution: { 'level': mediaResolution } }; } async function run() { // Create parts with different resolutions const imagePartHigh = fileToGenerativePart('img.png', 'image/png', Part.MediaResolutionLevel.MEDIA_RESOLUTION_HIGH); const model_name = 'gemini-3.1-pro-preview'; const response = await ai.models.generateContent({ model: model_name, contents: ['Describe these images:', imagePartHigh] // Global config can still be set, but per-part settings will override // config: { // mediaResolution: MediaResolution.MEDIA_RESOLUTION_MEDIUM // } }); console.log(response.text); } run();` REST`# Replace with paths to your images IMAGE_PATH=\"path/to/image.jpg\" # Base64 encode the images BASE64_IMAGE1=$(base64 -w 0 \"$IMAGE_PATH\") MODEL_ID=\"gemini-3.1-pro-preview\" echo '{ \"contents\": [{ \"parts\": [ {\"text\": \"Describe these images:\"}, { \"inline_data\": { \"mime_type\": \"image/jpeg\", \"data\": \"'\"$BASE64_IMAGE1\"'\", }, \"media_resolution\": {\"level\": \"MEDIA_RESOLUTION_HIGH\"} } ] }] }' > request.json\n\ncurl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/${MODEL_ID}:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d @request.json` Global media resolution You can set a default resolution for all media parts in a request using the\n`GenerationConfig`. This is supported by all multimodal models. If a request\nincludes both global and [per-part settings](/gemini-api/docs/media-resolution#per-part-media-resolution), the per-part setting takes precedence for that specific item. Python`from google import genai from google.genai import types client = genai.Client() # Prepare standard image part with open('image.jpg', 'rb') as f: image_bytes = f.read() image_part = types.Part.from_bytes(data=image_bytes, mime_type='image/jpeg') # Set global configuration config = types.GenerateContentConfig( media_resolution=types.MediaResolution.MEDIA_RESOLUTION_HIGH ) response = client.models.generate_content( model='gemini-3.8-flash', contents=[\"Describe this image:\", image_part], config=config ) print(response.text)` Javascript`import { GoogleGenAI, MediaResolution } from '@google/genai'; import * as fs from 'fs'; const ai = new GoogleGenAI({ }); async function run() { // ... (Image loading logic) ... const response = await ai.models.generateContent({ model: 'gemini-3.8-flash', contents: [\"Describe this image:\", imagePart], config: { mediaResolution: MediaResolution.MEDIA_RESOLUTION_HIGH } }); console.log(response.text); } run();` REST`# ... (Base64 encoding logic) ...\n\ncurl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [...], \"generation_config\": { \"media_resolution\": \"MEDIA_RESOLUTION_HIGH\" } }'` Available resolution values The Gemini API defines the following levels for media resolution: `MEDIA_RESOLUTION_UNSPECIFIED`: The default setting. The token count for\nthis level varies significantly between Gemini 3 and earlier Gemini models. `MEDIA_RESOLUTION_LOW`: Lower token count, resulting in faster processing\nand lower cost, but with less detail. `MEDIA_RESOLUTION_MEDIUM`: A balance between detail, cost, and latency. `MEDIA_RESOLUTION_HIGH`: Higher token count, providing more detail for the\nmodel to work with, at the expense of increased latency and cost. `MEDIA_RESOLUTION_ULTRA_HIGH` (Per part only): Highest token count, required for specific\nuse cases such as [computer use](/gemini-api/docs/computer-use). Note that `MEDIA_RESOLUTION_HIGH` provides the optimal performance for most use\ncases. The exact number of tokens generated for each of these\nlevels depends on both the **media type** (Image, Video, PDF) and the **model\nversion**. Token counts The tables below summarize the approximate token counts for each\n`media_resolution` value and media type per model family. **Gemini 3 models** **MediaResolution** **Image** **Video** **PDF** `MEDIA_RESOLUTION_UNSPECIFIED` (Default)\n 1120\n 70\n 560\n `MEDIA_RESOLUTION_LOW` 280\n 70\n 280 + Native Text\n `MEDIA_RESOLUTION_MEDIUM` 560\n 70\n 560 + Native Text\n `MEDIA_RESOLUTION_HIGH` 1120\n 280\n 1120 + Native Text\n `MEDIA_RESOLUTION_ULTRA_HIGH` 2240\n N/A\n N/A\n **Gemini 2.5 models** **MediaResolution** **Image** **Video** **PDF (Scanned)** **PDF (Native)** `MEDIA_RESOLUTION_UNSPECIFIED` (Default)\n 256 + Pan & Scan (~2048)\n 256\n 256 + OCR\n 256 + Native Text\n `MEDIA_RESOLUTION_LOW` 64\n 64\n 64 + OCR\n 64 + Native Text\n `MEDIA_RESOLUTION_MEDIUM` 256\n 256\n 256 + OCR\n 256 + Native Text\n `MEDIA_RESOLUTION_HIGH` 256 + Pan & Scan\n 256\n 256 + OCR\n 256 + Native Text\n Choosing the right resolution **Default (`UNSPECIFIED`):** Start with the default. It's tuned for a good\nbalance of quality, latency, and cost for most common use cases. **`LOW`:** Use for scenarios where cost and latency are paramount, and\nfine-grained detail is less critical. **`MEDIUM` / `HIGH`:** Increase the resolution when the task requires\nunderstanding intricate details within the media. This is often needed for\ncomplex visual analysis, chart reading, or dense document comprehension. **`ULTRA HIGH`** - Only available for per part setting. Recommended for specific use cases such as\ncomputer use or where testing shows a clear enhancement over `HIGH`. **Per-part control (Gemini 3):** Optimizes token usage. For\nexample, in a prompt with multiple images, use `HIGH` for a complex diagram\nand `LOW` or `MEDIUM` for simpler contextual images. **Recommended settings** The following lists the recommended media resolution settings for each\nsupported media type. **Media Type** **Recommended Setting** **Max Tokens** **Usage Guidance** **Images** `MEDIA_RESOLUTION_HIGH` 1120\n Recommended for most image analysis tasks to ensure maximum quality.\n **PDFs** `MEDIA_RESOLUTION_MEDIUM` 560\n Optimal for document understanding; quality typically saturates at `medium`. Increasing to `high` rarely improves OCR results for standard documents.\n **Video** (General)\n `MEDIA_RESOLUTION_LOW` (or `MEDIA_RESOLUTION_MEDIUM`)\n 70 (per frame)\n **Note:** For video, `low` and `medium` settings are treated identically (70 tokens) to optimize context usage. This is sufficient for most action recognition and description tasks.\n **Video** (Text-heavy)\n `MEDIA_RESOLUTION_HIGH` 280 (per frame)\n Required only when the use case involves reading dense text (OCR) or small details within video frames.\n Always test and evaluate the impact of different resolution settings on your\nspecific application to find the best trade-off between quality, latency, and\ncost. Relationship with video processing modes The `media_resolution` and processing parameters control different aspects of video input: `media_resolution` controls the **resolution** of each frame (number of tokens per frame). `processing` / `media_processing` controls **which content from the video** is loaded into context. You can set both on the same video input. For example, you might use agentic processing with low media resolution to minimize total token usage for a long video. For details on video processing modes, see the [Agentic video understanding](/gemini-api/docs/generate-content/video-understanding#agentic-video-understanding) guide. Version compatibility summary The `MediaResolution` enum is available for all models supporting media\ninput. The token counts associated with each enum level **differ** between\nGemini 3 models and earlier Gemini versions. Setting `media_resolution` on individual `Part` objects is **exclusive to\nGemini 3 models**. Next steps Learn more about the multimodal capabilities of Gemini API in the\n[image understanding](/gemini-api/docs/generate-content/image-understanding), [video understanding](/gemini-api/docs/generate-content/video-understanding) and\n[document understanding](/gemini-api/docs/generate-content/document-processing) guides. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 10458, "slov": 1370, "odkazu": 128, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:18", "sha256": "4ebd9089340ebda188ecbd725cc2e2c0d59ee50987f3e3a384d7fe3b64a85100", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/music-generation", "titulek": "Generate music with Lyria 3.5 | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Generate music with Lyria 3.5", "popis": "Generate music with the Gemini API using Lyria 3 Clip and Lyria 3.5", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/music-generation", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Generate music with Lyria 3.5  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Generate music with the Gemini API using Lyria 3 Clip and Lyria 3.5", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/music-generation", "og:image": "https://ai.google.dev/static/site-assets/images/vision.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Generate music with Lyria 3.5"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Generate music with Lyria 3.5", "item": "https://ai.google.dev/gemini-api/docs/generate-content/music-generation"}]}], "drobecky": ["Generate Content API", "Generate music with Lyria 3.5"], "osnova": [{"uroven": 1, "text": "Generate music with Lyria 3.5"}, {"uroven": 2, "text": "Generate a music clip"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "C#"}, {"uroven": 2, "text": "Generate a full-length song"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "C#"}, {"uroven": 2, "text": "Select output format"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Parse the response"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Generate music from images"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "C#"}, {"uroven": 2, "text": "Provide custom lyrics"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Control timing and structure"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Generate instrumental tracks"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Generate music in different languages"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "Java"}, {"uroven": 3, "text": "C#"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Model intelligence"}, {"uroven": 2, "text": "Interactions API"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "Prompting guide"}, {"uroven": 3, "text": "Genre"}, {"uroven": 3, "text": "Instruments"}, {"uroven": 3, "text": "Song structure"}, {"uroven": 3, "text": "Lyrics"}, {"uroven": 4, "text": "Using your own lyrics"}, {"uroven": 4, "text": "Prompting the model to write lyrics"}, {"uroven": 3, "text": "Vocals"}, {"uroven": 3, "text": "Other prompt parameters"}, {"uroven": 3, "text": "Example prompts"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "What's next"}], "markdown": "Generate music with Lyria 3.5 Lyria 3.5 is Google's family of music generation models, available\nthrough the Gemini API. With Lyria 3.5, you can generate high-quality, 44.1 kHz\nstereo audio from text prompts or from images. These models deliver structural\ncoherence, including vocals, timed lyrics, and full instrumental arrangements. The Lyria family includes models: Model Model ID Best for Duration Output **Lyria 3 Clip** `lyria-3-clip-preview` Short clips, loops, previews 30 seconds MP3 **Lyria 3.5** `lyria-3.5` Full-length songs with verses, choruses, bridges A couple of minutes (controllable via prompt) MP3 Both models can be used using the standard `generateContent` method and the new\n[Interactions API](/gemini-api/docs/interactions-overview), supporting multimodal\ninputs (text and images), and produce **44.1 kHz high-fidelity stereo** audio. Generate a music clip The Lyria 3 Clip model always generates a **30-second** clip. To generate a\nclip, call the `generateContent` method with a text prompt. The response always\nincludes the generated lyrics and song structure alongside the audio. Python`from google import genai client = genai.Client() response = client.models.generate_content( model=\"lyria-3-clip-preview\", contents=\"Create a 30-second cheerful acoustic folk song with \" \"guitar and harmonica.\", ) # Parse the response for part in response.parts: if part.text is not None: print(part.text) elif part.inline_data is not None: with open(\"clip.mp3\", \"wb\") as f: f.write(part.inline_data.data) print(\"Audio saved to clip.mp3\")` JavaScript`import { GoogleGenAI } from \"@google/genai\"; import * as fs from \"node:fs\"; const ai = new GoogleGenAI({}); async function main() { const response = await ai.models.generateContent({ model: \"lyria-3-clip-preview\", contents: \"Create a 30-second cheerful acoustic folk song with \" + \"guitar and harmonica.\", }); for (const part of response.candidates[0].content.parts) { if (part.text) { console.log(part.text); } else if (part.inlineData) { const buffer = Buffer.from(part.inlineData.data, \"base64\"); fs.writeFileSync(\"clip.mp3\", buffer); console.log(\"Audio saved to clip.mp3\"); } } } main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"os\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } result, err := client.Models.GenerateContent( ctx, \"lyria-3-clip-preview\", genai.Text(\"Create a 30-second cheerful acoustic folk song \" + \"with guitar and harmonica.\"), nil, ) if err != nil { log.Fatal(err) } for _, part := range result.Candidates[0].Content.Parts { if part.Text != \"\" { fmt.Println(part.Text) } else if part.InlineData != nil { err := os.WriteFile(\"clip.mp3\", part.InlineData.Data, 0644) if err != nil { log.Fatal(err) } fmt.Println(\"Audio saved to clip.mp3\") } } }` Java`import com.google.genai.Client; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.Part; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class GenerateMusicClip { public static void main(String[] args) throws IOException { try (Client client = new Client()) { GenerateContentResponse response = client.models.generateContent( \"lyria-3-clip-preview\", \"Create a 30-second cheerful acoustic folk song with \" + \"guitar and harmonica.\"); for (Part part : response.parts()) { if (part.text().isPresent()) { System.out.println(part.text().get()); } else if (part.inlineData().isPresent()) { var blob = part.inlineData().get(); if (blob.data().isPresent()) { Files.write(Paths.get(\"clip.mp3\"), blob.data().get()); System.out.println(\"Audio saved to clip.mp3\"); } } } } } }` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/lyria-3-clip-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"Create a 30-second cheerful acoustic folk song with guitar and harmonica.\"} ] }] }'` C#`using System.Threading.Tasks; using Google.GenAI; using Google.GenAI.Types; using System.IO; public class GenerateMusicClip { public static async Task main() { var client = new Client(); var response = await client.Models.GenerateContentAsync( model: \"lyria-3-clip-preview\", contents: \"Create a 30-second cheerful acoustic folk song with guitar and harmonica.\" ); foreach (var part in response.Candidates[0].Content.Parts) { if (part.Text != null) { Console.WriteLine(part.Text); } else if (part.InlineData != null) { await File.WriteAllBytesAsync(\"clip.mp3\", part.InlineData.Data); Console.WriteLine(\"Audio saved to clip.mp3\"); } } } }` Generate a full-length song Use the `lyria-3.5` model to generate full-length songs that last a\ncouple of minutes. The Pro model understands musical structure and can create\ncompositions with distinct verses, choruses, and bridges. You can influence the\nduration by specifying it in your prompt (e.g., \"create a 2-minute song\") or by\nusing timestamps to define the structure. Python`response = client.models.generate_content( model=\"lyria-3.5\", contents=\"An epic cinematic orchestral piece about a journey home. \" \"Starts with a solo piano intro, builds through sweeping \" \"strings, and climaxes with a massive wall of sound.\", )` JavaScript`const response = await ai.models.generateContent({ model: \"lyria-3.5\", contents: \"An epic cinematic orchestral piece about a journey home. \" + \"Starts with a solo piano intro, builds through sweeping \" + \"strings, and climaxes with a massive wall of sound.\", });` Go`result, err := client.Models.GenerateContent( ctx, \"lyria-3.5\", genai.Text(\"An epic cinematic orchestral piece about a journey \" + \"home. Starts with a solo piano intro, builds through \" + \"sweeping strings, and climaxes with a massive wall of sound.\"), nil, )` Java`GenerateContentResponse response = client.models.generateContent( \"lyria-3.5\", \"An epic cinematic orchestral piece about a journey home. \" + \"Starts with a solo piano intro, builds through sweeping \" + \"strings, and climaxes with a massive wall of sound.\");` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/lyria-3.5:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"An epic cinematic orchestral piece about a journey home. Starts with a solo piano intro, builds through sweeping strings, and climaxes with a massive wall of sound.\"} ] }] }'` C#`var response = await client.Models.GenerateContentAsync( model: \"lyria-3.5\", contents: \"An epic cinematic orchestral piece about a journey home. \" + \"Starts with a solo piano intro, builds through sweeping \" + \"strings, and climaxes with a massive wall of sound.\" );` Select output format By default, the Lyria 3.5 models generate audio in **MP3** format. For\nLyria 3.5, you can also request the output in **WAV** format by setting\nthe `response_format` in the `generationConfig`. Python`from google.genai import types response = client.models.generate_content( model=\"lyria-3.5\", contents=\"An atmospheric ambient track.\", config=types.GenerateContentConfig( response_modalities=[\"AUDIO\", \"TEXT\"], response_format={\"audio\": {\"mime_type\": \"audio/wav\"}}, ), )` JavaScript`const response = await ai.models.generateContent({ model: \"lyria-3.5\", contents: \"An atmospheric ambient track.\", config: { responseModalities: [\"AUDIO\", \"TEXT\"], responseFormat: { audio: { mimeType: \"audio/wav\" } }, }, });` Go`config := &genai.GenerateContentConfig{ ResponseModalities: []string{\"AUDIO\", \"TEXT\"}, ResponseMIMEType: \"audio/wav\", } result, err := client.Models.GenerateContent( ctx, \"lyria-3.5\", genai.Text(\"An atmospheric ambient track.\"), config, )` Java`GenerateContentConfig config = GenerateContentConfig.builder() .responseModalities(\"AUDIO\", \"TEXT\") .responseFormat(ResponseFormat.builder().audio(AudioFormat.builder().mimeType(\"audio/wav\").build()).build()) .build(); GenerateContentResponse response = client.models.generateContent( \"lyria-3.5\", \"An atmospheric ambient track.\", config);` C#`var config = new GenerateContentConfig { ResponseModalities = { \"AUDIO\", \"TEXT\" }, ResponseMimeType = \"audio/wav\" }; var response = await client.Models.GenerateContentAsync( model: \"lyria-3.5\", contents: \"An atmospheric ambient track.\", config: config );` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/lyria-3.5:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"An atmospheric ambient track.\"} ] }], \"generationConfig\": { \"responseModalities\": [\"AUDIO\", \"TEXT\"], \"responseFormat\": { \"audio\": { \"mimeType\": \"audio/wav\" } } } }'` Parse the response The response from Lyria 3.5 contains multiple parts. Text parts contain the\ngenerated lyrics or a JSON description of the song structure. Parts with\n`inline_data` contain the audio bytes. Python`lyrics = [] audio_data = None for part in response.parts: if part.text is not None: lyrics.append(part.text) elif part.inline_data is not None: audio_data = part.inline_data.data if lyrics: print(\"Lyrics:\\n\" + \"\\n\".join(lyrics)) if audio_data: with open(\"output.mp3\", \"wb\") as f: f.write(audio_data)` JavaScript`const lyrics = []; let audioData = null; for (const part of response.candidates[0].content.parts) { if (part.text) { lyrics.push(part.text); } else if (part.inlineData) { audioData = Buffer.from(part.inlineData.data, \"base64\"); } } if (lyrics.length) { console.log(\"Lyrics:\\n\" + lyrics.join(\"\\n\")); } if (audioData) { fs.writeFileSync(\"output.mp3\", audioData); }` Go`var lyrics []string var audioData []byte for _, part := range result.Candidates[0].Content.Parts { if part.Text != \"\" { lyrics = append(lyrics, part.Text) } else if part.InlineData != nil { audioData = part.InlineData.Data } } if len(lyrics) > 0 { fmt.Println(\"Lyrics:\\n\" + strings.Join(lyrics, \"\\n\")) } if audioData != nil { err := os.WriteFile(\"output.mp3\", audioData, 0644) if err != nil { log.Fatal(err) } }` Java`List lyrics = new ArrayList<>(); byte[] audioData = null; for (Part part : response.parts()) { if (part.text().isPresent()) { lyrics.add(part.text().get()); } else if (part.inlineData().isPresent()) { audioData = part.inlineData().get().data().get(); } } if (!lyrics.isEmpty()) { System.out.println(\"Lyrics:\\n\" + String.join(\"\\n\", lyrics)); } if (audioData != null) { Files.write(Paths.get(\"output.mp3\"), audioData); }` C#`var lyrics = new List(); byte[] audioData = null; foreach (var part in response.Candidates[0].Content.Parts) { if (part.Text != null) { lyrics.Add(part.Text); } else if (part.InlineData != null) { audioData = part.InlineData.Data; } } if (lyrics.Count > 0) { Console.WriteLine(\"Lyrics:\\n\" + string.Join(\"\\n\", lyrics)); } if (audioData != null) { await File.WriteAllBytesAsync(\"output.mp3\", audioData); }` REST`# The output from the REST API is a JSON object containing base64 encoded data. # You can extract the text or the audio data using a tool like jq. # To extract the audio and save it to a file:\ncurl ... | jq -r '.candidates[0].content.parts[] | select(.inlineData) | .inlineData.data' | base64 -d > output.mp3` Generate music from images Lyria 3.5 supports multimodal inputs — you can provide up to **10 images**\nalongside your text prompt and the model will compose music inspired by the\nvisual content. Python`from PIL import Image image = Image.open(\"desert_sunset.jpg\") response = client.models.generate_content( model=\"lyria-3.5\", contents=[ \"An atmospheric ambient track inspired by the mood and \" \"colors in this image.\", image, ], )` JavaScript`const imageData = fs.readFileSync(\"desert_sunset.jpg\"); const base64Image = imageData.toString(\"base64\"); const response = await ai.models.generateContent({ model: \"lyria-3.5\", contents: [ { text: \"An atmospheric ambient track inspired by the mood \" + \"and colors in this image.\" }, { inlineData: { mimeType: \"image/jpeg\", data: base64Image, }, }, ], });` Go`imgData, err := os.ReadFile(\"desert_sunset.jpg\") if err != nil { log.Fatal(err) } parts := []*genai.Part{ genai.NewPartFromText(\"An atmospheric ambient track inspired \" + \"by the mood and colors in this image.\"), &genai.Part{ InlineData: &genai.Blob{ MIMEType: \"image/jpeg\", Data: imgData, }, }, } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } result, err := client.Models.GenerateContent( ctx, \"lyria-3.5\", contents, nil, )` Java`GenerateContentResponse response = client.models.generateContent( \"lyria-3.5\", Content.fromParts( Part.fromText(\"An atmospheric ambient track inspired by \" + \"the mood and colors in this image.\"), Part.fromBytes( Files.readAllBytes(Path.of(\"desert_sunset.jpg\")), \"image/jpeg\")));` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/lyria-3.5:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H 'Content-Type: application/json' \\ -d \"{ \\\"contents\\\": [{ \\\"parts\\\":[ {\\\"text\\\": \\\"An atmospheric ambient track inspired by the mood and colors in this image.\\\"}, { \\\"inline_data\\\": { \\\"mime_type\\\":\\\"image/jpeg\\\", \\\"data\\\": \\\"\\\" } } ] }] }\"` C#`var response = await client.Models.GenerateContentAsync( model: \"lyria-3.5\", contents: new List { Part.FromText(\"An atmospheric ambient track inspired by the mood and colors in this image.\"), Part.FromBytes(await File.ReadAllBytesAsync(\"desert_sunset.jpg\"), \"image/jpeg\") } );` \n Provide custom lyrics You can write your own lyrics and include them in the prompt. Use section tags\nlike `[Verse]`, `[Chorus]`, and `[Bridge]` to help the model understand the\nsong structure: Python`prompt = \"\"\" Create a dreamy indie pop song with the following lyrics: [Verse 1] Walking through the neon glow, city lights reflect below, every shadow tells a story, every corner, fading glory. [Chorus] We are the echoes in the night, burning brighter than the light, hold on tight, don't let me go, we are the echoes down below. [Verse 2] Footsteps lost on empty streets, rhythms sync to heartbeats, whispers carried by the breeze, dancing through the autumn leaves. \"\"\" response = client.models.generate_content( model=\"lyria-3.5\", contents=prompt, )` JavaScript`const prompt = ` Create a dreamy indie pop song with the following lyrics: [Verse 1] Walking through the neon glow, city lights reflect below, every shadow tells a story, every corner, fading glory. [Chorus] We are the echoes in the night, burning brighter than the light, hold on tight, don't let me go, we are the echoes down below. [Verse 2] Footsteps lost on empty streets, rhythms sync to heartbeats, whispers carried by the breeze, dancing through the autumn leaves. `; const response = await ai.models.generateContent({ model: \"lyria-3.5\", contents: prompt, });` Go`prompt := ` Create a dreamy indie pop song with the following lyrics: [Verse 1] Walking through the neon glow, city lights reflect below, every shadow tells a story, every corner, fading glory. [Chorus] We are the echoes in the night, burning brighter than the light, hold on tight, don't let me go, we are the echoes down below. [Verse 2] Footsteps lost on empty streets, rhythms sync to heartbeats, whispers carried by the breeze, dancing through the autumn leaves. ` result, err := client.Models.GenerateContent( ctx, \"lyria-3.5\", genai.Text(prompt), nil, )` Java`String prompt = \"\"\" Create a dreamy indie pop song with the following lyrics: [Verse 1] Walking through the neon glow, city lights reflect below, every shadow tells a story, every corner, fading glory. [Chorus] We are the echoes in the night, burning brighter than the light, hold on tight, don't let me go, we are the echoes down below. [Verse 2] Footsteps lost on empty streets, rhythms sync to heartbeats, whispers carried by the breeze, dancing through the autumn leaves. \"\"\"; GenerateContentResponse response = client.models.generateContent( \"lyria-3.5\", prompt);` C#`var prompt = @\" Create a dreamy indie pop song with the following lyrics: [Verse 1] Walking through the neon glow, city lights reflect below, every shadow tells a story, every corner, fading glory. [Chorus] We are the echoes in the night, burning brighter than the light, hold on tight, don't let me go, we are the echoes down below. [Verse 2] Footsteps lost on empty streets, rhythms sync to heartbeats, whispers carried by the breeze, dancing through the autumn leaves. \"; var response = await client.Models.GenerateContentAsync( model: \"lyria-3.5\", contents: prompt );` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/lyria-3.5:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"Create a dreamy indie pop song with the following lyrics: ...\"} ] }] }'` Control timing and structure You can specify exactly what happens at specific moments in the song using\ntimestamps. This is useful for controlling when instruments enter, when lyrics\nare delivered, and how the song progresses: Python`prompt = \"\"\" [0:00 - 0:10] Intro: Begin with a soft lo-fi beat and muffled vinyl crackle. [0:10 - 0:30] Verse 1: Add a warm Fender Rhodes piano melody and gentle vocals singing about a rainy morning. [0:30 - 0:50] Chorus: Full band with upbeat drums and soaring synth leads. The lyrics are hopeful and uplifting. [0:50 - 1:00] Outro: Fade out with the piano melody alone. \"\"\" response = client.models.generate_content( model=\"lyria-3.5\", contents=prompt, )` JavaScript`const prompt = ` [0:00 - 0:10] Intro: Begin with a soft lo-fi beat and muffled vinyl crackle. [0:10 - 0:30] Verse 1: Add a warm Fender Rhodes piano melody and gentle vocals singing about a rainy morning. [0:30 - 0:50] Chorus: Full band with upbeat drums and soaring synth leads. The lyrics are hopeful and uplifting. [0:50 - 1:00] Outro: Fade out with the piano melody alone. `; const response = await ai.models.generateContent({ model: \"lyria-3.5\", contents: prompt, });` Go`prompt := ` [0:00 - 0:10] Intro: Begin with a soft lo-fi beat and muffled vinyl crackle. [0:10 - 0:30] Verse 1: Add a warm Fender Rhodes piano melody and gentle vocals singing about a rainy morning. [0:30 - 0:50] Chorus: Full band with upbeat drums and soaring synth leads. The lyrics are hopeful and uplifting. [0:50 - 1:00] Outro: Fade out with the piano melody alone. ` result, err := client.Models.GenerateContent( ctx, \"lyria-3.5\", genai.Text(prompt), nil, )` Java`String prompt = \"\"\" [0:00 - 0:10] Intro: Begin with a soft lo-fi beat and muffled vinyl crackle. [0:10 - 0:30] Verse 1: Add a warm Fender Rhodes piano melody and gentle vocals singing about a rainy morning. [0:30 - 0:50] Chorus: Full band with upbeat drums and soaring synth leads. The lyrics are hopeful and uplifting. [0:50 - 1:00] Outro: Fade out with the piano melody alone. \"\"\"; GenerateContentResponse response = client.models.generateContent( \"lyria-3.5\", prompt);` C#`var prompt = @\" [0:00 - 0:10] Intro: Begin with a soft lo-fi beat and muffled vinyl crackle. [0:10 - 0:30] Verse 1: Add a warm Fender Rhodes piano melody and gentle vocals singing about a rainy morning. [0:30 - 0:50] Chorus: Full band with upbeat drums and soaring synth leads. The lyrics are hopeful and uplifting. [0:50 - 1:00] Outro: Fade out with the piano melody alone. \"; var response = await client.Models.GenerateContentAsync( model: \"lyria-3.5\", contents: prompt );` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/lyria-3.5:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"[0:00 - 0:10] Intro: ...\"} ] }] }'` Generate instrumental tracks For background music, game soundtracks, or any use case where vocals are not\nrequired, you can prompt the model to produce instrumental-only tracks: Python`response = client.models.generate_content( model=\"lyria-3-clip-preview\", contents=\"A bright chiptune melody in C Major, retro 8-bit \" \"video game style. Instrumental only, no vocals.\", )` JavaScript`const response = await ai.models.generateContent({ model: \"lyria-3-clip-preview\", contents: \"A bright chiptune melody in C Major, retro 8-bit \" + \"video game style. Instrumental only, no vocals.\", });` Go`result, err := client.Models.GenerateContent( ctx, \"lyria-3-clip-preview\", genai.Text(\"A bright chiptune melody in C Major, retro 8-bit \" + \"video game style. Instrumental only, no vocals.\"), nil, )` Java`GenerateContentResponse response = client.models.generateContent( \"lyria-3-clip-preview\", \"A bright chiptune melody in C Major, retro 8-bit \" + \"video game style. Instrumental only, no vocals.\");` C#`var response = await client.Models.GenerateContentAsync( model: \"lyria-3-clip-preview\", contents: \"A bright chiptune melody in C Major, retro 8-bit \" + \"video game style. Instrumental only, no vocals.\" );` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/lyria-3-clip-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"A bright chiptune melody in C Major, retro 8-bit video game style. Instrumental only, no vocals.\"} ] }] }'` Generate music in different languages Lyria 3.5 generates lyrics in the language of your prompt. To generate a song\nwith French lyrics, write your prompt in French. The model adapts its vocal\nstyle and pronunciation to match the language. Python`response = client.models.generate_content( model=\"lyria-3.5\", contents=\"CrĂŠe une chanson pop romantique en français sur un \" \"coucher de soleil Ă Paris. Utilise du piano et de \" \"la guitare acoustique.\", )` JavaScript`const response = await ai.models.generateContent({ model: \"lyria-3.5\", contents: \"CrĂŠe une chanson pop romantique en français sur un \" + \"coucher de soleil Ă Paris. Utilise du piano et de \" + \"la guitare acoustique.\", });` Go`result, err := client.Models.GenerateContent( ctx, \"lyria-3.5\", genai.Text(\"CrĂŠe une chanson pop romantique en français sur un \" + \"coucher de soleil Ă Paris. Utilise du piano et de \" + \"la guitare acoustique.\"), nil, )` Java`GenerateContentResponse response = client.models.generateContent( \"lyria-3.5\", \"CrĂŠe une chanson pop romantique en français sur un \" + \"coucher de soleil Ă Paris. Utilise du piano et de \" + \"la guitare acoustique.\");` C#`var response = await client.Models.GenerateContentAsync( model: \"lyria-3.5\", contents: \"CrĂŠe une chanson pop romantique en français sur un \" + \"coucher de soleil Ă Paris. Utilise du piano et de \" + \"la guitare acoustique.\" );` REST`curl -s -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/lyria-3.5:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [{ \"parts\": [ {\"text\": \"CrĂŠe une chanson pop romantique en français sur un coucher de soleil Ă Paris. Utilise du piano et de la guitare acoustique.\"} ] }] }'` Model intelligence Lyria 3.5 analyzes your prompt process where the\nmodel reasons through musical structure (intro, verse, chorus, bridge, etc.)\nbased on your prompt.\nThis happens before the audio is generated and ensures structural coherence and\nmusicality. Interactions API You can use Lyria 3.5 models with the [Interactions API](/gemini-api/docs/interactions-overview);\na unified interface for interacting with Gemini models and agents. It simplifies\nstate management and long-running tasks for complex multimodal use cases. Python`import base64 from google import genai client = genai.Client() interaction = client.interactions.create( model=\"lyria-3.5\", input=\"A melancholic jazz fusion track in D minor, \" + \"featuring a smooth saxophone melody, walking bass line, \" + \"and complex drum rhythms.\", ) generated_audio = interaction.output_audio if generated_audio: with open(\"interaction_output.mp3\", \"wb\") as f: f.write(base64.b64decode(generated_audio.data)) print(\"Audio saved to interaction_output.mp3\") lyrics = interaction.output_text if lyrics: print(f\"Lyrics:\\n{lyrics}\")` JavaScript`import { GoogleGenAI } from '@google/genai'; import * as fs from 'fs'; const client = new GoogleGenAI({}); const interaction = await client.interactions.create({ model: 'lyria-3.5', input: 'A melancholic jazz fusion track in D minor, ' + 'featuring a smooth saxophone melody, walking bass line, ' + 'and complex drum rhythms.', }); const generatedAudio = interaction.output_audio; if (generatedAudio) { fs.writeFileSync('interaction_output.mp3', Buffer.from(generatedAudio.data, 'base64')); console.log('Audio saved to interaction_output.mp3'); } const lyrics = interaction.output_text; if (lyrics) { console.log(`Lyrics:\\n${lyrics}`); }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/interactions\" \\\n-H \"Content-Type: application/json\" \\\n-H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n-d '{ \"model\": \"lyria-3.5\", \"input\": \"A melancholic jazz fusion track in D minor, featuring a smooth saxophone melody, walking bass line, and complex drum rhythms.\" }'` Prompting guide Your prompt can be as simple as \"a folk song about cute cats avoiding puddles,\nfemale vocals and the noise of rain\", or something detailed and structured\nlike: A 1980s-style synth-pop track with a driving beat, shimmering synthesizers,\nand a catchy, anthemic chorus. The song should have a retro-futuristic feel,\nreminiscent of classic 80s pop hits, with a modern production polish. The\ntempo should be upbeat and danceable, around 120 BPM, with a clear\nverse-chorus structure and a memorable instrumental hook. The lyrics are about\nthe feeling of getting ready for a party. Both simple and complex prompts can give you good outputs. Experiment with\nthese tips to find what works best for you. Genre Lead your prompt with the genre of music you want, such as hip hop, rock, and\nrap. You can specify a mix of genres: A fusion of metal and rap A combination of death metal and opera A classical piece with electronic drone elements Modern electronic dance music (EDM) mixed with Europop You can also incorporate an era: Early 90s hip-hop 60s French ye-ye pop 80s electronic experimentation 2000s mainstream pop If you prompt for bespoke genres or regional variants, like \"Berlin techno\" or\n\"Bay area hyphy\", the model will attempt to capture that essence, but it may\nnot always get it right. Instruments By default Lyria 3.5 will make songs with the instruments and tools you'd\nexpect for the genre. You don't need to be prescriptive. However, a dance track isn't going to include a saxophone unless you ask for\nit. So if you want a saxophone solo, you need to prompt it: A dance track with a driving beat, shimmering synthesizers, and a catchy,\nanthemic chorus. A saxophone solo should come in during the bridge. Your prompt can include specific instruments, how they sound, and how they\ninteract with each other. You can use this combination to create certain moods\nor textures: A dirty, distorted bassline fighting against clean, crisp hi-hats Warm, analog synthesizer pads swelling underneath a dry, intimate acoustic\nguitar A wall of sound created by multiple layers of fuzzy guitars, with buried,\ndistant vocals Song structure You can outline the progression of a song in your prompt. Use arrows or a list\nto define the flow: `[Intro]` -> `[Verse 1]` -> `[Chorus]` -> `[Verse 2]` -> `[Chorus]` ->\n`[Bridge]` -> `[Outro]` Start with a quiet piano intro, build into a loud verse, drop into a\nsilence, then explode into the chorus. You can also specify how energy levels change between these sections: Build tension in the pre-chorus, then drop to silence before a massive,\nexplosive chorus Gradual crescendo throughout the song, adding one instrument at a time\nuntil a chaotic wall of sound Sudden stop after the bridge, followed by an acapella chorus You can also prompt the exact time you want something to happen: Build to a drop at 12s Someone says \"what\" every 2 seconds The chorus kicks in at 22s Lyrics Vocals and lyrics are generated by default. You can provide your own lyrics,\nask for no lyrics (or an instrumental), or steer the lyric generation in the\ndirection you want. Your lyrics will be in the language you write your prompt in. You can also ask\nfor lyrics to be in another language, like \"Write the lyrics in French\". Using your own lyrics To give the model your own lyrics, include them in the prompt with a \"Lyrics:\"\nprefix: `Lyrics:\n\n[Intro]\nOooh, oooh\n\n[Verse 1]\nLet's go\nLet's go\nGo with the flow\n\n[Chorus]\n...` You can prefix parts of the song with section titles like `[Intro]`,\n`[Verse 1]`, `[Pre-chorus]`, `[Chorus]` and `[Outro]`. If you want a word or line to be repeated, like an echo or by backing singers,\nyou can include it in parentheses: \"Let's go (go)\". Prompting the model to write lyrics If you want Lyria 3.5 to make lyrics for you, it's best to include details\nof what the lyrics will be about in your prompt. Otherwise the model needs to\ninfer a subject from your music prompt, and it may not be what you want. The lyrics are about lost love and the pain of heartbreak. The singer is\nreminiscing about a past relationship and the memories that come flooding\nback. If you want a repeating chorus, it helps to ask for one in your prompt: The lyrics are about lost love and the pain of heartbreak. The singer is\nreminiscing about a past relationship and the memories that come flooding\nback. A powerful chorus focuses on getting over the pain and moving on. Lyria 3.5 will automatically steer the structure of the lyrics towards the\ntype of music you're requesting, but you can re-emphasize this in your prompt\ntoo. For example: An EDM track that repeats the same energetic phrase over and over again. You can also prompt for vocal effects that aren't strictly lyrics, for example: A repeating sample from a movie says \"I can't believe this!\" throughout\nthe song A high energy techno track, right before the drop the sound all stops and a\nlittle voice says \"I don't know what I'm doing here\", then the music drops. The track opens with a conversation about the movies in the 90s being\nbetter than today. Then the track segues into a pop song. Vocals You can prompt for how you want the lyrics to be delivered. For the best\nresults, specify a detailed singer profile covering gender, timbre, and vocal\nrange. **Female Soprano**: Clear, crystalline timbre with an agile, soaring\nquality. Capable of hitting whistly high notes with an airy, breathy\ntexture. **Female Alto**: Rich, warm, and husky lower range. Smoky timbre with a\ntouch of vocal fry, soulful and resonant. **Male Tenor**: Bright, piercing, and energetic. Youthful timbre with a\nslight nasal edge, cutting through the mix with high belting power. **Male Baritone**: Deep, chocolatey, and velvet-smooth. Resonant chest\nvoice with a soothing, crooning delivery. **Weathered Rocker (Male)**: Raspy and textured with a gravelly timbre,\nreminiscent of 90s grunge. Strained upper range for emotional intensity. Other prompt parameters You can also include these parameters to further refine your prompt: **BPM**: Set the tempo (e.g., \"120 BPM\", \"slow tempo around 70 BPM\"). **Key/Scale**: Specify a musical key (e.g., \"in G major\", \"D minor\"). **Mood and atmosphere**: Use descriptive adjectives (e.g., \"nostalgic\",\n\"aggressive\", \"ethereal\", \"dreamy\"). **Duration**: The Clip model always produces 30-second clips. For the Pro\nmodel, specify the desired length in your prompt (e.g., \"create a 2-minute\nsong\") or use timestamps to control duration. Example prompts Here are some examples of effective prompts: `\"A 30-second lofi hip hop beat with dusty vinyl crackle, mellow Rhodes\npiano chords, a slow boom-bap drum pattern at 85 BPM, and a jazzy upright\nbass line. Instrumental only.\"` `\"An upbeat, feel-good pop song in G major at 120 BPM with bright acoustic\nguitar strumming, claps, and warm vocal harmonies about a summer road\ntrip.\"` `\"A dark, atmospheric trap beat at 140 BPM with heavy 808 bass, eerie synth\npads, sharp hi-hats, and a haunting vocal sample. In D minor.\"` Best practices **Iterate with Clip first.** Use the faster `lyria-3-clip-preview` model to\nexperiment with prompts before committing to a full-length generation with\n`lyria-3.5`. **Be specific.** Vague prompts produce generic results. Mention instruments,\nBPM, key, mood, and structure for the best output. **Match your language.** Prompt in the language you want the lyrics in. **Use section tags.** `[Verse]`, `[Chorus]`, `[Bridge]` tags give the model\nclear structure to follow. **Separate lyrics from instructions.** When providing custom lyrics, clearly\nseparate them from your musical direction instructions. Limitations **Safety**: All prompts are checked by safety filters. Prompts that trigger\nthe filters will be blocked. This includes prompts that request specific\nartist voices or the generation of copyrighted lyrics. **Watermarking**: All generated audio includes a\n[SynthID audio watermark](/responsible/docs/safeguards/synthid) for\nidentification. This watermark is imperceptible to the human ear and\ndoes not affect the listening experience. **Multi-turn editing**: Music generation is a single-turn process.\nIterative editing or refining a generated clip through multiple prompts is\nnot supported in the current version of Lyria 3.5. **Length**: The Clip model always generates 30-second clips. The Pro model\ngenerates songs that last a couple of minutes; exact duration can be\ninfluenced through your prompt. **Determinism**: Results may vary between calls, even with the same prompt. What's next Check [pricing](https://ai.google.dev/gemini-api/docs/generate-content/pricing) for Lyria 3.5 models. Try [real-time, streaming music generation](https://ai.google.dev/gemini-api/docs/generate-content/realtime-music-generation) with\nLyria RealTime. Generate multi-speaker conversations with the\n[TTS models](https://ai.google.dev/gemini-api/docs/generate-content/speech-generation). Discover how to generate [images](https://ai.google.dev/gemini-api/docs/generate-content/image-generation) or [videos](https://ai.google.dev/gemini-api/docs/generate-content/video). Find out how Gemini can [understand audio files](https://ai.google.dev/gemini-api/docs/generate-content/audio). Have a real-time conversation with Gemini using the\n[Live API](https://ai.google.dev/gemini-api/docs/generate-content/live). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-08 UTC.", "znaku_textu": 34444, "slov": 5015, "odkazu": 133, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-13 20:12:54", "sha256": "1ba18b3e0596e9ed3d0aff35c7abc7b019cbd6411501845f15e107564f4f3263", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started_Lyria.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/priority-inference", "titulek": "Priority inference | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Priority inference", "popis": "", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/priority-inference", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Priority inference  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/priority-inference", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Priority inference"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Priority inference", "item": "https://ai.google.dev/gemini-api/docs/generate-content/priority-inference"}]}], "drobecky": ["Generate Content API", "Priority inference"], "osnova": [{"uroven": 1, "text": "Priority inference"}, {"uroven": 2, "text": "How to use Priority"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "JavaScript"}, {"uroven": 3, "text": "Go"}, {"uroven": 3, "text": "REST"}, {"uroven": 2, "text": "How Priority inference works"}, {"uroven": 3, "text": "Key benefits"}, {"uroven": 3, "text": "Use cases"}, {"uroven": 3, "text": "Rate limits"}, {"uroven": 3, "text": "Graceful downgrade logic"}, {"uroven": 3, "text": "Client responsibility"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "Supported models"}, {"uroven": 2, "text": "What's next"}], "markdown": "Priority inference Description: Learn how to optimize latency with the Priority inference tier\n\n The Gemini Priority API is a premium inference tier designed for\nbusiness-critical workloads that require lower latency and the highest\nreliability at a premium price point. Priority tier traffic is prioritized above\nstandard API and Flex tier traffic. Priority inference is available to [Tier 2 & Tier 3](/gemini-api/docs/billing#about-billing) users across the GenerateContent API\nand Interactions API endpoints. How to use Priority To use the Priority tier, set the `service_tier` field in the request body to\n`priority`. The default tier is standard if the field is omitted. Python`from google import genai client = genai.Client() try: response = client.models.generate_content( model=\"gemini-3.8-flash\", contents=\"Triage this critical customer support ticket immediately.\", config={\"service_tier\": \"priority\"}, ) # Validate for graceful downgrade if response.sdk_http_response.headers.get(\"x-gemini-service-tier\") == \"standard\": print(\"Warning: Priority limit exceeded, processed at Standard tier.\") print(response.text) except Exception as e: # Standard error handling (e.g., DEADLINE_EXCEEDED) print(f\"Error during API call: {e}\")` JavaScript`import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI({}); async function main() { try { const result = await ai.models.generateContent({ model: \"gemini-3.8-flash\", contents: \"Triage this critical customer support ticket immediately.\", config: {serviceTier: \"priority\"}, }); // Validate for graceful downgrade if (result.sdkHttpResponse.headers.get(\"x-gemini-service-tier\") === \"standard\") { console.log(\"Warning: Priority limit exceeded, processed at Standard tier.\"); } console.log(result.text); } catch (e) { console.log(`Error during API call: ${e}`); } } await main();` Go`package main import ( \"context\" \"fmt\" \"log\" \"google.golang.org/genai\" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) } defer client.Close() resp, err := client.Models.GenerateContent( ctx, \"gemini-3.8-flash\", genai.Text(\"Triage this critical customer support ticket immediately.\"), &genai.GenerateContentConfig{ ServiceTier: \"priority\", }, ) if err != nil { log.Fatalf(\"Error during API call: %v\", err) } // Validate for graceful downgrade if resp.SDKHTTPResponse.Header.Get(\"x-gemini-service-tier\") == \"standard\" { fmt.Println(\"Warning: Priority limit exceeded, processed at Standard tier.\") } fmt.Println(resp.Text()) }` REST`curl -X POST \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{ \"contents\": [{ \"parts\":[{\"text\": \"Analyze user sentiment in real time\"}] }], \"service_tier\": \"priority\" }'` How Priority inference works Priority inference routes requests to high-criticality compute queues, offering\npredictable, fast performance for user-facing applications. Its primary\nmechanism is a graceful server-side downgrade to standard processing for traffic\nthat exceeds dynamic limits, ensuring application stability instead of failing\nthe request. Feature Priority Standard Flex Batch **Pricing** 75-100% more than Standard Full price 50% discount 50% discount **Latency** Seconds Seconds to minutes Minutes (1–15 min target) Up to 24 hours **Reliability** High (Non-sheddable) High / Medium-high Best-effort (Sheddable) High (for throughput) **Interface** Synchronous Synchronous Synchronous Asynchronous Key benefits **Low latency**: Designed for second response times for interactive,\nuser-facing AI tools. **High reliability**: Traffic is treated with the highest criticality and is\nstrictly non-sheddable. **Graceful degradation**: Traffic spikes exceeding dynamic limits are\nautomatically downgraded to the Standard tier for processing instead of failing,\npreventing service outages. **Low friction**: Uses the same synchronous `generateContent` method as the\nstandard and Flex tiers. Use cases Priority processing is ideal for business-critical workflows where performance\nand reliability are paramount. **Interactive AI applications**: Customer service chatbots and copilots where\nusers pay a premium and expect fast, consistent responses. **Real-time decision engines**: Systems requiring highly reliable, low-latency\noutcomes, such as live ticket triaging or fraud detection. **Premium customer features**: Developers who need to guarantee higher service\nlevel objectives (SLOs) for paying customers. Rate limits Priority consumption holds its own rate limits even though consumption is\ncounted towards [overall interactive traffic rate limits](https://aistudio.google.com/rate-limit). The default rate limits\nfor Priority inference are **0.3x standard rate limit for Model / Tier** Graceful downgrade logic If Priority limits are exceeded due to congestion, overflow requests are\n**automatically and gracefully** downgraded to Standard processing instead of\nfailing with a 503 or 429 error. Downgraded requests are billed at the standard\nrate, not the Priority premium rate. Client responsibility **Response monitoring**: Developers should monitor the `x-gemini-service-tier`\nheader in the API response to detect if requests are being frequently downgraded to\n`standard`. **Retries**: Clients must implement retry logic/exponential backoff for\nstandard errors, such as `DEADLINE_EXCEEDED`. Pricing Priority inference is priced at 75-100% more than the [standard API](/gemini-api/docs/pricing) and billed per token. Supported models The following models support Priority inference: Model Priority inference [Gemini 3.8 Flash](/gemini-api/docs/models/gemini-3.8-flash) ✔️ [Gemini 3.7 Flash](/gemini-api/docs/models/gemini-3.7-flash) ✔️ [Gemini 3.6 Flash](/gemini-api/docs/models/gemini-3.6-flash) ✔️ [Gemini 3.5 Flash-Lite](/gemini-api/docs/models/gemini-3.5-flash-lite) ✔️ [Gemini 3.5 Flash](/gemini-api/docs/models/gemini-3.5-flash) ✔️ [Gemini 3.1 Flash-Lite](/gemini-api/docs/models/gemini-3.1-flash-lite) ✔️ [Gemini 3.1 Pro Preview](/gemini-api/docs/models/gemini-3.1-pro-preview) ✔️ [Gemini 3 Flash Preview](/gemini-api/docs/models/gemini-3-flash-preview) ✔️ [Gemini 3 Pro Image Preview](/gemini-api/docs/models/gemini-3-pro-image) ✔️ [Gemini 2.5 Pro](/gemini-api/docs/models/gemini-2.5-pro) ✔️ [Gemini 2.5 Flash](/gemini-api/docs/models/gemini-2.5-flash) ✔️ [Gemini 2.5 Flash Image](/gemini-api/docs/models/gemini-2.5-flash-image) ✔️ [Gemini 2.5 Flash-Lite](/gemini-api/docs/models/gemini-2.5-flash-lite) ✔️ What's next Read about Gemini's other [inference and optimization](/gemini-api/docs/optimization) options: [Flex inference](/gemini-api/docs/flex-inference) for 50% cost reduction. [Batch API](/gemini-api/docs/batch-api) for asynchronous processing within 24 hours. [Context caching](/gemini-api/docs/caching) for reduced input token costs. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-02 UTC.", "znaku_textu": 7338, "slov": 939, "odkazu": 139, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:14:32", "sha256": "b8ad2ea883b98bf3b65caa87c20e1b292421d625764ba57bce508ebe71e505e2", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/rate-limit", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-agentic", "titulek": "Agentic vision capabilities | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Agentic vision capabilities", "popis": "Use Gemini Robotics ER agentic capabilities including code execution, instrument reading, and image annotation.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-agentic", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Agentic vision capabilities  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Use Gemini Robotics ER agentic capabilities including code execution, instrument reading, and image annotation.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-agentic", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Agentic vision capabilities"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Agentic vision capabilities", "item": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-agentic"}]}], "drobecky": ["Generate Content API", "Agentic vision capabilities"], "osnova": [{"uroven": 1, "text": "Agentic vision capabilities"}, {"uroven": 2, "text": "Thinking level"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Object detection (Zoom and crop)"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Read an analog gauge and apply logic"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Measure fluid in a container"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Read markings on a circuit board"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Image annotation"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "What's next"}], "markdown": "Agentic vision capabilities Gemini Robotics ER models can write and execute Python code to manipulate\nimages and apply logic before answering. This page covers code execution\nexamples: object detection with zoom and crop, instrument reading, fluid\nmeasurement, circuit board reading, and image annotation. To adapt these examples to your own use case, replace the prompt text and the\nuploaded image file with your own. You can also adjust the requested JSON\nschema in the prompt to match the output structure your application needs, or\nadd a `system_instruction` to enforce output format and precision. For full runnable code, see the\n[Robotics cookbook](https://github.com/google-gemini/robotics-samples/blob/main/Getting%20Started/gemini_robotics_er.ipynb). Thinking level You can control the thinking level to trade latency for accuracy. Spatial\ntasks like object detection perform well with a low thinking level. Complex tasks like\ncounting or weight estimation benefit from a higher thinking level. The following example sets the thinking level to `high` for a complex counting task: Python`from google import genai from google.genai import types client = genai.Client() with open('scene.jpeg', 'rb') as f: image_bytes = f.read() response = client.models.generate_content( model=\"gemini-robotics-er-2-preview\", contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/jpeg', ), \"Identify and count all objects on the table.\" ], config=types.GenerateContentConfig( thinking_config=types.ThinkingConfig(thinking_level=\"high\") ) ) print(response.text)` See [Thinking](/gemini-api/docs/generate-content/thinking) for details. Object detection (Zoom and crop) The following example demonstrates how to use code execution to zoom and crop an\nimage for a clearer view when detecting objects and returning bounding boxes. 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 = \"\"\" Return JSON in the format {label: val, y: val, x: val, y2: val, x2: val} for the compostable objects in this scene. Please Zoom and crop the image for a clearer view. Return an annotated image of the final result with the bounding boxes drawn on it to the API caller as a part of your process. \"\"\" response = client.models.generate_content( model=\"gemini-robotics-er-2-preview\", contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/jpeg', ), prompt ], config = types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution)], ) ) print(response.text)` The model output would be similar to the following json response: `[ {\"label\": \"compostable\", \"y\": 256, \"x\": 482, \"y2\": 295, \"x2\": 546}, {\"label\": \"compostable\", \"y\": 317, \"x\": 478, \"y2\": 350, \"x2\": 542}, {\"label\": \"compostable\", \"y\": 586, \"x\": 556, \"y2\": 668, \"x2\": 595}, {\"label\": \"compostable\", \"y\": 463, \"x\": 669, \"y2\": 511, \"x2\": 718}, {\"label\": \"compostable\", \"y\": 178, \"x\": 565, \"y2\": 250, \"x2\": 609} ]` The following image displays the boxes returned from the model. Read an analog gauge and apply logic The following example demonstrates how to use the model to read an analog gauge\nand perform time calculations. It uses a system instruction to enforce a JSON output. Python`from google import genai from google.genai import types client = genai.Client() with open('gauge.jpeg', 'rb') as f: image_bytes = f.read() system_instruction = \"Be precise. When JSON is requested, reply with ONLY that JSON (no preface, no code block).\" response = client.models.generate_content( model=\"gemini-robotics-er-2-preview\", contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/jpeg', ), \"\"\"Read the current value from this gauge. Then, calculate how long it will take at the current rate for the value to reach maximum. Reply in JSON: {\"current_value\": val, \"max_value\": val, \"time_to_max_minutes\": val}\"\"\" ], config = types.GenerateContentConfig( system_instruction=system_instruction, tools=[types.Tool(code_execution=types.ToolCodeExecution)], ) ) print(response.text)` Measure fluid in a container The following example demonstrates how to use code execution to measure the\nlevel of fluid in a container. Python`from google import genai from google.genai import types client = genai.Client() with open('fluid.jpeg', 'rb') as f: image_bytes = f.read() system_instruction = \"Be precise. When JSON is requested, reply with ONLY that JSON (no preface, no code block).\" response = client.models.generate_content( model=\"gemini-robotics-er-2-preview\", contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/jpeg', ), \"\"\"Measure the amount of fluid in the container. Reply in JSON: {\"fluid_level_ml\": val, \"container_capacity_ml\": val, \"percentage_full\": val}\"\"\" ], config = types.GenerateContentConfig( system_instruction=system_instruction, tools=[types.Tool(code_execution=types.ToolCodeExecution)], ) ) print(response.text)` Read markings on a circuit board The following example demonstrates how to use code execution to read the\nmarkings on a circuit board. Python`from google import genai from google.genai import types client = genai.Client() with open('circuit_board.jpeg', 'rb') as f: image_bytes = f.read() system_instruction = \"Be precise. When JSON is requested, reply with ONLY that JSON (no preface, no code block).\" response = client.models.generate_content( model=\"gemini-robotics-er-2-preview\", contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/jpeg', ), \"\"\"Read all visible component labels and markings on this circuit board. Reply in JSON: {\"components\": [{\"label\": val, \"location\": [y, x]}]}\"\"\" ], config = types.GenerateContentConfig( system_instruction=system_instruction, tools=[types.Tool(code_execution=types.ToolCodeExecution)], ) ) print(response.text)` Image annotation The following example demonstrates how to use code execution to annotate an\nimage (e.g., drawing arrows for disposal instructions) and return the modified image. 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-2-preview\", contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/jpeg', ), prompt ], config = types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution)], ) ) print(response.text)` The following is an example image input. The model output would be similar to the following: `The annotated image shows the suggested disposal locations for the items on the table:\n - **Green bin (Compost/Organic)**: Green chili, red chili, grapes, and cherries.\n - **Blue bin (Recycling)**: Yellow crushed can and plastic container.\n - **Black bin (Trash)**: Chocolate bar wrapper, Welch's packet, and white tissue.` What's next [Task orchestration](/gemini-api/docs/robotics-orchestration) — long-horizon tasks with custom robot APIs. [Robotics with streaming](/gemini-api/docs/robotics-streaming) — real-time bidirectional streaming (Gemini Robotics ER 2 only). [Video understanding](/gemini-api/docs/robotics-video-progress) — moment finding and progress classification (Gemini Robotics ER 2 only). Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 7926, "slov": 1023, "odkazu": 125, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:15:03", "sha256": "f1e252a299c73d9f81e897a2535200956b4b8c7c79c3947e70e8ce3f7ff92742", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://github.com/google-gemini/robotics-samples/blob/main/Getting%20Started/gemini_robotics_er.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-orchestration", "titulek": "Task orchestration | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Task orchestration", "popis": "Orchestrate long-horizon robotics tasks by combining spatial reasoning with custom robot APIs.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-orchestration", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Task orchestration  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Orchestrate long-horizon robotics tasks by combining spatial reasoning with custom robot APIs.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-orchestration", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Task orchestration"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Task orchestration", "item": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-orchestration"}]}], "drobecky": ["Generate Content API", "Task orchestration"], "osnova": [{"uroven": 1, "text": "Task orchestration"}, {"uroven": 2, "text": "Using a custom robot API"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "What's next"}], "markdown": "Task orchestration Gemini Robotics ER models can plan tasks and reason about space, inferring\nwhich actions to take and which objects to move to complete a goal. This page\nshows an example for driving a pick-and-place\noperation through a custom robot API to orchestrate the task of placing an item\ninto a bowl. For full runnable code, see the\n[Robotics cookbook](https://github.com/google-gemini/robotics-samples/blob/main/Getting%20Started/gemini_robotics_er.ipynb). Using a custom robot API This example demonstrates task orchestration with a custom robot API. It\nintroduces a mock API designed for a pick-and-place operation. The task is to\npick up a blue block and place it in an orange bowl: This example uses the following mock robot API and tool definitions: Python`from google import genai from google.genai import types client = genai.Client() def move(x, y, high): print(f\"Mock Robot: Moving to coordinates: {x}, {y}, {'high above table' if high else 'down at table level'}\") def setGripperState(opened): print(f\"Mock Robot: {'Opening gripper' if opened else 'Closing gripper'}\") robot_origin_y = 300 robot_origin_x = 500 move_declaration = types.FunctionDeclaration( name=\"move\", description=\"Moves the arm to the given coordinates.\", parameters=types.Schema( type=types.Type.OBJECT, properties={ \"x\": types.Schema(type=types.Type.INTEGER, description=\"X coordinate relative to the origin\"), \"y\": types.Schema(type=types.Type.INTEGER, description=\"Y coordinate relative to the origin\"), \"high\": types.Schema(type=types.Type.BOOLEAN, description=\"Set to True to lift the robot arm above the scene. Set to False to place the gripper on the surface.\"), }, required=[\"x\", \"y\", \"high\"], ), ) set_gripper_state_declaration = types.FunctionDeclaration( name=\"setGripperState\", description=\"Opens or closes the robot's gripper.\", parameters=types.Schema( type=types.Type.OBJECT, properties={ \"opened\": types.Schema(type=types.Type.BOOLEAN, description=\"True opens the gripper, False closes the gripper.\"), }, required=[\"opened\"], ), ) robot_tools = types.Tool(function_declarations=[move_declaration, set_gripper_state_declaration])` The following example sends the prompt and image to the model with the tool\ndefinitions. It then runs an agentic loop: after each model response, it\nexecutes any requested function calls (`move`, `setGripperState`), returns the\nresults back to the model, and repeats until the model stops calling functions\nor the step limit is reached. Python`with open(\"robot-api-example.png\", \"rb\") as f: img_bytes = f.read() prompt = ( \"You are a robotic arm with six degrees-of-freedom. \" f\"The origin point for calculating the moves is at normalized point y={robot_origin_y}, x={robot_origin_x}. \" \"Use this as the new (0,0) for calculating moves, allowing x and y to be negative.\\n\\n\" \"Find the blue block and the orange bowl. Calculate their coordinates relative to the origin.\\n\" \"Perform a pick and place operation where you pick up the blue block and place it into the orange bowl. \" \"Call the appropriate sequence of functions to complete this operation.\" ) contents = [ types.Content(role=\"user\", parts=[ types.Part.from_bytes(data=img_bytes, mime_type=\"image/png\"), types.Part(text=prompt), ]) ] print(\"\\n--- Executing Orchestrated Plan ---\") max_steps = 15 # Safety limit to prevent infinite loops step_count = 0 # The Agentic Loop while step_count < max_steps: step_count += 1 response = client.models.generate_content( model=\"gemini-robotics-er-2-preview\", contents=contents, config=types.GenerateContentConfig( tools=[robot_tools], thinking_config=types.ThinkingConfig(thinking_level=\"low\"), ), ) # Add model response to conversation history contents.append(response.candidates[0].content) # Check for function calls function_calls = [part for part in response.candidates[0].content.parts if part.function_call] if not function_calls: # Model is done calling functions print(\"Sequence complete.\") print(f\"Model Summary: {response.text}\") break # Execute function calls and collect results function_response_parts = [] for part in function_calls: fc = part.function_call if fc.name == \"move\": move(**fc.args) elif fc.name == \"setGripperState\": setGripperState(**fc.args) function_response_parts.append( types.Part.from_function_response( name=fc.name, response={\"status\": \"success\"}, ) ) # Send function results back to model contents.append(types.Content(role=\"user\", parts=function_response_parts))` The following shows a possible output of the model based on the prompt and\nthe mock robot API. The output includes the output of the robot\nfunction calls that the model sequenced together. `--- Executing Orchestrated Plan ---\nMock Robot: Opening gripper\nMock Robot: Moving to coordinates: 160, 440, high above table\nMock Robot: Moving to coordinates: 160, 440, down at table level\nMock Robot: Closing gripper\nMock Robot: Moving to coordinates: 160, 440, high above table\nMock Robot: Moving to coordinates: -250, 60, high above table\nMock Robot: Moving to coordinates: -250, 60, down at table level\nMock Robot: Opening gripper\nMock Robot: Moving to coordinates: -250, 60, high above table\nSequence complete.\nModel Summary: I have completed the task of picking up the blue block and placing it into the orange bowl.` What's next [Robotics with streaming](/gemini-api/docs/robotics-streaming) — real-time streaming with function calling (Gemini Robotics ER 2 only). [Video understanding](/gemini-api/docs/robotics-video-progress) — track task progress from video (ER 2 only). [Spatial reasoning](/gemini-api/docs/robotics-spatial) — pointing, tracking, and bounding box examples. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 6049, "slov": 776, "odkazu": 126, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 07:03:13", "sha256": "d98e12f1e6846f62b2df703e3e1d69f41dcd30fcd17c6f3e4f47f03cba268dd3", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://github.com/google-gemini/robotics-samples/blob/main/Getting%20Started/gemini_robotics_er.ipynb", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-overview", "titulek": "Gemini Robotics ER | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Gemini Robotics ER", "popis": "Overview of Gemini Robotics ER models and capabilities for building robotics applications.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-overview", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Gemini Robotics ER  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Overview of Gemini Robotics ER models and capabilities for building robotics applications.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-overview", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Gemini Robotics ER"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Gemini Robotics ER", "item": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-overview"}]}], "drobecky": ["Generate Content API", "Gemini Robotics ER"], "osnova": [{"uroven": 1, "text": "Gemini Robotics ER"}, {"uroven": 2, "text": "Models"}, {"uroven": 2, "text": "Robotics capabilities"}, {"uroven": 2, "text": "Getting started"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "JSON"}, {"uroven": 2, "text": "How it works"}, {"uroven": 2, "text": "Safety"}, {"uroven": 2, "text": "Best practices"}, {"uroven": 2, "text": "Limitations"}, {"uroven": 2, "text": "Privacy Notice"}, {"uroven": 2, "text": "Pricing"}, {"uroven": 2, "text": "Model endpoints"}, {"uroven": 3, "text": "Gemini Robotics ER 2 Preview"}, {"uroven": 3, "text": "Gemini Robotics ER 2 Streaming Preview"}, {"uroven": 3, "text": "Gemini Robotics ER 1.6 Preview"}, {"uroven": 2, "text": "What's next"}], "markdown": "Gemini Robotics ER Gemini Robotics ER (embodied reasoning) models are vision-language models\n(VLMs) that let robots\nperceive and interact with the physical world. They interpret visual data,\nperform spatial and temporal reasoning, plan multi-step tasks, and orchestrate\nrobots and tools. Models The Gemini Robotics ER 2 model is the latest model in Gemini Robotics.\nIt is our updated reasoning model that enable robots to\nunderstand their environments precisely. It specializes in embodied reasoning\ncapabilities, such as agentic orchestration of robots (e.g. using VLAs), robot\nvideo understanding including progress understanding and success detection,\ninstrument reading, pointing, and spatial reasoning. The Gemini Robotics ER 2 model introduces two model endpoints: **`gemini-robotics-er-2-preview`**: The standard ER 2 model. Builds on\nGemini 3.5 Flash with improved spatial reasoning, video moment finding,\nvideo progress classification, multi-robot orchestration, and multi-step\ntool use. **`gemini-robotics-er-2-streaming-preview`**: Optimized for real-time\nstreaming via the [Live API](/gemini-api/docs/robotics-streaming). Use this\nmodel for low-latency robot agents that process continuous audio and video\ninput. If you are using Gemini Robotics ER 1.6, upgrade to Gemini Robotics ER 2 by replacing\n`model=\"gemini-robotics-er-1.6-preview\"` with\n`model=\"gemini-robotics-er-2-preview\"` or\n`model=\"gemini-robotics-er-2-streaming-preview\"` in your API calls. Note that\nthe Gemini Robotics ER 1.6 model will be shut down at the\n[end of August](/gemini-api/docs/deprecations#robotics-models). [Try Gemini Robotics ER 2 in Google AI Studio](https://aistudio.google.com/prompts/new_chat?model=gemini-robotics-er-2-preview) Robotics capabilities Gemini Robotics ER supports a range of embodied reasoning capabilities.\nSelect a capability to learn more: Capability Description Guide Spatial reasoning Point to objects, track them in video, detect with bounding boxes,\n plan trajectories. [Spatial reasoning](/gemini-api/docs/generate-content/robotics-spatial) Agentic vision Use code execution to enhance other capabilities by leveraging image manipulation tools. [Agentic vision](/gemini-api/docs/generate-content/robotics-agentic) Task orchestration Combine spatial reasoning with custom robot APIs to complete\n long-horizon tasks. [Task orchestration](/gemini-api/docs/generate-content/robotics-orchestration) Streaming (Gemini Robotics ER 2 Streaming endpoint only) Bidirectional streaming for real-time robot agents with low-latency\n function calling. [Streaming for robotics](/gemini-api/docs/robotics-streaming) Video progress (Gemini Robotics ER 2 only) Moment finding and progress classification from continuous video\n feeds. [Video understanding](/gemini-api/docs/generate-content/robotics-video-progress) Getting started The following example finds objects in an image and returns their normalized 2D\ncoordinates and labels. You can pass this output directly to a robotics API or a\nVLA model to generate robot actions. Python`from google import genai from google.genai import types PROMPT = \"\"\" Point to no more than 10 items in the image. The label returned should be an identifying name for the object detected. The answer should follow the json format: [{\"point\": , \"label\": }, ...]. The points are in [y, x] format normalized to 0-1000. \"\"\" client = genai.Client() uploaded_file = client.files.upload(file=\"my-image.png\") response = client.models.generate_content( model=\"gemini-robotics-er-2-preview\", contents=[ types.Part.from_uri( file_uri=uploaded_file.uri, mime_type=uploaded_file.mime_type ), PROMPT ], config=types.GenerateContentConfig( thinking_config=types.ThinkingConfig(thinking_level=\"high\") ), ) print(response.text)` REST`# First, ensure you have the image file locally. # Encode the image to base64 IMAGE_BASE64=$(base64 -w 0 my-image.png)\n\ncurl -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/gemini-robotics-er-2-preview:generateContent\" \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [ { \"parts\": [ { \"inlineData\": { \"mimeType\": \"image/png\", \"data\": \"'\"${IMAGE_BASE64}\"'\" } }, { \"text\": \"Point to no more than 10 items in the image. The label returned should be an identifying name for the object detected. The answer should follow the json format: [{\\\"point\\\": [y, x], \\\"label\\\": }, ...]. The points are in [y, x] format normalized to 0-1000.\" } ] } ], \"generationConfig\": { \"thinkingConfig\": { \"thinkingLevel\": \"high\" } } }'` The output will be a JSON array containing objects, each with a `point`\n(normalized `[y, x]` coordinates) and a `label` identifying the object. JSON`[ {\"point\": [376, 508], \"label\": \"small banana\"}, {\"point\": [287, 609], \"label\": \"larger banana\"}, {\"point\": [223, 303], \"label\": \"pink starfruit\"}, {\"point\": [435, 172], \"label\": \"paper bag\"}, {\"point\": [270, 786], \"label\": \"green plastic bowl\"}, {\"point\": [488, 775], \"label\": \"metal measuring cup\"}, {\"point\": [673, 580], \"label\": \"dark blue bowl\"}, {\"point\": [471, 353], \"label\": \"light blue bowl\"}, {\"point\": [492, 497], \"label\": \"bread\"}, {\"point\": [525, 429], \"label\": \"lime\"} ]` The following image is an example of how these points can be displayed: How it works Gemini Robotics ER takes image, video, or audio input with natural language\nprompts. It identifies objects, reasons about scene context and spatial\nrelationships, and returns structured output like coordinates or bounding boxes. Gemini Robotics ER is also agentic: it breaks complex tasks into sub-tasks and\nexecutes them by calling your robot functions or running generated code. For\nexample, \"put the apple in the bowl\" becomes a sequence of locate, grasp, and\nplace steps. See [Function\ncalling](/gemini-api/docs/function-calling?example=meeting#how-it-works) for\ndetails on how Gemini executes tool calls. Safety While Gemini Robotics ER was built with safety in mind, it is your\nresponsibility to maintain a safe environment around the robot. Generative AI\nmodels can make mistakes, and physical robots can cause damage. To learn more,\nvisit the\n[Google DeepMind robotics safety page](https://deepmind.google/models/gemini-robotics/safety). Best practices Use plain, natural language. Describe what you want the robot to do as you\nwould to a person. If a term isn't working, try a common synonym. Optimize visual input. Crop or zoom into small or unclear objects before\nsending the image. Lighting and low color contrast can affect detection. Break complex tasks into steps. Send each step as a separate prompt to\nkeep the model focused and improve accuracy. Query multiple times and average results for high-precision tasks. This\nconsensus approach reduces variance on spatial outputs. Limitations Consider the following limitations when developing with Gemini Robotics ER: **API key restrictions:** The Gemini API does not accept requests from\nunrestricted API keys and returns a `403 Forbidden` error. Secure your API\nkey by adding restrictions in [AI Studio](https://aistudio.google.com/api-keys).\nSee [Secure unrestricted API keys](/gemini-api/docs/api-key#secure-unrestricted-keys)\nfor details. **Latency vs performance:** Complex queries, high-resolution inputs or high\nthinking levels can lead to increased processing times. For thinking level\nuse medium for a good balance between latency and performance. **Hallucinations:** Like all large language models, Gemini Robotics ER models\ncan occasionally \"hallucinate\" or provide incorrect information, especially\nfor ambiguous prompts or out-of-distribution inputs. **Dependence on prompt quality:** Output quality depends on the clarity\nof the input prompt. Use specific, well-structured prompts. **Computational cost:** Running the model, especially with video inputs or\nhigh `thinking_budget`, consumes computational resources and incurs costs.\nSee the [Thinking](/gemini-api/docs/generate-content/thinking) page for more details. **Input types:** See the following topics for details on limitations for each mode.\n [Image inputs](/gemini-api/docs/generate-content/image-understanding#technical-details-image) [Video inputs](/gemini-api/docs/generate-content/video-understanding#supported-formats) [Audio inputs](/gemini-api/docs/generate-content/audio#supported-formats) Privacy Notice You acknowledge that the models referenced in this document (the \"Robotics\nModels\") leverage video and audio data in order to operate and move your\nhardware in accordance with your instructions. You therefore may operate the\nRobotics Models such that data from identifiable persons, such as voice,\nimagery, and likeness data (\"Personal Data\"), will be collected by the Robotics\nModels. If you elect to operate the Robotics Models in a manner that collects\nPersonal Data, you agree that you will not permit any identifiable persons to\ninteract with, or be present in the area surrounding, the Robotics Models,\nunless and until such identifiable persons have been sufficiently notified of\nand consented to the fact that their Personal Data may be provided to and used\nby Google as outlined in the Gemini API Additional Terms of Service found at\n[https://ai.google.dev/gemini-api/terms](https://ai.google.dev/gemini-api/terms)\n(the \"Terms\"), including in accordance\nwith the section entitled \"How Google Uses Your Data\". You will ensure that such\nnotice permits the collection and use of Personal Data as outlined in the Terms,\nand you will use commercially reasonable efforts to minimize the collection and\ndistribution of Personal Data by using techniques such as face blurring and\noperating the Robotics Models in areas not containing identifiable persons to\nthe extent practicable. Pricing For detailed information on pricing and available regions, refer to the\n[pricing](/gemini-api/docs/pricing) page. Model endpoints Gemini Robotics ER 2 Preview Property Description id_cardModel code `gemini-robotics-er-2-preview` saveSupported data types **Inputs** Text, images, video, audio **Output** Text token_autoToken limits[[*]](/gemini-api/docs/tokens) **Input token limit** 131,072 **Output token limit** 65,536 handymanCapabilities **[Audio generation](/gemini-api/docs/speech-generation)** Not supported **[Caching](/gemini-api/docs/caching)** Supported **[Code execution](/gemini-api/docs/code-execution)** Supported **[Computer use](/gemini-api/docs/computer-use)** Supported **[File search](/gemini-api/docs/file-search)** Supported **[Function calling](/gemini-api/docs/function-calling)** Supported **[Grounding with Google Maps](/gemini-api/docs/maps-grounding)** Supported **[Image generation](/gemini-api/docs/image-generation)** Not supported **[Live API](/gemini-api/docs/live-api)** Not supported **[Search grounding](/gemini-api/docs/google-search)** Supported **[Structured outputs](/gemini-api/docs/structured-output)** Supported **[Thinking](/gemini-api/docs/thinking)** Supported **[URL context](/gemini-api/docs/url-context)** Supported speedConsumption options **[Batch API](/gemini-api/docs/batch-api)** Supported **[Flex inference](/gemini-api/docs/flex-inference)** Not supported **[Priority inference](/gemini-api/docs/priority-inference)** Not supported 123Versions Read the [model version patterns](/gemini-api/docs/models/gemini#model-versions) for more details. Preview: `gemini-robotics-er-2-preview` calendar_monthLatest update July 2026 id_cardModel card [Model card](https://deepmind.google/models/model-cards/gemini-robotics-er-2/) Gemini Robotics ER 2 Streaming Preview Property Description id_cardModel code `gemini-robotics-er-2-streaming-preview` saveSupported data types **Inputs** Text, images, video, audio **Output** Text token_autoToken limits[[*]](/gemini-api/docs/tokens) **Input token limit** 131,072 **Output token limit** 65,536 handymanCapabilities **[Audio generation](/gemini-api/docs/speech-generation)** Not supported **[Caching](/gemini-api/docs/caching)** Not supported **[Code execution](/gemini-api/docs/code-execution)** Not supported **[Computer use](/gemini-api/docs/computer-use)** Not supported **[File search](/gemini-api/docs/file-search)** Not supported **[Function calling](/gemini-api/docs/function-calling)** Supported **[Grounding with Google Maps](/gemini-api/docs/maps-grounding)** Not supported **[Image generation](/gemini-api/docs/image-generation)** Not supported **[Live API](/gemini-api/docs/live-api)** Supported **[Search grounding](/gemini-api/docs/google-search)** Supported **[Structured outputs](/gemini-api/docs/structured-output)** Not supported **[Thinking](/gemini-api/docs/thinking)** Supported **[URL context](/gemini-api/docs/url-context)** Not supported speedConsumption options **[Batch API](/gemini-api/docs/batch-api)** Not supported **[Flex inference](/gemini-api/docs/flex-inference)** Not supported **[Priority inference](/gemini-api/docs/priority-inference)** Not supported 123Versions Read the [model version patterns](/gemini-api/docs/models/gemini#model-versions) for more details. Preview: `gemini-robotics-er-2-streaming-preview` calendar_monthLatest update July 2026 id_cardModel card [Model card](https://deepmind.google/models/model-cards/gemini-robotics-er-2/) Gemini Robotics ER 1.6 Preview Property Description id_cardModel code `gemini-robotics-er-1.6-preview` saveSupported data types **Inputs** Text, images, video, audio **Output** Text token_autoToken limits[[*]](/gemini-api/docs/tokens) **Input token limit** 131,072 **Output token limit** 65,536 handymanCapabilities **[Audio generation](/gemini-api/docs/speech-generation)** Not supported **[Caching](/gemini-api/docs/caching)** Supported **[Code execution](/gemini-api/docs/code-execution)** Supported **[Computer use](/gemini-api/docs/computer-use)** Supported **[File search](/gemini-api/docs/file-search)** Supported **[Function calling](/gemini-api/docs/function-calling)** Supported **[Grounding with Google Maps](/gemini-api/docs/maps-grounding)** Supported **[Image generation](/gemini-api/docs/image-generation)** Not supported **[Live API](/gemini-api/docs/live-api)** Not supported **[Search grounding](/gemini-api/docs/google-search)** Supported **[Structured outputs](/gemini-api/docs/structured-output)** Supported **[Thinking](/gemini-api/docs/thinking)** Supported **[URL context](/gemini-api/docs/url-context)** Supported speedConsumption options **[Batch API](/gemini-api/docs/batch-api)** Supported **[Flex inference](/gemini-api/docs/flex-inference)** Not supported **[Priority inference](/gemini-api/docs/priority-inference)** Not supported 123Versions Read the [model version patterns](/gemini-api/docs/models/gemini#model-versions) for more details. Preview: `gemini-robotics-er-1.6-preview` calendar_monthLatest update December 2025 cognition_2Knowledge cutoff January 2025 What's next [Spatial reasoning](/gemini-api/docs/generate-content/robotics-spatial) — pointing, tracking, bounding boxes, trajectories. [Agentic capabilities](/gemini-api/docs/generate-content/robotics-agentic) — code execution, instrument reading, image annotation. [Task orchestration](/gemini-api/docs/generate-content/robotics-orchestration) — long-horizon tasks with custom robot APIs. [Robotics with streaming](/gemini-api/docs/robotics-streaming) — real-time bidirectional streaming (Gemini Robotics ER 2 only). [Video understanding](/gemini-api/docs/generate-content/robotics-video-progress) — moment finding and progress classification (Gemini Robotics ER 2 only). [Google DeepMind robotics safety](https://deepmind.google/models/gemini-robotics/safety) — safety research behind the model family. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-09-04 UTC.", "znaku_textu": 15766, "slov": 1966, "odkazu": 149, "kodovani": "iso-8859-2", "kodovani_deklarovane": "utf-8", "format": "html", "duplikat_z": "", "http": 200, "odkud": "live", "wb_ts": "", "stazeno": "2026-09-14 06:16:38", "sha256": "4e7a8023497e97dcd8f5a62cd7bcea835a986b5362b67c60bf98d48a94888bc7", "hloubka": 1, "zdroj_objevu": "sitemap", "ze_seznamu": false, "mime": "text/html", "odkazy_externi": ["https://aistudio.google.com/apikey", "https://github.com/google-gemini/cookbook", "https://discuss.ai.google.dev/c/gemini-api/", "https://aistudio.google.com/status", "https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash", "https://aistudio.google.com/prompts/new_chat?model=gemini-robotics-er-2-preview", "https://deepmind.google/models/gemini-robotics/safety", "https://aistudio.google.com/api-keys", "https://deepmind.google/models/model-cards/gemini-robotics-er-2/", "https://creativecommons.org/licenses/by/4.0/", "https://www.apache.org/licenses/LICENSE-2.0", "https://developers.google.com/site-policies", "https://policies.google.com/terms", "https://policies.google.com/privacy"]} {"url": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-spatial", "titulek": "Spatial reasoning | Gemini Generate Content API (Legacy) | Google AI for Developers", "h1": "Spatial reasoning", "popis": "Use Gemini Robotics ER for spatial reasoning tasks including object detection, tracking, and trajectory planning.", "klicova_slova": "", "kanonicka": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-spatial", "jazyk": "en", "robots_meta": "", "og": {"og:site_name": "Google AI for Developers", "og:type": "website", "og:title": "Spatial reasoning  |  Gemini Generate Content API (Legacy)  |  Google AI for Developers", "og:description": "Use Gemini Robotics ER for spatial reasoning tasks including object detection, tracking, and trajectory planning.", "og:url": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-spatial", "og:image": "https://ai.google.dev/static/site-assets/images/share-gemini-api-2026-07.png", "og:image:width": "1200", "og:image:height": "675", "og:locale": "en"}, "jsonld": [{"@context": "https://schema.org", "@type": "Article", "headline": "Spatial reasoning"}, {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "Generate Content API", "item": "https://ai.google.dev/gemini-api/docs/generate-content/get-started"}, {"@type": "ListItem", "position": 2, "name": "Spatial reasoning", "item": "https://ai.google.dev/gemini-api/docs/generate-content/robotics-spatial"}]}], "drobecky": ["Generate Content API", "Spatial reasoning"], "osnova": [{"uroven": 1, "text": "Spatial reasoning"}, {"uroven": 2, "text": "Point to objects"}, {"uroven": 3, "text": "Python"}, {"uroven": 3, "text": "REST"}, {"uroven": 3, "text": "JSON"}, {"uroven": 2, "text": "Tracking objects in a video"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Object detection and bounding boxes"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Trajectories"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Making room for a laptop"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "Packing a lunch"}, {"uroven": 3, "text": "Python"}, {"uroven": 2, "text": "What's next"}], "markdown": "Spatial reasoning Gemini Robotics ER models can point to objects, track them in video, detect\nthem with bounding boxes, and generate movement trajectories. All examples on\nthis page use natural language prompts with `generateContent`. For full runnable code, see the\n[Robotics cookbook](https://github.com/google-gemini/robotics-samples/blob/main/Getting%20Started/gemini_robotics_er.ipynb). Point to objects The following example finds specific objects in an image and returns their\nnormalized `[y, x]` coordinates: Python`from google import genai from google.genai import types PROMPT = \"\"\" Point to no more than 10 items in the image. The label returned should be an identifying name for the object detected. The answer should follow the json format: [{\"point\": , \"label\": }, ...]. The points are in [y, x] format normalized to 0-1000. \"\"\" client = genai.Client() # Load your image with open(\"my-image.png\", 'rb') as f: image_bytes = f.read() image_response = client.models.generate_content( model=\"gemini-robotics-er-2-preview\", contents=[ types.Part.from_bytes( data=image_bytes, mime_type='image/png', ), PROMPT ], config = types.GenerateContentConfig( thinking_config=types.ThinkingConfig(thinking_level=\"high\") ) ) print(image_response.text)` REST`# First, ensure you have the image file locally. # Encode the image to base64 IMAGE_BASE64=$(base64 -w 0 my-image.png)\n\ncurl -X POST \\ \"https://generativelanguage.googleapis.com/v1beta/models/gemini-robotics-er-2-preview:generateContent \\ -H \"x-goog-api-key: $GEMINI_API_KEY\" \\ -H \"Content-Type: application/json\" \\ -d '{ \"contents\": [ { \"parts\": [ { \"inlineData\": { \"mimeType\": \"image/png\", \"data\": \"'\"${IMAGE_BASE64}\"'\" } }, { \"text\": \"Point to no more than 10 items in the image. The label returned should be an identifying name for the object detected. The answer should follow the json format: [{\\\"point\\\": [y, x], \\\"label\\\": }, ...]. The points are in [y, x] format normalized to 0-1000.\" } ] } ], \"generationConfig\": { \"thinkingConfig\": { \"thinkingLevel\": \"high\" } } }'` The output will be a JSON array containing objects, each with a `point`\n(normalized `[y, x]` coordinates) and a `label` identifying the object. JSON`[ {\"point\": [376, 508], \"label\": \"small banana\"}, {\"point\": [287, 609], \"label\": \"larger banana\"}, {\"point\": [223, 303], \"label\": \"pink starfruit\"}, {\"point\": [435, 172], \"label\": \"paper bag\"}, {\"point\": [270, 786], \"label\": \"green plastic bowl\"}, {\"point\": [488, 775], \"label\": \"metal measuring cup\"}, {\"point\": [673, 580], \"label\": \"dark blue bowl\"}, {\"point\": [471, 353], \"label\": \"light blue bowl\"}, {\"point\": [492, 497], \"label\": \"bread\"}, {\"point\": [525, 429], \"label\": \"lime\"} ]` The following image is an example of how these points can be displayed: Tracking objects in a video Gemini Robotics ER 2 can also analyze video frames to track objects\nover time. See [Video inputs](/gemini-api/docs/video-understanding#supported-formats)\nfor a list of supported video formats. Python`from google import genai from google.genai import types client = genai.Client() # Load your video with open(\"my-video.mp4\", 'rb') as f: video_bytes = f.read() prompt = \"\"\" Point to the red ball in every frame where it appears. The answer should follow the json format: [{\"point\": [y, x], \"label\":