arrow_forwardGuides / Google AI Studio
AI dev tool 25 min read Updated April 2026

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.

Free
15 RPM, 1M tokens/day
2M
Context Window
Gemini
2.5 Flash / Pro

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 TierVery generousMinimalNone
Sign-upGoogle Account onlyGCP Project + billingCredit card
Context WindowUp to 2M tokens2M (more expensive)128K
Grounding (Web)Yes, built-inYes (extra cost)No
MultimodalText/image/video/PDF/audioYesImage only
Fine-tuningYes, freeYes (paid)Yes (paid)
lightbulb
When to choose AI Studio and when Vertex AI?

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:

1
Go to aistudio.google.com
Open your browser and navigate to the address. Click Sign in with a Google account.
2
Click "Get API Key"
In the side menu click Get API keyCreate API key → choose a Google Cloud project (or create a new one).
3
Copy the key
The API Key looks like this: AIzaSy.... Save it — it won't be shown again.
4
Save it in a .env file
Don't store the key directly in code — always use environment variables.
aistudio.google.com/apikey
API Keys
My Project API Key
AIzaSy••••••••••••••••••••••••••••••
play_circle
Google AI Studio — Gemini API Tutorial
YouTube • search for tutorials
open_in_new

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:

edit_note
Prompt Mode

A one-off request. You write a prompt, click Run, get an answer. Meant for testing prompts and producing content in a click.

forum
Chat Mode

A multi-turn conversation with history. Lets you build and test Chatbots before coding them.

code
Code Execution

Gemini runs Python code in a built-in engine. Suited to calculations, data analysis and generating charts.

aistudio.google.com/prompts/new_chat
Prompt
Explain what RAG is in 3 sentences
RAG (Retrieval Augmented Generation) is a technique that lets language models access external information in real time...
127 tokens 0.8s
Parameters
Model
gemini-2.5-flash
Temperature
Max Tokens
2048

Important parameters in the Playground

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:

# .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"))
security
Free Tier — limits worth knowing

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
aistudio.google.com — Multimodal Prompt
picture_as_pdf
annual_report_2025.pdf • 248 pages
Summarize the report in 5 key points
Results from the report:
◆ Q4 revenue rose 23% year-over-year
◆ The AI Enterprise market is growing 47% annually
◆ Launch of 3 new products in the security space

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

Customer Support Bot
"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."
Code Review Assistant
"You are a senior engineer. Review code: security, performance, readability, best practices. Give fix examples."
Data Extraction
"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
search
Grounding = the reason to choose Gemini

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

description
1. Document Analyzer

A system that takes a PDF (contract/report/research) and returns: a summary, key points, risks and insights — all in structured JSON.

File API + PDF JSON Mode System Instructions
play_circle
2. Video Summarizer

Take a YouTube URL, pull the transcript, produce a summary with timestamps, and key points in Markdown — automatically.

YouTube URI Multimodal Streaming
forum
3. Multi-turn Chatbot

A Chatbot with full conversation memory, a custom System Instruction, real-time Streaming, and saving history to a JSON file.

start_chat history stream=True
code_blocks
4. Code Reviewer

Send Python code, get a detailed analysis: bugs, security issues, improvement suggestions and fixed code — with quality scores.

System Instructions JSON Mode temperature=0.1
hub
5. RAG with Embeddings

Using Gemini Embeddings to index documents, semantic search with Cosine Similarity, and source-based answers.

embedding-004 Cosine Similarity Grounding

A quick cheat sheet

Model names (April 2026)

Model Context Free? Price (Input)
gemini-2.5-flash-preview-04-171MYes$0.075/1M
gemini-2.5-pro-preview-03-252MNo$1.25/1M
gemini-2.0-flash1MYes$0.075/1M
text-embedding-0042048Yes$0.00/1M

Common error codes

CodeMeaningSolution
429Rate LimitAdd time.sleep(60) or upgrade the plan
400Bad RequestCheck the MIME type and file format
403Wrong API KeyCheck the .env and the key itself
SAFETYSafety FilterChange the prompt or tune the Safety Settings
rocket_launch

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.