Gemini Tutorial: Learn Google AI from Scratch (2026)
Gemini is Google's most capable multimodal AI model, natively handling text, images, audio, video, and code. After building retrieval-augmented generation (RAG) pipelines and a code review assistant on Gemini, I have found its key differentiator to be the million-token context window — you can feed it entire codebases or hour-long videos in a single request.
This tutorial covers the Gemini API, multimodal capabilities, function calling, grounding with Google Search, and building production applications that leverage Gemini's unique strengths.
Getting Started with the Gemini API
The Gemini API is accessed through the google-generativeai Python package. You need an API key from Google AI Studio (free tier: 60 requests/minute, paid for production). The model is accessed as genai.GenerativeModel('gemini-2.0-pro') — the 2.0 Pro model offers the best balance of capability and cost as of 2026.
Basic usage is similar to OpenAI's API: create a model instance, call generate_content() with a prompt. Gemini supports system instructions, safety settings, and generation config (temperature, top_p, top_k, max_output_tokens).
import google.generativeai as genai
import os
genai.configure(api_key=os.environ['GEMINI_API_KEY'])
model = genai.GenerativeModel(
model_name='gemini-2.0-pro',
system_instruction='You are an expert Python developer.'
)
response = model.generate_content(
'Explain async/await in Python with a practical example.',
generation_config=genai.types.GenerationConfig(
temperature=0.2,
max_output_tokens=1024
)
)
print(response.text)
Multimodal Inputs
Gemini can process images (JPEG, PNG, WebP, HEIC), audio (MP3, WAV), video (MP4, MOV), and PDFs directly in the prompt. You upload content as parts: text parts and inline data parts. The model understands the contents holistically — it reads text in images, transcribes audio, and understands visual scenes.
For video, Gemini can process the visual track and audio track simultaneously. A 5-minute video costs about 50,000 tokens. The million-token context means you can include entire movies or codebases in a single request.
import PIL.Image
img = PIL.Image.open('diagram.png')
response = model.generate_content([
'Explain this architecture diagram and suggest improvements.',
img
])
print(response.text)
with open('meeting_recording.mp3', 'rb') as f:
audio_data = f.read()
response = model.generate_content([
'Summarize this meeting and list action items.',
{'mime_type': 'audio/mp3', 'data': audio_data}
])
Function Calling
Gemini can call external functions when it needs current data or to perform actions. You define functions as JSON schemas, and the model decides when to call them. The model returns a function call request with typed arguments, and your code executes the function and passes the result back.
This pattern powers AI agents: the model can query databases, call APIs, send emails, or control IoT devices. Function calling works in a loop — the model can chain multiple function calls to accomplish a complex task. Always validate function arguments server-side.
def get_weather(city: str) -> dict:
return {'temperature': 22, 'condition': 'sunny', 'city': city}
model = genai.GenerativeModel(
'gemini-2.0-pro',
tools=[get_weather]
)
chat = model.start_chat()
response = chat.send_message('Should I bring an umbrella to Paris tomorrow?')
print(response.text)
Grounding with Google Search
Gemini's training data has a cutoff date. For current events or any factual query where accuracy is critical, enable grounding with Google Search. The model retrieves fresh search results and incorporates them into its response, with citations. This eliminates hallucinations about recent topics.
Grounding is enabled by adding google_search_retrieval to the tool configuration. The response includes grounding citations showing which sources were used. For enterprise, Vertex AI provides Enterprise Grounding with your own data sources.
model = genai.GenerativeModel(
'gemini-2.0-pro',
tools='google_search_retrieval'
)
response = model.generate_content(
'What are the latest developments in quantum computing as of July 2026?'
)
for citation in response.candidates[0].grounding_metadata.grounding_supports:
print(f'Segment: {citation.segment.text}')
print(f'Sources: {citation.grounding_chunks}')
Streaming
For a better user experience, stream responses token by token using generate_content(..., stream=True). The response yields Generation objects with incremental text. This is essential for chat interfaces where users expect to see text appear as it is generated.
For real-time applications, Gemini's low-latency streaming supports voice conversations, live captioning, and interactive code assistants. The response chunks include safety ratings and usage metadata.
response = model.generate_content(
'Write a Python script that downloads and analyzes stock data.',
stream=True
)
for chunk in response:
print(chunk.text, end='', flush=True)
usage = response.usage_metadata
print(f'\n\nPrompt tokens: {usage.prompt_token_count}')
print(f'Response tokens: {usage.candidates_token_count}')
Safety and Production Best Practices
Every Gemini response includes safety ratings categorized by harm type (harassment, hate speech, sexually explicit, dangerous). In production, check these ratings and log violations. Set safety_settings per request to adjust thresholds.
Always use temperature=0 for deterministic outputs when accuracy matters (code generation). Use higher temperatures (0.7-1.0) for creative tasks. Implement exponential backoff for rate limits.
response = model.generate_content(
'Generate a SQL query to find top 10 customers by revenue.',
safety_settings=[
{
'category': genai.types.HarmCategory.HARM_CATEGORY_HARASSMENT,
'threshold': genai.types.HarmBlockThreshold.BLOCK_ONLY_HIGH
}
]
)
for rating in response.candidates[0].safety_ratings:
print(f'{rating.category}: {rating.probability}')
Frequently Asked Questions
How does Gemini compare to GPT-4 and Claude?
Gemini's unique advantage is the 1M+ token context window — 4x larger than GPT-4 and 2x larger than Claude. It is also natively multimodal (audio/video). Each has strengths in different benchmarks.
What is the pricing for Gemini API?
As of 2026, Gemini 2.0 Pro costs $0.10/1M input tokens and $0.40/1M output tokens. Flash (faster, cheaper) costs $0.04/1M input and $0.15/1M output. There is a free tier via Google AI Studio.
Can I fine-tune Gemini on my own data?
Yes, through Vertex AI. You can fine-tune Gemini 2.0 models using supervised fine-tuning (SFT) with your own example pairs. Useful for domain-specific tasks like legal document analysis or proprietary code generation.
How do I handle rate limits?
Implement exponential backoff with jitter. Start with a 1-second delay, double after each retry, up to 60 seconds. Use the async client for concurrent requests within quota. For production volumes, request a quota increase through Google Cloud Console.
Originally published on Ayodhyyya. Last updated June 1, 2026.