Google AI Studio
The complete guide
The easiest, free and fastest way to get started with the Gemini API — from the Playground to full Python integration, Multimodal, Grounding and Fine-tuning.
Google AI Studio vs competitors — why use it?
Google AI Studio (aistudio.google.com) is Google's free Web interface and API for direct access to the Gemini models. Unlike Vertex AI, which is meant for enterprises and requires setting up a full Google Cloud Project, AI Studio starts with one click with any Google account — no credit card.
| Platform | Google AI Studio | Vertex AI | OpenAI Playground |
|---|---|---|---|
| Free Tier | Very generous | Minimal | None |
| Sign-up | Google Account only | GCP Project + billing | Credit card |
| Context Window | Up to 2M tokens | 2M (more expensive) | 128K |
| Grounding (Web) | Yes, built-in | Yes (extra cost) | No |
| Multimodal | Text/image/video/PDF/audio | Yes | Image only |
| Fine-tuning | Yes, free | Yes (paid) | Yes (paid) |
AI Studio is perfect for development, prototyping and personal projects. Vertex AI suits enterprise Production environments with SLA, IAM, VPC and regulatory requirements. For most AI practitioners — AI Studio is the right choice.
Setup & API Key — 4 steps
To get started, do four simple steps:
Sign in with a Google account.AIzaSy.... Save it — it won't be shown again.Playground — experimenting before code
Before writing a single line of code, AI Studio offers a visual Playground that lets you try prompts, tune parameters and understand the model's behavior. Three main modes:
A one-off request. You write a prompt, click Run, get an answer. Meant for testing prompts and producing content in a click.
A multi-turn conversation with history. Lets you build and test Chatbots before coding them.
Gemini runs Python code in a built-in engine. Suited to calculations, data analysis and generating charts.
Important parameters in the Playground
- Temperature (0–2): Low = consistent and stable, high = creative and varied. For precise instructions — 0.1. For creative writing — 0.9.
- Top-K: The number of tokens considered at each step. A low value = more focused.
- Top-P (Nucleus Sampling): Cutting by cumulative probability. 0.95 = a good default.
- Max Output Tokens: Always set it to control costs and answer length.
API Keys — creation, security and .env
An API Key is your password for access to the service. If it leaks, someone can use your quota (and cost you money on paid plans). The rules:
- Never put an API Key directly in code — even if the code is "private", Git leaks.
- A .env file — store the key there, add
.envto.gitignore. - Restrict the Key — in the Google Cloud console you can restrict by IP or referrer.
- Create a separate Key per project — so it's easy to revoke access for a specific project.
# .env (not committed to Git!)
GOOGLE_API_KEY=AIzaSy...
# .gitignore
.env
*.env
import os
from dotenv import load_dotenv
import google.generativeai as genai
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
Gemini 2.5 Flash for free: 15 RPM (requests per minute), 1,500 RPD (requests per day), 1M TPM (tokens per minute). For serious projects — upgrade to Pay-as-you-go, which costs $0.075 per million input tokens.
Python SDK — the complete guide
The google-generativeai library is the most convenient way to integrate Gemini into projects. Here's everything you need:
pip install google-generativeai python-dotenv Pillow
import google.generativeai as genai
import os
from dotenv import load_dotenv
import json
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
model = genai.GenerativeModel('gemini-2.5-flash-preview-04-17')
# --- a basic request ---
response = model.generate_content("Explain what RAG is in 3 sentences")
print(response.text)
# --- a multi-turn conversation ---
chat = model.start_chat(history=[])
r1 = chat.send_message("What is your name?")
r2 = chat.send_message("Tell me about your coding capabilities")
print(r2.text)
# --- Streaming (token by token) ---
for chunk in model.generate_content("Write a poem about AI", stream=True):
print(chunk.text, end="", flush=True)
# --- JSON Mode ---
response = model.generate_content(
"Give a list of 5 AI tools with name, company and price. JSON only.",
generation_config={"response_mime_type": "application/json"}
)
data = json.loads(response.text)
print(data)
GenerationConfig — full control over the output
config = genai.GenerationConfig(
temperature=0.7, # creativity (0–2)
top_k=40, # number of tokens to consider
top_p=0.95, # nucleus sampling
max_output_tokens=2048, # limit the output
stop_sequences=["---"], # stop when it hits this string
response_mime_type="text/plain" # or "application/json"
)
response = model.generate_content(
"Write a short Python guide",
generation_config=config
)
Counting tokens before sending
# check the cost before sending
token_count = model.count_tokens("my long prompt...")
print(f"Tokens: {token_count.total_tokens}")
# tip: 1 token ≈ 0.75 English word
Multimodal — Vision, PDF, YouTube and audio
Gemini is a truly multimodal model — not just image processing as an "add-on", but deep understanding of all media types. Here are the main ways:
Images — visual analysis
import PIL.Image
import requests
from io import BytesIO
model = genai.GenerativeModel('gemini-2.5-flash-preview-04-17')
# image from a local file
image = PIL.Image.open('invoice.jpg')
response = model.generate_content([
"Analyze the invoice: extract the vendor name, date, total amount and item details",
image
])
print(response.text)
# image from a URL
r = requests.get("https://example.com/chart.png")
image_from_url = PIL.Image.open(BytesIO(r.content))
response = model.generate_content(["Describe this chart", image_from_url])
print(response.text)
PDF — document analysis
# a direct PDF (up to 2M tokens = about 1,500 pages!)
with open('annual_report.pdf', 'rb') as f:
pdf_bytes = f.read()
response = model.generate_content([
"Summarize the annual report: 5 key points + a risk analysis + opportunities",
{"mime_type": "application/pdf", "data": pdf_bytes}
])
print(response.text)
YouTube Video — video analysis
# sending a YouTube URL directly to Gemini!
response = model.generate_content([
"Write a transcript and summary of this video",
{"file_uri": "https://www.youtube.com/watch?v=VIDEO_ID", "mime_type": "video/youtube"}
])
print(response.text)
File API — large files
import time
# uploading a large file (up to 2GB!)
video_file = genai.upload_file(
path="lecture.mp4",
display_name="A lecture on LLMs",
mime_type="video/mp4"
)
# wait for processing
while video_file.state.name == "PROCESSING":
time.sleep(5)
video_file = genai.get_file(video_file.name)
response = model.generate_content([video_file, "Write a transcript with timestamps"])
print(response.text)
genai.delete_file(video_file.name) # clean up after use
System Instructions — defining the model's personality
System Instructions are directives sent before every conversation that define the model's personality, tone, language and answer limits. They save tokens on each request and ensure consistency.
model = genai.GenerativeModel(
model_name='gemini-2.5-flash-preview-04-17',
system_instruction="""
You are a professional AI guide for Automation4MI.
Rules:
- Always answer clearly and in a friendly way
- Use Python code examples when relevant
- Always state the limits of your knowledge
- Don't make up facts — if you don't know, say so
- Answer structure: explanation → example → practical tip
"""
)
# now every conversation gets these instructions
chat = model.start_chat()
r = chat.send_message("What is Fine-tuning?")
print(r.text)
System Instruction templates by use
"You are a professional support rep. Answer politely. Don't promise things you don't know. Refer to a human agent when the issue is complex."
"You are a senior engineer. Review code: security, performance, readability, best practices. Give fix examples."
"Extract structured information. Always answer in JSON only. If a field is missing — return null. Don't add extra text."
Grounding — real-time Google Search
Grounding is one of Gemini's most unique advantages — the ability to connect the model directly to Google's search engine. This lets you get up-to-date answers about events that happened after the Training Cutoff, including stock prices, news, and sports results.
from google.generativeai.types import Tool, GoogleSearchRetrieval, DynamicRetrievalConfig
# basic Grounding
model_with_search = genai.GenerativeModel(
model_name='gemini-2.5-flash-preview-04-17',
tools=[Tool(google_search=GoogleSearchRetrieval())]
)
response = model_with_search.generate_content(
"What is NVIDIA's stock price today and what is the market sentiment?"
)
print(response.text)
# checking citations
if response.candidates[0].grounding_metadata:
for chunk in response.candidates[0].grounding_metadata.grounding_chunks:
print(f"Source: {chunk.web.title} — {chunk.web.uri}")
Dynamic Retrieval — controlling when to search
# Dynamic Retrieval — Gemini searches only if score > threshold
model_smart = genai.GenerativeModel(
model_name='gemini-2.5-flash-preview-04-17',
tools=[Tool(
google_search=GoogleSearchRetrieval(
dynamic_retrieval_config=DynamicRetrievalConfig(
mode="MODE_DYNAMIC",
dynamic_threshold=0.5 # 0=always search, 1=almost never search
)
)
)]
)
# general questions → won't search (saves cost)
# news questions → searches automatically
No other model offers a free, direct connection to Google Search. It's perfect for applications that require up-to-date information: market analysis, news, research — without maintaining a separate Web Scraper.
Fine-tuning — training a custom model
Fine-tuning lets you train a customized version of Gemini Flash on your data. It's useful when you need a model that speaks in a specific style, knows business terminology, or specializes in a narrow domain.
import google.generativeai as genai
# creating a Tuned Model (requires about 100-1000 examples)
operation = genai.create_tuned_model(
display_name="automation4mi-assistant",
source_model="models/gemini-1.5-flash-001-tuning",
training_data=[
{"text_input": "What's the difference between n8n and Make?", "output": "n8n is open-source and suited to developers..."},
{"text_input": "What is RAG?", "output": "RAG (Retrieval Augmented Generation) is..."},
# ... more examples
],
epoch_count=5,
batch_size=8,
learning_rate=0.001
)
# wait for training to finish
tuned_model = operation.result()
print(f"Model ready: {tuned_model.name}")
Dataset format for Fine-tuning
# each example: input → expected output
training_examples = [
{
"text_input": "an example question",
"output": "the ideal answer in the desired format"
},
# minimum: 100 examples
# recommended: 500-1000 examples for high quality
# maximum: 40,000 examples
]
5 practical projects
A system that takes a PDF (contract/report/research) and returns: a summary, key points, risks and insights — all in structured JSON.
Take a YouTube URL, pull the transcript, produce a summary with timestamps, and key points in Markdown — automatically.
A Chatbot with full conversation memory, a custom System Instruction, real-time Streaming, and saving history to a JSON file.
Send Python code, get a detailed analysis: bugs, security issues, improvement suggestions and fixed code — with quality scores.
Using Gemini Embeddings to index documents, semantic search with Cosine Similarity, and source-based answers.
A quick cheat sheet
Model names (April 2026)
| Model | Context | Free? | Price (Input) |
|---|---|---|---|
| gemini-2.5-flash-preview-04-17 | 1M | Yes | $0.075/1M |
| gemini-2.5-pro-preview-03-25 | 2M | No | $1.25/1M |
| gemini-2.0-flash | 1M | Yes | $0.075/1M |
| text-embedding-004 | 2048 | Yes | $0.00/1M |
Common error codes
| Code | Meaning | Solution |
|---|---|---|
| 429 | Rate Limit | Add time.sleep(60) or upgrade the plan |
| 400 | Bad Request | Check the MIME type and file format |
| 403 | Wrong API Key | Check the .env and the key itself |
| SAFETY | Safety Filter | Change the prompt or tune the Safety Settings |
The next steps
Continuing? Connect Pinecone to Gemini for a full RAG, try NotebookLM for document analysis, or the learning tracks to build complete AI applications.