import { GoogleGenerativeAI } from "@google/generative-ai";const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });const result = await model.generateContent("Explain recursion simply.");console.log(result.response.text());
System instruction + chat
javascript
const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash", systemInstruction: "You are a senior DevOps engineer. Give concise, practical answers.",});const chat = model.startChat();const r1 = await chat.sendMessage("What is a Kubernetes pod?");console.log(r1.response.text());const r2 = await chat.sendMessage("How is it different from a deployment?");console.log(r2.response.text());
Streaming response
javascript
const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });const result = await model.generateContentStream( "Write a step-by-step guide to setting up CI/CD.");for await (const chunk of result.stream) { process.stdout.write(chunk.text());}
Vision — image input
javascript
import fs from "fs";const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });const imageData = fs.readFileSync("diagram.png");const base64 = imageData.toString("base64");const result = await model.generateContent([ { inlineData: { mimeType: "image/png", data: base64 } }, "Describe what's in this architecture diagram.",]);console.log(result.response.text());
const tools = [ { functionDeclarations: [ { name: "get_stock_price", description: "Get the current stock price for a ticker symbol", parameters: { type: "object", properties: { ticker: { type: "string", description: "Stock ticker symbol, e.g. GOOG", }, }, required: ["ticker"], }, }, ], },];const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash", tools,});const result = await model.generateContent("What's Google's stock price?");const response = result.response;// Check if model wants to call a functionconst call = response.candidates[0].content.parts[0].functionCall;if (call) { console.log(call.name, call.args); // get_stock_price { ticker: 'GOOG' }}
Grounding with Google Search
javascript
const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash", tools: [{ googleSearch: {} }], // enable live search grounding});const result = await model.generateContent( "What happened in AI news this week?");console.log(result.response.text());// Check grounding metadataconst groundingMeta = result.response.candidates[0].groundingMetadata;console.log(groundingMeta?.webSearchQueries); // queries usedconsole.log(groundingMeta?.groundingChunks); // sources cited
Code execution
javascript
const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash", tools: [{ codeExecution: {} }],});const result = await model.generateContent( "Calculate the first 20 Fibonacci numbers and plot them.");// Response includes code written, execution output, and optionally a chartconst parts = result.response.candidates[0].content.parts;for (const part of parts) { if (part.executableCode) console.log("Code:", part.executableCode.code); if (part.codeExecutionResult) console.log("Output:", part.codeExecutionResult.output);}
import { GoogleAIFileManager } from "@google/generative-ai/server";const fileManager = new GoogleAIFileManager(process.env.GEMINI_API_KEY);// Upload a large PDFconst uploadResult = await fileManager.uploadFile("report.pdf", { mimeType: "application/pdf", displayName: "Q4 Report",});const file = uploadResult.file;console.log(`Uploaded: ${file.uri}`);// Use the uploaded file in a promptconst model = genAI.getGenerativeModel({ model: "gemini-2.5-pro" });const result = await model.generateContent([ { fileData: { fileUri: file.uri, mimeType: "application/pdf" } }, "Summarize the key financial highlights from this report.",]);console.log(result.response.text());
Environment setup
bash
# Install SDKnpm install @google/generative-ai# Set API keyexport GEMINI_API_KEY=AIza...# Get a key: aistudio.google.com# Python SDKpip install google-generativeaipython3 -c "import google.generativeai as genaigenai.configure(api_key='YOUR_KEY')model = genai.GenerativeModel('gemini-2.0-flash')r = model.generate_content('Hello!')print(r.text)"
Gemini CLI setup
bash
# Installnpm install -g @google/gemini-cli# Authenticate (opens browser)gemini auth login# Or set API key directlyexport GEMINI_API_KEY=AIza...# Start interactive sessiongemini# One-shot with file contextgemini -p "Review this code for bugs" < src/main.ts
Frequently Asked Questions
Which Gemini model should I select for software development?
Use gemini-2.5-pro for complex refactoring, multi-file code review, and deep architectural reasoning. Use gemini-2.5-flash or gemini-2.0-flash for high-throughput tasks like inline completions, basic chat, or fast code generation.
How does Google Search grounding work with Gemini API?
By passing the googleSearch tool parameter in your API payload, Gemini executes web queries behind the scenes and embeds real-time search citations directly into the generated response.