Repository Public
1This guide will help you get started using the legacy **generateContent** API.2For new projects and applications, we strongly recommend using the new3**Interactions API** instead, which is our simplest and best way to build with4Gemini models and agents.56> [!NOTE]7> **Note:** Are you using a coding agent? Install the [API Development8> Skills](https://ai.google.dev/gemini-api/docs/coding-agents#available-skills) to help your agent stay current with the latest API patterns.910This quickstart shows you how to install our11[libraries](https://ai.google.dev/gemini-api/docs/libraries) and make your first request, stream12responses, build multi-turn conversations, and use tools using the standard13`generateContent` method.1415## Get an API key1617To use the Gemini API, you need to have an API key to authenticate your requests, enforce security limits, and track usage to your account.1819- Google AI Studio automatically creates a project and API key for new users. You can copy it from the [API keys page](https://aistudio.google.com/api-keys).20- If you need a new key, click **Create API key** in AI Studio and follow the dialog to add a new key-project pair.2122[Create a Gemini API Key](https://aistudio.google.com/apikey)2324Set your key as an environment variable:2526 export GEMINI_API_KEY="YOUR_API_KEY"2728### Upgrade to the paid tier2930Upgrading to the paid tier increases your rate limits and requires setting up31Cloud Billing.3233- Click **Set up billing** on the AI Studio [API keys](https://aistudio.google.com/api-keys) or [Projects](https://aistudio.google.com/projects) pages.34- 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.35- View your API usage in [Google AI Studio](https://aistudio.google.com/usage) under **Dashboard** \> **Usage**.3637See the [Billing page](https://ai.google.dev/gemini-api/docs/billing) for more information.3839## Install the Google GenAI SDK4041### Python4243Using [Python 3.9+](https://www.python.org/downloads/), install the44[`google-genai` package](https://pypi.org/project/google-genai/)45using the following46[pip command](https://packaging.python.org/en/latest/tutorials/installing-packages/):4748 pip install -q -U google-genai4950### JavaScript5152Using [Node.js v18+](https://nodejs.org/en/download/package-manager),53install the54[Google Gen AI SDK for TypeScript and JavaScript](https://www.npmjs.com/package/@google/genai)55using the following56[npm command](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm):5758 npm install @google/genai5960## Generate text6162Use the `models.generate_content` method to63[generate a text response](https://ai.google.dev/gemini-api/docs/text-generation).6465### Python6667 from google import genai6869 client = genai.Client()7071 response = client.models.generate_content(72 model="gemini-3.8-flash",73 contents="Explain how AI works in a few words"74 )7576 print(response.text)7778### JavaScript7980 import { GoogleGenAI } from "@google/genai";8182 const ai = new GoogleGenAI({});8384 async function main() {85 const response = await ai.models.generateContent({86 model: "gemini-3.8-flash",87 contents: "Explain how AI works in a few words",88 });8990 console.log(response.text);91 }9293 main();9495### REST9697 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \98 -H "x-goog-api-key: $GEMINI_API_KEY" \99 -H 'Content-Type: application/json' \100 -X POST \101 -d '{102 "contents": [103 {104 "parts": [105 {106 "text": "Explain how AI works in a few words"107 }108 ]109 }110 ]111 }'112113## Stream responses114115By default, the model returns a response only after the entire generation116process is complete. For a faster, more interactive experience, you can117[stream the response](https://ai.google.dev/gemini-api/docs/text-generation#stream) chunks as they118are generated.119120### Python121122 response = client.models.generate_content_stream(123 model="gemini-3.8-flash",124 contents="Explain how AI works in detail"125 )126127 for chunk in response:128 print(chunk.text, end="", flush=True)129130### JavaScript131132 async function main() {133 const responseStream = await ai.models.generateContentStream({134 model: "gemini-3.8-flash",135 contents: "Explain how AI works in detail",136 });137138 for await (const chunk of responseStream) {139 process.stdout.write(chunk.text);140 }141 }142143 main();144145### REST146147 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent" \148 -H "x-goog-api-key: $GEMINI_API_KEY" \149 -H 'Content-Type: application/json' \150 --no-buffer \151 -X POST \152 -d '{153 "contents": [154 {155 "parts": [156 {157 "text": "Explain how AI works in detail"158 }159 ]160 }161 ]162 }'163164## Multi-turn conversations165166For multi-turn conversations, the SDKs provide a stateful `chats` helper to167build a [multi-turn chat experience](https://ai.google.dev/gemini-api/docs/text-generation#chat)168that automatically manages conversation history.169170### Python171172 chat = client.chats.create(model="gemini-3.8-flash")173174 response1 = chat.send_message("I have 2 dogs in my house.")175 print("Response 1:", response1.text)176177 response2 = chat.send_message("How many paws are in my house?")178 print("Response 2:", response2.text)179180### JavaScript181182 async function main() {183 const chat = ai.chats.create({ model: "gemini-3.8-flash" });184185 let response = await chat.sendMessage({ message: "I have 2 dogs in my house." });186 console.log("Response 1:", response.text);187188 response = await chat.sendMessage({ message: "How many paws are in my house?" });189 console.log("Response 2:", response.text);190 }191192 main();193194### REST195196 # REST is stateless. You must pass the full conversation history in the request.197 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \198 -H "x-goog-api-key: $GEMINI_API_KEY" \199 -H 'Content-Type: application/json' \200 -X POST \201 -d '{202 "contents": [203 {204 "role": "user",205 "parts": [{"text": "I have 2 dogs in my house."}]206 },207 {208 "role": "model",209 "parts": [{"text": "That is nice! Two dogs mean you have plenty of company."}]210 },211 {212 "role": "user",213 "parts": [{"text": "How many paws are in my house?"}]214 }215 ]216 }'217218## Use tools219220Extend the model's capabilities by221[grounding responses with Google Search](https://ai.google.dev/gemini-api/docs/google-search)222to access real-time web content. The model automatically decides when to223search, executes queries, and synthesizes a response.224225### Python226227 from google import genai228 from google.genai import types229230 config = types.GenerateContentConfig(231 tools=[types.Tool(google_search=types.GoogleSearch())]232 )233234 response = client.models.generate_content(235 model="gemini-3.8-flash",236 contents="Who won the euro 2024?",237 config=config238 )239240 print(response.text)241242 metadata = response.candidates[0].grounding_metadata243 if metadata.web_search_queries:244 print("\nSearch queries executed:")245 for query in metadata.web_search_queries:246 print(f" - {query}")247248 if metadata.grounding_chunks:249 print("\nSources:")250 for chunk in metadata.grounding_chunks:251 print(f" - [{chunk.web.title}]({chunk.web.uri})")252253### JavaScript254255 async function main() {256 const response = await ai.models.generateContent({257 model: "gemini-3.8-flash",258 contents: "Who won the euro 2024?",259 config: {260 tools: [{ googleSearch: {} }]261 }262 });263264 console.log(response.text);265266 const metadata = response.candidates[0]?.groundingMetadata;267 if (metadata?.webSearchQueries) {268 console.log("\nSearch queries executed:");269 for (const query of metadata.webSearchQueries) {270 console.log(` - ${query}`);271 }272 }273 if (metadata?.groundingChunks) {274 console.log("\nSources:");275 for (const chunk of metadata.groundingChunks) {276 console.log(` - [${chunk.web.title}](${chunk.web.uri})`);277 }278 }279 }280281 main();282283### REST284285 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \286 -H "x-goog-api-key: $GEMINI_API_KEY" \287 -H "Content-Type: application/json" \288 -X POST \289 -d '{290 "contents": [291 {292 "parts": [293 {"text": "Who won the euro 2024?"}294 ]295 }296 ],297 "tools": [298 {299 "google_search": {}300 }301 ]302 }'303304The Gemini API also supports other built-in tools:305306- **[Code execution](https://ai.google.dev/gemini-api/docs/code-execution)**: Lets the model write and run Python code to solve complex math problems.307- **[URL context](https://ai.google.dev/gemini-api/docs/url-context)**: Lets you ground responses in specific web page URLs you provide.308- **[File search](https://ai.google.dev/gemini-api/docs/file-search)**: Lets you upload files and ground responses in their content using semantic search.309- **[Google Maps](https://ai.google.dev/gemini-api/docs/maps-grounding)**: Lets you ground responses in location data and search for places, directions, and maps.310- **[Computer use](https://ai.google.dev/gemini-api/docs/computer-use)**: Lets the model interact with a virtual computer screen, keyboard, and mouse to perform tasks.311312## Call custom functions313314Use **[function calling](https://ai.google.dev/gemini-api/docs/function-calling)** to connect315models to your custom tools and APIs. The model determines when to call your316function and returns a `functionCall` in the response for your application317to execute.318319This example declares a mock temperature function and checks if the model320wants to call it.321322### Python323324 from google import genai325 from google.genai import types326327 weather_function = {328 "name": "get_current_temperature",329 "description": "Gets the current temperature for a given location.",330 "parameters": {331 "type": "object",332 "properties": {333 "location": {334 "type": "string",335 "description": "The city name, e.g. San Francisco",336 },337 },338 "required": ["location"],339 },340 }341342 tools = types.Tool(function_declarations=[weather_function])343 config = types.GenerateContentConfig(tools=[tools])344345 contents = ["What's the temperature in London?"]346347 response = client.models.generate_content(348 model="gemini-3.8-flash",349 contents=contents,350 config=config,351 )352353 part = response.candidates[0].content.parts[0]354 if part.function_call:355 fc = part.function_call356 print(f"Model requested function: {fc.name} with args {fc.args}")357358 mock_result = {"temperature": "15C", "condition": "Cloudy"}359360 contents.append(response.candidates[0].content)361362 fn_response_part = types.Part.from_function_response(363 name=fc.name,364 response=mock_result,365 id=fc.id366 )367 contents.append(types.Content(role="user", parts=[fn_response_part]))368369 final_response = client.models.generate_content(370 model="gemini-3.8-flash",371 contents=contents,372 config=config,373 )374 print("Final Response:", final_response.text)375376### JavaScript377378 import { GoogleGenAI, Type } from '@google/genai';379380 async function main() {381 const weatherFunction = {382 name: 'get_current_temperature',383 description: 'Gets the current temperature for a given location.',384 parameters: {385 type: Type.OBJECT,386 properties: {387 location: {388 type: Type.STRING,389 description: 'The city name, e.g. San Francisco',390 },391 },392 required: ['location'],393 },394 };395396 const contents = [{397 role: 'user',398 parts: [{ text: "What's the temperature in London?" }]399 }];400401 const response = await ai.models.generateContent({402 model: 'gemini-3.8-flash',403 contents: contents,404 config: {405 tools: [{ functionDeclarations: [weatherFunction] }],406 },407 });408409 if (response.functionCalls && response.functionCalls.length > 0) {410 const fc = response.functionCalls[0];411 console.log(`Model requested function: ${fc.name}`);412413 const mockResult = { temperature: "15C", condition: "Cloudy" };414415 contents.push(response.candidates[0].content);416417 contents.push({418 role: 'user',419 parts: [{420 functionResponse: {421 name: fc.name,422 response: mockResult,423 id: fc.id424 }425 }]426 });427428 const finalResponse = await ai.models.generateContent({429 model: 'gemini-3.8-flash',430 contents: contents,431 config: {432 tools: [{ functionDeclarations: [weatherFunction] }],433 },434 });435 console.log("Final Response:", finalResponse.text);436 }437 }438439 main();440441### REST442443 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \444 -H "x-goog-api-key: $GEMINI_API_KEY" \445 -H 'Content-Type: application/json' \446 -X POST \447 -d '{448 "contents": [449 {450 "role": "user",451 "parts": [{"text": "What'\''s the temperature in London?"}]452 }453 ],454 "tools": [455 {456 "functionDeclarations": [457 {458 "name": "get_current_temperature",459 "description": "Gets the current temperature for a given location.",460 "parameters": {461 "type": "object",462 "properties": {463 "location": {464 "type": "string",465 "description": "The city name, e.g. San Francisco"466 }467 },468 "required": ["location"]469 }470 }471 ]472 }473 ]474 }'475476## What's next477478Now that you've got started with the Gemini API, explore the following479guides to build more advanced applications:480481- [Text generation](https://ai.google.dev/gemini-api/docs/text-generation)482- [Image generation](https://ai.google.dev/gemini-api/docs/image-generation)483- [Image understanding](https://ai.google.dev/gemini-api/docs/image-understanding)484- [Thinking](https://ai.google.dev/gemini-api/docs/thinking)485- [Function calling](https://ai.google.dev/gemini-api/docs/function-calling)486- [Grounding with Google Search](https://ai.google.dev/gemini-api/docs/google-search)487- [Long context](https://ai.google.dev/gemini-api/docs/long-context)488- [Embeddings](https://ai.google.dev/gemini-api/docs/embeddings)