Getting started
发布时间:2026-09-11 | 浏览:1
Español – América Latina
Português – Brasil
This guide gets you started with the Gemini API using the Interactions API . You'll make your first API call in under a minute and explore text generation, multimodal understanding, image generation, structured output, tools, function calling, agents, and background execution.
The Interactions API is available through the Python and JavaScript SDKs, as well as through REST.
1. 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. You can copy it from the API keys page .
If you need a new key, click Create API key in AI Studio and follow the dialog to add a new key-project pair.
Create a Gemini API Key
Set your key as an environment variable:
Upgrade to the paid tier
Upgrading to the paid tier increases your rate limits and requires setting up Cloud Billing.
Click Set up billing on the AI Studio API keys or Projects pages.
Follow the Cloud Billing dialog to create or link a billing account, add a payment method, and prepay a minimum of $5 (or currency equivalent) in paid credits.
View your API usage in Google AI Studio under Dashboard > Usage .
See the Billing page for more information.
2. Install the SDK and make your first call
Install the SDK and generate text with a single API call.
Install the SDK:
Initialize the client and make a request:
Install the SDK:
Initialize the client and make a request:
When using REST, the API returns the full Interaction resource containing metadata, usage statistics, and the step-by-step history of the turn.
While the SDKs expose the full response, they also provide convenience properties like interaction.output_text and interaction.output_image to access final outputs directly. Learn more about the response structure in the Interactions overview or read the text generation guide for details on system instructions and generation config.
3. Stream the response
For more fluid interactions, stream the response as it's generated. Each step.delta event delivers a chunk of text you can display immediately.
When streaming, the server responds with a stream of server-sent events (SSE). Each event includes a type and JSON data.
For a detailed look at handling streaming events and delta types, see the streaming interactions guide .
4. Multi-turn conversations
The Interactions API supports multi-turn conversations with two approaches:
Stateful (recommended) : Continue a conversation on the server using previous_interaction_id . Ideal for most chat and agentic workflows where you want the server to manage history and optimize caching.
Stateless : Manage the conversation history on the client by passing all previous turns (including intermediate model thought and tool steps) in each request.
Stateless : Manage the conversation history on the client by passing all previous turns (including intermediate model thought and tool steps) in each request.
Stateful (recommended)
Chain interactions by passing previous_interaction_id . The server manages the full conversation history for you.
Set store=false and manage conversation history on the client side. You must preserve and resend all model-generated steps (including thought and function_call steps) exactly as received.
The second interaction returns a complete response object that includes only the new steps, but is grounded in the previous turn's context. Learn more about maintaining state in the multi-turn conversations guide , or explore stateless mode for client-side history management.
5. Multimodal understanding
Gemini models understand images, audio, video, and documents natively. Pass media alongside text in a single request.
Explore how to pass images, video, and audio files in the image understanding guide .
Audio understanding
Transcribe, summarize, or answer questions about audio files.
Video understanding
Analyze video content, locate events, and describe actions.
Document processing
Extract information from PDFs and other document formats.
6. Multimodal generation
Gemini can generate images natively using the Nano Banana image models.
When the model generates an image, it returns the base64-encoded image data in a step within the steps array, as well as via the output_image convenience property. Check out the image generation guide to learn about aspect ratios, image editing, and references.
Speech generation
Generate expressive, multi-speaker speech with Gemini 3.1 Flash TTS.
Music generation
Create clips and full-length songs with Lyria 3.5.
7. Use structured output
Configure the model to return JSON that matches a schema you define. Structured output works with Pydantic (Python) and Zod (JavaScript).
The output text block contains a valid JSON string conforming exactly to the requested schema. To learn how to define more complex structures and recursive schemas, see the structured output guide .
Ground the model's response in real-time information with Google Search. The API automatically searches, processes results, and returns citations.
The search steps are detailed within the interaction history, and the final output includes inline citations pointing to web sources.
You can learn how to extract search citations in the Google Search grounding guide , or see how to combine multiple tools in the tool combination guide .
Run Python code in a secure sandboxed Borg environment.
Pass public web URLs directly to ground responses in webpage content.
Index and search across uploaded documents and media files.
Ground responses in real-world geospatial and location data.
Browser automation and screen interaction.
9. Call your own functions
Function calling lets you connect the model to your code. You declare a function's name and parameters, the model decides when to call it and returns structured arguments, and you execute it locally and send the result back.
Stateful (recommended)
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:
The initial user_input step.
All model-generated steps returned in Turn 1 (including thought and function_call steps) exactly as received.
The function_result step containing the output of your executed function.
During Turn 1, the model returns a response with status requires_action and the function_call step:
After you run the function locally and submit the result (Turn 2), the final completed interaction returns:
For advanced features like parallel function calling or function choice modes, see the function calling guide .
10. Run a managed agent
Managed agents run in a remote sandbox with access to tools like code execution and file management. Pass an agent instead of a model and set environment="remote" .
You can also define and save custom agents with your own instructions, skills, and data sources.
Make your first agent call, stream responses, and build a custom agent.
Antigravity Agent
Capabilities, tools, multimodal input, and pricing for the default agent.
Agents in AI Studio
Visual playground for prototyping agents without writing code.
11. Run tasks in the background
Set background=True to run long tasks asynchronously. Poll for results with interactions.get() . For more details, see the Background execution guide .
The initial response returns immediately with status in_progress :
Once the background task is fully executed, checking the interaction state returns:
Read about running models and agents asynchronously in the background execution guide .
Background execution : Run long-running tasks asynchronously and manage state.
Text generation : System instructions, generation config, and advanced text patterns.
Image generation : Aspect ratios, image editing, and style references.
Image understanding : Classification, object detection, and visual Q&A.
Thinking : Use chain-of-thought reasoning for complex tasks.
Function calling : Parallel, compositional, and constrained function modes.
Google Search : Grounding, citations, and search suggestions.
Managed Agents : Pre-built agents with code execution and file management.
Deep Research : Autonomous multi-step research with planning and synthesis.
Structured output : JSON schemas, enums, and recursive type definitions.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-09-04 UTC.