> ## AI Agent Context > Get the complete documentation index at: https://aistudio.google.com/llms.txt > Use this file to discover all available pages. > For the full documentation in a single file, fetch: https://aistudio.google.com/llms-full.txt # Getting started This guide will help you get started using the legacy **generateContent** API. For new projects and applications, we strongly recommend using the new **Interactions API** instead, which provides a simplified interface for agentic workflows and the latest models. This quickstart shows you how to install our [libraries](/docs/libraries) and make your first request, stream responses, build multi-turn conversations, and use tools using the standard `generateContent` method. ## Choose the right Gemini tool {% id="choose-tool" %} Use the [Google GenAI SDKs](/docs/libraries) and [coding agent setup](/docs/coding-agents) when you are **building** Gemini into an application. Use the [Gemini API CLI](/docs/cli) (`gemini-api`) when an agent or script needs to **call** Gemini directly from the shell without adding SDK code to your project: | Tool | What it does | When to use it | | :--- | :--- | :--- | | **[Google GenAI SDKs](/docs/libraries)** | Imports Gemini client libraries into Python, TypeScript, JavaScript, Go, Java, or C# code. | You are building Gemini features into your application, backend service, or real-time [Live API](/docs/live-api) session. | | **[Gemini Docs MCP & skills](/docs/coding-agents)** | Gives coding agents live documentation search and current SDK rules. | Your coding agent is writing application code that imports a Google GenAI SDK. | | **[Gemini API CLI](/docs/cli)** (`gemini-api`) | Calls Gemini models and managed agents from any shell. | Your coding agent, shell script, or CI job needs to generate media, analyze files, or run a background research agent with zero project dependencies. | {% callout type="note" %} `gemini-api` is a stateless API client, not an interactive coding agent like `@google/gemini-cli`. You can run `gemini-api` inside any coding agent. {% /callout %} ## Get an API key {% id="get-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. * Additional projects and projects imported from Google Cloud may need [project verification](/docs/verification) before they can use the free tier. {% button href="https://aistudio.google.com/apikey" variant="primary" %} Get Gemini API key {% /button %} Set your key as an environment variable: ```bash export GEMINI_API_KEY="YOUR_API_KEY" ``` ### Upgrade to the paid tier {% id="upgrade-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](https://aistudio.google.com/api-keys) or [Projects](https://aistudio.google.com/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](https://aistudio.google.com/usage) under **Dashboard** > **Usage**. See the [Billing page](/docs/billing) for more information. ## Install the Google GenAI SDK {% id="install-gemini-library" %} {% tabs %} {% tab label="Python" %} Using [Python 3.9+](https://www.python.org/downloads/), install the [`google-genai` package](https://pypi.org/project/google-genai/) using the following [pip command](https://packaging.python.org/en/latest/tutorials/installing-packages/): ```shell pip install -q -U google-genai ``` {% /tab %} {% tab label="JavaScript" %} Using [Node.js v18+](https://nodejs.org/en/download/package-manager), install the [Google Gen AI SDK for TypeScript and JavaScript](https://www.npmjs.com/package/@google/genai) using the following [npm command](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm): ```shell npm install @google/genai ``` {% /tab %} {% /tabs %} ## Generate text {% id="generate-text" %} Use the `models.generate_content` method to [generate a text response](/docs/text-generation). {% tabs %} {% tab label="Python" %} ```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) ``` {% /tab %} {% tab label="JavaScript" %} ```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(); ``` {% /tab %} {% tab label="REST" %} ```shell 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" } ] } ] }' ``` {% /tab %} {% /tabs %} ## Stream responses {% id="stream-responses" %} By default, the model returns a response only after the entire generation process is complete. For a faster, more interactive experience, you can [stream the response](/docs/text-generation?generate-content=true#streaming-responses) chunks as they are generated. {% tabs %} {% tab label="Python" %} ```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) ``` {% /tab %} {% tab label="JavaScript" %} ```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); } } await main(); ``` {% /tab %} {% tab label="REST" %} ```shell 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" } ] } ] }' ``` {% /tab %} {% /tabs %} ## Multi-turn conversations {% id="multi-turn" %} For multi-turn conversations, the SDKs provide a stateful `chats` helper to build a [multi-turn chat experience](/docs/text-generation?generate-content=true#multi-turn-conversations) that automatically manages conversation history. {% tabs %} {% tab label="Python" %} ```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) ``` {% /tab %} {% tab label="JavaScript" %} ```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); } await main(); ``` {% /tab %} {% tab label="REST" %} ```shell # REST is stateless. You must pass the full conversation history in the request. 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": "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?"}] } ] }' ``` {% /tab %} {% /tabs %} ## Use tools {% id="use-tools" %} Extend the model's capabilities by [grounding responses with Google Search](/docs/google-search) to access real-time web content. The model automatically decides when to search, executes queries, and synthesizes a response. {% tabs %} {% tab label="Python" %} ```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})") ``` {% /tab %} {% tab label="JavaScript" %} ```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(); ``` {% /tab %} {% tab label="REST" %} ```shell 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": {} } ] }' ``` {% /tab %} {% /tabs %} The Gemini API also supports other built-in tools: * **[Code execution](/docs/code-execution)**: Lets the model write and run Python code to solve complex math problems. * **[URL context](/docs/url-context)**: Lets you ground responses in specific web page URLs you provide. * **[File search](/docs/file-search)**: Lets you upload files and ground responses in their content using semantic search. * **[Google Maps](/docs/maps-grounding)**: Lets you ground responses in location data and search for places, directions, and maps. * **[Computer use](/docs/computer-use)**: Lets the model interact with a virtual computer screen, keyboard, and mouse to perform tasks. ## Call custom functions {% id="function-calling" %} Use **[function calling](/docs/function-calling)** to connect models to your custom tools and APIs. The model determines when to call your function and returns a `functionCall` in the response for your application to execute. This example declares a mock temperature function and checks if the model wants to call it. {% tabs %} {% tab label="Python" %} ```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) ``` {% /tab %} {% tab label="JavaScript" %} ```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(); ``` {% /tab %} {% tab label="REST" %} ```shell 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"] } } ] } ] }' ``` {% /tab %} {% /tabs %} ## What's next {% id="what's-next" %} Now that you've got started with the Gemini API, explore the following guides to build more advanced applications: * [Text generation](/docs/text-generation) * [Image generation](/docs/image-generation) * [Image understanding](/docs/image-understanding) * [Thinking](/docs/thinking) * [Function calling](/docs/function-calling) * [Grounding with Google Search](/docs/google-search) * [Long context](/docs/long-context) * [Embeddings](/docs/embeddings)