
From “Hello World” to structured JSON, function calling, streaming, multimodal prompts, grounding, and a plug-and-play Next.js API route — all in one place.
Category: AI DevelopmentReading time: ~14–18 minutesAuthor: AlphaTechFinance
Explore Courses & eBooksSubscribe for AI Dev Tips
Contents
0) What is Google AI Studio (and when to use Vertex)?1) Create an API key2) Install the SDKs (Python & JS)3) Streaming responses4) Multi-turn chat state5) Structured output (JSON schema)6) Function calling (tools)7) Multimodal input (images + text)8) Grounding & factual answers9) Minimal Next.js API route10) Safety, params, tuning11) Pricing watch-outs12) Model picks (snapshot)FAQ
0) What is Google AI Studio (and when to use Vertex)?
AI Studio is the fastest way to prototype with Gemini models using a simple API key. You get a playground, prompt templates, and “Run settings” to tune temperature and safety. For enterprise needs (VPC, service accounts, fine-tuning at scale, observability), migrate to Vertex AI when ready.
Pro Tip: Start with AI Studio for speed. Wrap your prompts and configs behind a thin API so you can later switch to Vertex with minimal code changes.
Related reading on ATF: Retrieval-Augmented Generation (RAG) Guide • MACD Trading Guide (example of structured tutorials)
1) Create an API key
- In AI Studio → Keys, create a key.
- Store as an environment variable `GEMINI_API_KEY`.
# macOS/Linux
echo 'export GEMINI_API_KEY="YOUR_KEY"' >> ~/.bashrc && source ~/.bashrc
# Windows (PowerShell)
setx GEMINI_API_KEY "YOUR_KEY"
2) Install the SDKs (Python & JS)
pip install -U google-genai
import os
from google import genai
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
resp = client.models.generate_content(
model="gemini-2.0-pro",
contents="In one paragraph, explain what RAG is."
)
print(resp.text)
npm i google-genai
import { GoogleGenerativeAI } from "google-genai";
const genai = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
const model = genai.getGenerativeModel({ model: "gemini-2.0-pro" });
const { response } = await model.generateContent(
"Give me 3 app ideas using Gemini."
);
console.log(await response.text());
3) Streaming responses
Streaming improves perceived latency and UX. Show tokens as they arrive:
stream = client.models.generate_content_stream(
model="gemini-2.0-pro",
contents="Stream a 5-item checklist to launch an AI app."
)
for event in stream:
if event.delta is not None:
print(event.delta, end="", flush=True)
const stream = await model.generateContentStream(
"Stream 5 onboarding steps."
);
for await (const chunk of stream.stream) {
process.stdout.write(chunk.text());
}
4) Keep chat state (multi-turn memory)
history = [
{"role":"user","parts":[{"text":"You are my startup copilot."}]},
{"role":"model","parts":[{"text":"Got it. How can I help?"}]}
]
chat = client.chats.create(model="gemini-2.0-pro", history=history)
reply = chat.send_message("Draft an elevator pitch for a fintech blog.")
print(reply.text)
Mirror your Studio “Run settings” (temperature, max tokens) in code for consistent results across playground and production.
5) Structured output (JSON schema)
Generate data you can trust by enforcing a schema and JSON MIME type.
const schema = {
type: "OBJECT",
properties: {
title: { type: "STRING", description: "Short headline" },
tags: { type: "ARRAY", items: { type: "STRING" }},
steps: { type: "ARRAY", items: { type: "STRING" }}
},
required: ["title","steps"]
};
const model = genai.getGenerativeModel({
model: "gemini-2.0-pro",
generationConfig: {
responseMimeType: "application/json",
responseSchema: schema
}
});
const { response } = await model.generateContent(
"Create a tutorial outline: 'AI Marketing Agent that posts to X'."
);
const data = JSON.parse(await response.text());
console.log(data.title, data.steps.length);
Why it matters: JSON schemas make your front end simpler, safer, and faster to iterate — no brittle string parsing.
6) Function calling (connect to your tools)
Expose functions the model can call. Pass real API results back as functionResponse.
const tools = {
functionDeclarations: [{
name: "getWeather",
description: "Get temperature in Celsius for a city",
parameters: {
type: "OBJECT",
properties: { city: { type: "STRING" } },
required: ["city"]
}
}]
};
const toolModel = genai.getGenerativeModel({ model: "gemini-2.0-pro", tools });
const chat = await toolModel.startChat();
const res = await chat.sendMessage("I'm in Tokyo. Should I wear a jacket?");
const call = res.functionCalls()?.[0];
if (call?.name === "getWeather") {
// Replace with your real weather API:
const temp = 18;
const toolResult = await chat.sendMessage([{
functionResponse:{ name:"getWeather", response:{ temp } }
}]);
console.log(toolResult.response.text());
}
| Use case | Typical tool | Notes |
|---|---|---|
| Search | Web/Docs/Vector DB | Great for RAG grounding |
| Commerce | Stripe/PayPal | Let the model propose but you control execution |
| Data | Postgres/BigQuery | Use read-only roles for safety |
7) Multimodal input (images + text)
from google.genai.types import Part
img_bytes = open("screenshot.png","rb").read()
resp = client.models.generate_content(
model="gemini-2.0-pro",
contents=[
Part.from_bytes(img_bytes, mime_type="image/png"),
Part.from_text("Extract the key UI problems and suggest fixes.")
]
)
print(resp.text)
Use this to triage UI/UX issues, parse charts/tables, or generate test data from screenshots.
8) Grounding & factual answers
Enable grounding to reduce hallucinations and add citations. You can ground over your own docs (RAG), web results, Maps, or other enterprise data (on Vertex). For internal knowledge bases, pair grounding with function calling so the model can fetch and cite sources on demand.
Implementation tip: Keep your RAG layer modular. Swap providers (vector DB, search) without touching your UI.
ATF reads: RAG Starter Kit • Passkeys & Auth Hardening
9) Minimal Next.js API route (plug into any frontend)
import { NextRequest, NextResponse } from "next/server";
import { GoogleGenerativeAI } from "google-genai";
export async function POST(req: NextRequest) {
const { prompt } = await req.json();
const genai = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
const model = genai.getGenerativeModel({ model: "gemini-2.0-pro" });
const { response } = await model.generateContent(prompt);
const text = await response.text();
return NextResponse.json({ text });
}
Wire to a simple form and stream results to your UI. Add caching and auth before going public.
10) Safety, parameters, and tuning
- Run settings: Mirror Studio temperature, top-p, and safety thresholds in
generationConfigto keep dev ⇄ prod consistent. - Guardrails: Validate model arguments server-side before calling external systems.
- Observability: Log prompts, params, and outputs (redact PII). Add trace IDs to correlate UI actions with model calls.
11) Pricing watch-outs
- Prefer Flash/Flash-Lite for high-volume UX paths; reserve Pro/Reasoning for complex tasks.
- Budget by endpoint: streaming tokens, image inputs, and grounding calls each have different costs.
- Benchmark your prompts. Small wording changes can cut tokens by 20–40% with no quality loss.
12) Model picks (snapshot)
| Model | When I use it | Notes |
|---|---|---|
| gemini-2.0-pro | General reasoning & coding | Balanced quality/cost |
| gemini-2.0-flash / flash-lite | Fast UX, streaming | Lower latency and cost |
| Reasoning / “Thinking” variants | Complex planning/code | Use sparingly for tough tasks |
Start Learning: Courses & eBooksBrowse AI Tools on ATF
Next reads: Web Hosting Optimization for AI Apps • Modern FE Stack for AI Apps
FAQ
Is AI Studio enough for production?
For solo devs and small apps, yes — especially with a thin server layer. If you need SSO, private networking, SLA, or governance, move to Vertex AI.
How do I stop hallucinations?
Use grounding (RAG or web), require structured outputs, and validate arguments server-side. Add “I don’t know” acceptance in prompts.
What’s the fastest way to add Gemini to my site?
Use the Next.js route above and a simple fetch on the client. Add streaming and JSON schema before you ship.

