Repository Public
1> [!NOTE]2> **Note:** This version of the page covers the **generateContent API** . You can use the toggle on this page to switch to the [Interactions API version of this page](https://ai.google.dev/gemini-api/docs/quickstart).34This 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.56This quickstart shows you how to install our7[libraries](https://ai.google.dev/gemini-api/docs/libraries) and make your first request, stream8responses, build multi-turn conversations, and use tools using the standard9`generateContent` method.1011## Before you begin1213To use the Gemini API, you need to have an API key to authenticate your requests, enforce security limits, and track usage to your account.1415Create one on AI Studio for free to get started:1617[Create a Gemini API Key](https://aistudio.google.com/apikey)1819## Install the Google GenAI SDK2021### Python2223Using [Python 3.9+](https://www.python.org/downloads/), install the24[`google-genai` package](https://pypi.org/project/google-genai/)25using the following26[pip command](https://packaging.python.org/en/latest/tutorials/installing-packages/):2728 pip install -q -U google-genai2930### JavaScript3132Using [Node.js v18+](https://nodejs.org/en/download/package-manager),33install the34[Google Gen AI SDK for TypeScript and JavaScript](https://www.npmjs.com/package/@google/genai)35using the following36[npm command](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm):3738 npm install @google/genai3940## Generate text4142Use the `models.generate_content` method to43[generate a text response](https://ai.google.dev/gemini-api/docs/text-generation).4445### Python4647 from google import genai4849 client = genai.Client()5051 response = client.models.generate_content(52 model="gemini-3.5-flash",53 contents="Explain how AI works in a few words"54 )5556 print(response.text)5758### JavaScript5960 import { GoogleGenAI } from "@google/genai";6162 const ai = new GoogleGenAI({});6364 async function main() {65 const response = await ai.models.generateContent({66 model: "gemini-3.5-flash",67 contents: "Explain how AI works in a few words",68 });6970 console.log(response.text);71 }7273 main();7475### REST7677 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \78 -H "x-goog-api-key: $GEMINI_API_KEY" \79 -H 'Content-Type: application/json' \80 -X POST \81 -d '{82 "contents": [83 {84 "parts": [85 {86 "text": "Explain how AI works in a few words"87 }88 ]89 }90 ]91 }'9293## Stream responses9495By default, the model returns a response only after the entire generation96process is complete. For a faster, more interactive experience, you can97[stream the response](https://ai.google.dev/gemini-api/docs/text-generation#stream) chunks as they98are generated.99100### Python101102 response = client.models.generate_content_stream(103 model="gemini-3.5-flash",104 contents="Explain how AI works in detail"105 )106107 for chunk in response:108 print(chunk.text, end="", flush=True)109110### JavaScript111112 async function main() {113 const responseStream = await ai.models.generateContentStream({114 model: "gemini-3.5-flash",115 contents: "Explain how AI works in detail",116 });117118 for await (const chunk of responseStream) {119 process.stdout.write(chunk.text);120 }121 }122123 main();124125### REST126127 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:streamGenerateContent" \128 -H "x-goog-api-key: $GEMINI_API_KEY" \129 -H 'Content-Type: application/json' \130 --no-buffer \131 -X POST \132 -d '{133 "contents": [134 {135 "parts": [136 {137 "text": "Explain how AI works in detail"138 }139 ]140 }141 ]142 }'143144## Multi-turn conversations145146For multi-turn conversations, the SDKs provide a stateful `chats` helper to147build a [multi-turn chat experience](https://ai.google.dev/gemini-api/docs/text-generation#chat)148that automatically manages conversation history.149150### Python151152 chat = client.chats.create(model="gemini-3.5-flash")153154 response1 = chat.send_message("I have 2 dogs in my house.")155 print("Response 1:", response1.text)156157 response2 = chat.send_message("How many paws are in my house?")158 print("Response 2:", response2.text)159160### JavaScript161162 async function main() {163 const chat = ai.chats.create({ model: "gemini-3.5-flash" });164165 let response = await chat.sendMessage({ message: "I have 2 dogs in my house." });166 console.log("Response 1:", response.text);167168 response = await chat.sendMessage({ message: "How many paws are in my house?" });169 console.log("Response 2:", response.text);170 }171172 main();173174### REST175176 # REST is stateless. You must pass the full conversation history in the request.177 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \178 -H "x-goog-api-key: $GEMINI_API_KEY" \179 -H 'Content-Type: application/json' \180 -X POST \181 -d '{182 "contents": [183 {184 "role": "user",185 "parts": [{"text": "I have 2 dogs in my house."}]186 },187 {188 "role": "model",189 "parts": [{"text": "That is nice! Two dogs mean you have plenty of company."}]190 },191 {192 "role": "user",193 "parts": [{"text": "How many paws are in my house?"}]194 }195 ]196 }'197198## Use tools199200Extend the model's capabilities by201[grounding responses with Google Search](https://ai.google.dev/gemini-api/docs/google-search)202to access real-time web content. The model automatically decides when to203search, executes queries, and synthesizes a response.204205### Python206207 from google import genai208 from google.genai import types209210 config = types.GenerateContentConfig(211 tools=[types.Tool(google_search=types.GoogleSearch())]212 )213214 response = client.models.generate_content(215 model="gemini-3.5-flash",216 contents="Who won the euro 2024?",217 config=config218 )219220 print(response.text)221222 metadata = response.candidates[0].grounding_metadata223 if metadata.web_search_queries:224 print("\nSearch queries executed:")225 for query in metadata.web_search_queries:226 print(f" - {query}")227228 if metadata.grounding_chunks:229 print("\nSources:")230 for chunk in metadata.grounding_chunks:231 print(f" - [{chunk.web.title}]({chunk.web.uri})")232233### JavaScript234235 async function main() {236 const response = await ai.models.generateContent({237 model: "gemini-3.5-flash",238 contents: "Who won the euro 2024?",239 config: {240 tools: [{ googleSearch: {} }]241 }242 });243244 console.log(response.text);245246 const metadata = response.candidates[0]?.groundingMetadata;247 if (metadata?.webSearchQueries) {248 console.log("\nSearch queries executed:");249 for (const query of metadata.webSearchQueries) {250 console.log(` - ${query}`);251 }252 }253 if (metadata?.groundingChunks) {254 console.log("\nSources:");255 for (const chunk of metadata.groundingChunks) {256 console.log(` - [${chunk.web.title}](${chunk.web.uri})`);257 }258 }259 }260261 main();262263### REST264265 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \266 -H "x-goog-api-key: $GEMINI_API_KEY" \267 -H "Content-Type: application/json" \268 -X POST \269 -d '{270 "contents": [271 {272 "parts": [273 {"text": "Who won the euro 2024?"}274 ]275 }276 ],277 "tools": [278 {279 "google_search": {}280 }281 ]282 }'283284The Gemini API also supports other built-in tools:285286- **[Code execution](https://ai.google.dev/gemini-api/docs/code-execution)**: Lets the model write and run Python code to solve complex math problems.287- **[URL context](https://ai.google.dev/gemini-api/docs/url-context)**: Lets you ground responses in specific web page URLs you provide.288- **[File search](https://ai.google.dev/gemini-api/docs/file-search)**: Lets you upload files and ground responses in their content using semantic search.289- **[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.290- **[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.291292## Call custom functions293294Use **[function calling](https://ai.google.dev/gemini-api/docs/function-calling)** to connect295models to your custom tools and APIs. The model determines when to call your296function and returns a `functionCall` in the response for your application297to execute.298299This example declares a mock temperature function and checks if the model300wants to call it.301302### Python303304 from google import genai305 from google.genai import types306307 weather_function = {308 "name": "get_current_temperature",309 "description": "Gets the current temperature for a given location.",310 "parameters": {311 "type": "object",312 "properties": {313 "location": {314 "type": "string",315 "description": "The city name, e.g. San Francisco",316 },317 },318 "required": ["location"],319 },320 }321322 tools = types.Tool(function_declarations=[weather_function])323 config = types.GenerateContentConfig(tools=[tools])324325 contents = ["What's the temperature in London?"]326327 response = client.models.generate_content(328 model="gemini-3.5-flash",329 contents=contents,330 config=config,331 )332333 part = response.candidates[0].content.parts[0]334 if part.function_call:335 fc = part.function_call336 print(f"Model requested function: {fc.name} with args {fc.args}")337338 mock_result = {"temperature": "15C", "condition": "Cloudy"}339340 contents.append(response.candidates[0].content)341342 fn_response_part = types.Part.from_function_response(343 name=fc.name,344 response=mock_result,345 id=fc.id346 )347 contents.append(types.Content(role="user", parts=[fn_response_part]))348349 final_response = client.models.generate_content(350 model="gemini-3.5-flash",351 contents=contents,352 config=config,353 )354 print("Final Response:", final_response.text)355356### JavaScript357358 import { GoogleGenAI, Type } from '@google/genai';359360 async function main() {361 const weatherFunction = {362 name: 'get_current_temperature',363 description: 'Gets the current temperature for a given location.',364 parameters: {365 type: Type.OBJECT,366 properties: {367 location: {368 type: Type.STRING,369 description: 'The city name, e.g. San Francisco',370 },371 },372 required: ['location'],373 },374 };375376 const contents = [{377 role: 'user',378 parts: [{ text: "What's the temperature in London?" }]379 }];380381 const response = await ai.models.generateContent({382 model: 'gemini-3.5-flash',383 contents: contents,384 config: {385 tools: [{ functionDeclarations: [weatherFunction] }],386 },387 });388389 if (response.functionCalls && response.functionCalls.length > 0) {390 const fc = response.functionCalls[0];391 console.log(`Model requested function: ${fc.name}`);392393 const mockResult = { temperature: "15C", condition: "Cloudy" };394395 contents.push(response.candidates[0].content);396397 contents.push({398 role: 'user',399 parts: [{400 functionResponse: {401 name: fc.name,402 response: mockResult,403 id: fc.id404 }405 }]406 });407408 const finalResponse = await ai.models.generateContent({409 model: 'gemini-3.5-flash',410 contents: contents,411 config: {412 tools: [{ functionDeclarations: [weatherFunction] }],413 },414 });415 console.log("Final Response:", finalResponse.text);416 }417 }418419 main();420421### REST422423 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \424 -H "x-goog-api-key: $GEMINI_API_KEY" \425 -H 'Content-Type: application/json' \426 -X POST \427 -d '{428 "contents": [429 {430 "role": "user",431 "parts": [{"text": "What'\''s the temperature in London?"}]432 }433 ],434 "tools": [435 {436 "functionDeclarations": [437 {438 "name": "get_current_temperature",439 "description": "Gets the current temperature for a given location.",440 "parameters": {441 "type": "object",442 "properties": {443 "location": {444 "type": "string",445 "description": "The city name, e.g. San Francisco"446 }447 },448 "required": ["location"]449 }450 }451 ]452 }453 ]454 }'455456## What's next457458Now that you've got started with the Gemini API, explore the following459guides to build more advanced applications:460461- [Text generation](https://ai.google.dev/gemini-api/docs/text-generation)462- [Image generation](https://ai.google.dev/gemini-api/docs/image-generation)463- [Image understanding](https://ai.google.dev/gemini-api/docs/image-understanding)464- [Thinking](https://ai.google.dev/gemini-api/docs/thinking)465- [Function calling](https://ai.google.dev/gemini-api/docs/function-calling)466- [Grounding with Google Search](https://ai.google.dev/gemini-api/docs/google-search)467- [Long context](https://ai.google.dev/gemini-api/docs/long-context)468- [Embeddings](https://ai.google.dev/gemini-api/docs/embeddings)