
Gemini Prompting
- 32 installs
- 10 repo stars
- Updated July 24, 2026
- duyet/claude-plugins
Prompt-engineering guidance for Google's Gemini models - structuring prompts and patterns to get reliable output from Gemini.
About
A prompt-engineering skill focused on Google's Gemini models - how to structure prompts and apply model-specific patterns that produce reliable output from Gemini. It sits alongside sibling guides for Claude and Grok in this plugin collection. A solo builder reaches for it when integrating Gemini into an app or agent and wants Gemini-specific prompting technique rather than generic advice.
- Gemini-specific prompt structuring
- Patterns for reliable Gemini output
- Part of a per-model prompting set
Gemini Prompting by the numbers
- 32 all-time installs (skills.sh)
- Ranked #9,069 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/duyet/claude-plugins --skill gemini-promptingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 32 |
|---|---|
| repo stars | ★ 10 |
| Last updated | July 24, 2026 |
| Repository | duyet/claude-plugins ↗ |
What it does
Prompt-engineering guidance for Google's Gemini models - structuring prompts and patterns to get reliable output from Gemini.
Who is it for?
Getting reliable output from Gemini
Skip if: Non-Gemini models
Files
Gemini Prompt Engineering
Gemini is Google's multimodal AI model designed from the ground up for text, images, audio, video, and code. It features system instructions, ultra-long context windows (up to 1M+ tokens), and native multimodal understanding.
When to Invoke This Skill
Use this skill when:
- Crafting prompts specifically for Gemini/Google models
- Using system instructions to guide behavior
- Working with multimodal inputs (text, images, video, audio)
- Leveraging ultra-long context (1M+ tokens)
- Building with Gemini's agent reasoning capabilities
Gemini's Identity & Characteristics
| Attribute | Description |
|---|---|
| Architecture | Multimodal-first (text, images, audio, video, code) |
| Context Window | Up to 1M+ tokens (industry-leading) |
| System Instructions | Primary feature for behavior control |
| Strengths | Multimodal reasoning, long-context, code generation |
| Prompt Style | Flexible with system instruction preference |
| Models | Gemini 3 Flash (fast), Gemini 3 Pro (capable), Gemini 2.5 Flash/Pro (legacy) |
Universal Prompting Techniques (Gemini-Adapted)
1. Zero-Shot Prompting with System Instructions
Gemini's system instructions are powerful for zero-shot tasks.
{
"system_instruction": {
"parts": [{"text": "You are a technical writing assistant. Your responses are clear, concise, and use Markdown formatting."}]
},
"contents": [{"parts": [{"text": "Explain how JWT authentication works."}]}]
}2. Few-Shot Prompting
<system_instruction>
You are a sentiment classifier. Categorize text as positive, negative, or neutral.
</system_instruction>
<examples>
<example>
<input>
I absolutely love this product! Best purchase I've made all year.
</input>
<output>
{"sentiment": "positive", "confidence": 0.95}
</output>
</example>
<example>
<input>
This is the worst customer service I've ever experienced.
</input>
<output>
{"sentiment": "negative", "confidence": 0.92}
</output>
</example>
</examples>
<input>
The product is okay, does what it's supposed to do.
</input>
<output>3. Chain-of-Thought Prompting
<system_instruction>
You are a strong reasoner. Always think through problems step by step before answering.
</system_instruction>
The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.
Let's think about this systematically:4. Zero-Shot CoT
Simply add reasoning instructions:
<system_instruction>
Before answering, always think through the problem step by step.
</system_instruction>
What's the capital of the country that has the largest population in South America?
Let's work through this step by step.5. Prompt Chaining
Gemini's long context enables extensive chaining:
Chain 1:
<system_instruction>
You are a research assistant.
</system_instruction>
Extract all research papers related to "transformer architecture" from this document.
<document>
[paste large document]
</document>Chain 2:
Summarize the key findings from the extracted papers and identify common themes.
<extracted_papers>
[from previous response]
</extracted_papers>6. ReAct Prompting
<system_instruction>
You are a reasoning agent. Before taking any action, analyze logical dependencies, constraints, and risks. Think through the problem methodically.
</system_instruction>
<question>
[research question]
</question>
<thought_1>
[analysis and plan]
</thought_1>
<action_1>
[tool use or information gathering]
</action_1>
<observation_1>
[result]
</observation_1>
<thought_2>
[next steps based on observation]
</thought_2>
<final_answer>
[conclusion]
</final_answer>7. Tree of Thoughts
<system_instruction>
You are an expert planner. Explore multiple solution paths before recommending an approach.
</system_instruction>
<problem>
[complex problem]
</problem>
<thought_paths>
<path_1>
<approach>[strategy 1]</approach>
<reasoning>[step-by-step]</reasoning>
<expected_outcome>[result]</expected_outcome>
</path_1>
<path_2>
[...]
</path_2>
<path_3>
[...]
</path_3>
</thought_paths>
<recommendation>
[best approach with justification]
</recommendation>Gemini-Specific Best Practices
1. Use System Instructions
System instructions are Gemini's primary behavior control mechanism:
{
"system_instruction": {
"parts": [{
"text": "You are a specialized assistant for data science. You are precise, analytical, and always provide code examples in Python."
}]
}
}2. Comprehensive System Instruction Template
From official Gemini documentation:
<role>
You are Gemini, a specialized assistant for [Domain].
You are precise, analytical, and persistent.
</role>
<instructions>
1. **Plan**: Analyze the task and create a step-by-step plan.
2. **Execute**: Carry out the plan.
3. **Validate**: Review your output against the user's task.
4. **Format**: Present the final answer in the requested structure.
</instructions>
<constraints>
- Verbosity: [Low/Medium/High]
- Tone: [Formal/Casual/Technical]
</constraints>
<output_format>
Structure your response as follows:
1. **Executive Summary**: [Short overview]
2. **Detailed Response**: [The main content]
</output_format>3. Leverage Multimodal Inputs
Gemini natively processes multiple modalities:
{
"contents": [{
"parts": [
{"text": "Describe what's in this image and suggest a caption for social media."},
{
"inline_data": {
"mime_type": "image/jpeg",
"data": "[base64_encoded_image]"
}
}
]
}]
}4. Ultra-Long Context Utilization
Gemini's 1M+ token context enables massive document analysis:
<system_instruction>
You are a document analysis specialist.
</system_instruction>
<documents>
[Hundreds of pages of content - up to 1M tokens]
</documents>
<task>
Synthesize key themes across all documents and identify contradictions.
</task>5. Code-Specific Prompting
Gemini excels at code generation and analysis:
<system_instruction>
You are a senior software engineer. You provide clean, well-documented code with error handling.
</system_instruction>
Write a Python function that:
1. Validates email addresses using regex
2. Returns (is_valid, error_message) tuple
3. Includes comprehensive docstring
4. Handles edge cases
Language: PythonAdvanced Features
Function Calling
Gemini supports native function/tool calling for building agents:
from google import genai
from google.genai import types
client = genai.Client()
get_weather = types.FunctionDeclaration(
name="get_weather",
description="Get current weather for a location",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"location": types.Schema(
type=types.Type.STRING,
description="City name, e.g. San Francisco"
),
"unit": types.Schema(
type=types.Type.STRING,
description="Temperature unit (celsius or fahrenheit)",
enum=["celsius", "fahrenheit"]
)
},
required=["location"]
)
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What's the weather in Tokyo and Paris?",
config=types.GenerateContentConfig(
tools=[get_weather]
)
)Thinking Configuration
Control Gemini's reasoning process with configurable thinking budget:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Solve this step-by-step: [complex problem]",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_budget=8192 # tokens for reasoning
)
)
)Structured Outputs with JSON Schema
Get validated JSON output with schema enforcement:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Extract user profile information from this text: [text]",
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=types.Schema(
type=types.Type.OBJECT,
properties={
"name": types.Schema(type=types.Type.STRING),
"email": types.Schema(type=types.Type.STRING),
"age": types.Schema(type=types.Type.INTEGER),
"interests": types.Schema(
type=types.Type.ARRAY,
items=types.Schema(type=types.Type.STRING)
)
},
required=["name", "email"]
)
)
)Anti-Patterns to Avoid
| Anti-Pattern | Why It Fails | Better Approach |
|---|---|---|
| Ignoring system instructions | Wastes Gemini's key feature | Always set system_instruction |
| Not using multimodal | Underutilizes Gemini's strength | Combine text, images, audio |
| Small context thinking | Wastes 1M+ capability | Process large documents |
| Inconsistent formats | Confuses multimodal processing | Specify output format clearly |
| Single-shot for complex tasks | Misses reasoning depth | Use multi-turn conversations |
| Not using structured outputs | Manual parsing needed | Use JSON schema validation |
| Disabling thinking when needed | Misses reasoning insights | Enable thinking_budget for complex tasks |
Quick Reference Templates
Basic System Instruction
{
"system_instruction": {
"parts": [{"text": "[Your system instruction here]"}]
},
"contents": [{"parts": [{"text": "[Your prompt]"}]}]
}Multimodal Input
<system_instruction>
You are a visual analysis assistant.
</system_instruction>
Analyze this image and describe:
1. Main subject
2. Mood/atmosphere
3. Suggested use cases
[image]Long-Context Analysis
<system_instruction>
You are a research analyst specializing in synthesis and pattern recognition.
</system_instruction>
<large_context>
[up to 1M tokens of content]
</large_context>
<task>
[analysis task]
</task>
<output_format>
[structure]
</output_format>Model Capabilities Reference
| Feature | Gemini 3 Flash | Gemini 3 Pro | Gemini 2.5 Flash | Gemini 2.5 Pro |
|---|---|---|---|---|
| Context Window | 1M tokens | 1M tokens | 1M tokens | 1M tokens |
| System Instructions | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
| Multimodal | ✅ Native | ✅ Native | ✅ Native | ✅ Native |
| Code | ✅ Excellent | ✅ Excellent | ✅ Excellent | ✅ Excellent |
| Reasoning | ✅ Strong | ✅ Excellent | ✅ Strong | ✅ Excellent |
| Speed | Very Fast | Fast | Very Fast | Fast |
| Function Calling | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
| Thinking Config | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
| Status | Latest (2025) | Latest (2025) | Mature | Mature |
Note: Model names follow gemini-{version}-{variant} pattern. Use gemini-3-flash-preview for the latest features.
System Instruction Patterns
Role Definition
You are a [role] specializing in [domain].
You are [attribute 1], [attribute 2], and [attribute 3].Task Instructions
When given a task:
1. **Analyze**: Break down requirements
2. **Plan**: Create step-by-step approach
3. **Execute**: Complete the task
4. **Review**: Verify against requirementsOutput Formatting
Always structure your responses as:
- **Summary**: Brief overview
- **Details**: Main content
- **Examples**: Concrete illustrations (if applicable)
- **Caveats**: Limitations or considerationsBehavioral Constraints
- Always cite sources when making factual claims
- Indicate confidence levels for uncertain information
- Offer alternative viewpoints on subjective topics
- Flag potential ethical concernsSee Also
references/basics.md- Foundational Gemini prompting conceptsreferences/techniques.md- Detailed technique explanationsreferences/system-instructions.md- System instruction patternsreferences/multimodal.md- Multimodal prompting guidereferences/patterns.md- Reusable Gemini prompt patternsreferences/examples.md- Concrete examples and templatesgrok-promptingskill - For Grok/xAI-specific guidanceclaude-promptingskill - For Anthropic Claude-specific guidance
Gemini Prompt Engineering - Basics
What is Prompt Engineering for Gemini?
Prompt engineering for Gemini is the practice of crafting effective instructions to elicit optimal responses from Google's multimodal AI models. Gemini's unique architecture—multimodal-first design, ultra-long context, and system instructions—requires specific prompting strategies.
Why Gemini-Specific Prompting?
While universal prompting techniques apply to all LLMs, Gemini has unique characteristics:
1. Multimodal Native: Built for text, images, audio, video from the ground up 2. Ultra-Long Context: Up to 1M+ token context window 3. System Instructions: Primary mechanism for behavior control 4. Two Model Tiers: Flash (fast) and Pro (capable)
Core Principles for Gemini
1. Use System Instructions
System instructions are Gemini's key feature:
{
"system_instruction": {
"parts": [{"text": "You are a specialized data science assistant."}]
}
}2. Leverage Multimodal Capabilities
Combine different input types:
Analyze this image and write a blog post about it.
[image]3. Utilize Long Context
Process massive documents:
Analyze trends across this entire dataset.
[large dataset - up to 1M tokens]4. Specify Output Format
Always tell Gemini the expected format:
<output_format>
JSON with keys: "analysis", "confidence", "recommendations"
</output_format>Gemini Model Family
| Model | Best For | Speed | Context |
|---|---|---|---|
| Gemini 2.5 Flash | Speed, cost-efficiency | Very Fast | 1M tokens |
| Gemini 2.5 Pro | Complex reasoning, nuanced tasks | Fast | 1M tokens |
System Instruction vs. User Message
System Instruction:
- Sets behavior, role, and constraints
- Applies to all messages in conversation
- Not counted in user-visible message limits
- Best for: role definition, behavioral guidelines
User Message:
- The actual task or query
- Visible in conversation history
- Best for: specific requests, data input
Example:
{
"system_instruction": {
"parts": [{"text": "You are a code reviewer. Focus on correctness, performance, and maintainability."}]
},
"contents": [{
"parts": [{"text": "Review this Python function:\n\n[code]"}]
}]
}When to Use Gemini
| Scenario | Why Gemini? |
|---|---|
| Image/video analysis | Native multimodal understanding |
| Very long documents | 1M+ token context |
| Code generation | Excellent across all languages |
| Multilingual tasks | Strong language support |
| Multimodal RAG | Can process text + images together |
| Reasoning tasks | Pro model has strong reasoning |
Common Use Cases
1. Multimodal Analysis
Describe this image and suggest improvements.
[image]2. Code Generation
Write a function to validate email addresses in Python.
Include error handling and docstring.3. Document Synthesis
<system_instruction>
You are a research analyst.
</system_instruction>
Synthesize key findings from these 50 research papers.
[all papers - large context]4. Video Analysis
Summarize the key topics discussed in this video.
[video file]API Structure
Basic Request (New SDK)
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain quantum computing in simple terms."
)
print(response.text)Basic Request (Legacy SDK)
import google.generativeai as genai
model = genai.GenerativeModel("gemini-2.5-flash")
response = model.generate_content(
"Explain quantum computing in simple terms."
)
print(response.text)With System Instruction (Legacy SDK)
import google.generativeai as genai
model = genai.GenerativeModel(
"gemini-2.5-flash",
system_instruction="You are a physics tutor specializing in making complex topics accessible."
)
response = model.generate_content("Explain quantum entanglement.")With System Instruction (New SDK)
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain quantum entanglement.",
config=types.GenerateContentConfig(
system_instruction="You are a physics tutor specializing in making complex topics accessible."
)
)Multimodal Input (Legacy SDK)
import PIL.Image
import google.generativeai as genai
model = genai.GenerativeModel("gemini-2.5-pro")
image = PIL.Image.open("photo.jpg")
response = model.generate_content([
"Describe this image in detail.",
image
])Multimodal Input (New SDK)
from google import genai
import PIL.Image
client = genai.Client()
image = PIL.Image.open("photo.jpg")
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[
"Describe this image in detail.",
image
]
)Getting Started Checklist
- [ ] Choose appropriate Gemini model (Flash vs Pro)
- [ ] Set system instruction for behavior
- [ ] Structure prompt with clear task
- [ ] Specify output format
- [ ] Consider multimodal inputs
- [ ] Leverage long context if needed
- [ ] Test and iterate
Key Differences from Other Models
| Aspect | Gemini | Claude | Grok |
|---|---|---|---|
| Architecture | Multimodal-first | Text-first | Text-first |
| Context | 1M+ tokens | 200K tokens | ~128K tokens |
| Key Feature | System instructions | XML tags | Conversational |
| Strength | Multimodal | Long-context analysis | Real-time knowledge |
| Best For | Multimodal tasks | Document analysis | Current events |
Gemini Prompt Examples
Real-world examples demonstrating effective Gemini prompting.
---
Example 1: System Instruction with Reasoning
From Official Gemini Documentation
{
"system_instruction": {
"parts": [{
"text": "You are a very strong reasoner and planner. Use these critical instructions to structure your plans, thoughts, and responses.\n\nBefore taking any action, you must proactively, methodically, and independently plan and reason about:\n\n1) Logical dependencies and constraints\n2) Risk assessment\n3) Abductive reasoning and hypothesis exploration\n4) Outcome evaluation and adaptability\n5) Information availability\n6) Precision and Grounding\n7) Completeness\n8) Persistence and patience\n9) Inhibit your response: only act after completing above reasoning"
}]
},
"contents": [{
"parts": [{
"text": "I need to plan a migration from a monolithic architecture to microservices. What should I consider?"
}]
}]
}Why It Works:
- Comprehensive reasoning framework
- Systematic approach to complex planning
- Prevents premature conclusions
- Ensures thoroughness
---
Example 2: Multimodal Analysis (Legacy SDK)
import google.generativeai as genai
import PIL.Image
model = genai.GenerativeModel("gemini-2.5-pro")
image = PIL.Image.open("product.jpg")
response = model.generate_content([
"""Analyze this product image and create:
1. **Product Name**: Creative, memorable name
2. **Tagline**: Catchy one-line description
3. **Features**: 5 key features based on what you see
4. **Target Audience**: Who would buy thisExample 2: Multimodal Analysis (New SDK)
from google import genai
import PIL.Image
client = genai.Client()
image = PIL.Image.open("product.jpg")
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[
"""Analyze this product image and create:
1. **Product Name**: Creative, memorable name
2. **Tagline**: Catchy one-line description
3. **Features**: 5 key features based on what you see
4. **Target Audience**: Who would buy this
5. **Price Suggestion**: Reasonable price point
6. **Marketing Copy**: 2-paragraph product description
Format as Markdown with proper headers.""",
image
])---
Example 3: Long-Context Document Analysis
{
"system_instruction": {
"parts": [{
"text": "You are a legal analyst specializing in contract review and risk identification."
}]
},
"contents": [{
"parts": [{
"text": "Review this services agreement and identify:\n\n1. **Unusual Terms**: Anything non-standard\n2. **Risks**: Potential issues for our company\n3. **Missing Protections**: What should be added\n4. **Negotiation Points**: What to push back on\n5. **Overall Assessment**: Favorable or unfavorable\n\n<contract>\n[Full contract - can be hundreds of pages]\n</contract>\n\nOur company is a [company description] and this is for [purpose]."
}]
}]
}---
Example 4: Code Generation with System Instruction
model = genai.GenerativeModel(
"gemini-2.5-flash",
system_instruction="""You are a senior Python engineer specializing in:
- Clean, PEP 8 compliant code
- Comprehensive error handling
- Type hints (Python 3.10+)
- Docstrings (Google style)
- Unit test examples
You never write code without proper validation and error handling."""
)
response = model.generate_content("""
Write a Python function that validates and processes credit card information.
Requirements:
- Validate card number using Luhn algorithm
- Identify card type (Visa, Mastercard, Amex)
- Validate expiration date
- Validate CVV length based on card type
- Return (valid: bool, card_type: str, errors: list[str])
Include usage examples and unit tests.
""")---
Example 5: Video Analysis
import google.generativeai as genai
model = genai.GenerativeModel("gemini-2.5-pro")
video = genai.upload_file("tutorial.mp4")
response = model.generate_content([
"""Analyze this tutorial video and extract:
1. **Topic**: What is being taught
2. **Key Steps**: Chronological list of steps shown
3. **Tools/Technologies**: What software or tools are used
4. **Difficulty Level**: Beginner/Intermediate/Advanced
5. **Prerequisites**: What viewers need to know beforehand
6. **Timestamps**: Key moments with timestamps
7. **Summary**: 2-3 sentence overview
Format as structured Markdown.""",
video
])---
Example 6: Comparative Analysis
<system_instruction>
You are a technology analyst specializing in cloud infrastructure and cost optimization.
</system_instruction>
Compare AWS Lambda, Google Cloud Functions, and Azure Functions for this use case:
<use_case>
We need to process user-uploaded images:
- Resize to multiple formats
- Apply watermarks
- Store in CDN
- Average 10,000 images/day
- Burst capacity up to 100,000/day
- Cost-sensitive startup
</use_case>
<comparison_criteria>
- Pricing (cold starts, execution time, requests)
- Performance (cold start time, max execution time)
- Ecosystem (integrations, monitoring)
- Scalability (concurrent execution limits)
- Ease of deployment
</comparison_criteria>
<output_format>
## Comparison Table
| Feature | AWS Lambda | Cloud Functions | Azure Functions |
|---------|------------|-----------------|----------------|
| [rows for each criterion] |
## Analysis
### For Our Use Case
**Recommendation**: [which service and why]
**Cost Estimate**: [monthly cost estimate]
**Implementation Notes**: [specific considerations]
**Risks**: [potential issues]---
Example 7: Research Synthesis with Long Context
{
"system_instruction": {
"parts": [{
"text": "You are a research scientist conducting a literature review on AI safety."
}]
},
"contents": [{
"parts": [{
"text": "Synthesize these 50 research papers on AI alignment and safety.\n\n<documents>\n[Papers 1-50 - full text using 1M context]\n</documents>\n\nProvide:\n\n1. **Key Themes**: What are the main research areas?\n2. **Consensus**: What do most researchers agree on?\n3. **Debates**: What are the major disagreements?\n4. **Methodologies**: What approaches are being used?\n5. **Gaps**: What hasn't been studied?\n6. **Future Directions**: Where is the field heading?\n\nCite specific papers when making claims."
}]
}]
}---
Example 8: Educational Content Creation
<system_instruction>
You are an expert educator who creates engaging learning materials for programming students.
</system_instruction>
Create an interactive tutorial explaining async/await in JavaScript.
<requirements>
- Target audience: Intermediate JS developers
- Include: concepts, examples, exercises
- Use analogies for complex concepts
- Build from simple to complex
- Include common mistakes
</requirements>
<output_format>
# Tutorial: Async/Await in JavaScript
## Learning Objectives
- [objectives]
## Prerequisites
- [what students need]
## Concepts
### [Concept 1]
[Explanation with analogy]
[Code example]
[Why it matters]
### [Concept 2]
[...]
## Common Mistakes
| Mistake | Why It's Wrong | Correct Approach |
|---------|---------------|-----------------|
| [table of mistakes]
## Practice Exercises
### Exercise 1: [title]
[problem]
<details>
<summary>Solution</summary>
[solution code]
</details>
## Summary
[key takeaways]
## Further Reading
[resources]
</output_format>---
Example 9: Strategic Planning
{
"system_instruction": {
"parts": [{
"text": "You are a strategic planning consultant with 20 years of experience helping tech companies scale."
}]
},
"contents": [{
"parts": [{
"text": "Create a 12-month strategic plan for our SaaS startup.\n\n<current_state>\n- Product: B2B project management tool\n- Stage: Series A, $5M ARR\n- Team: 30 people\n- Growth: 15% MoM\n- Churn: 5% monthly\n- CAC: $500\n- LTV: $3,000\n</current_state>\n\n<goals>\n1. Reach $15M ARR\n2. Reduce churn to 3%\n3. Launch enterprise tier\n4. Expand to EU market\n</goals>\n\nProvide:\n- Q1-Q4 priorities\n- Key metrics to track\n- Team hiring plan\n- Budget allocation\n- Risk mitigation\n\nBe specific and actionable."
}]
}]
}---
Example 10: Multimodal RAG
model = genai.GenerativeModel("gemini-2.5-pro")
# Reference materials
logo = genai.upload_file("company-logo.png")
style_guide = genai.upload_file("brand-guidelines.pdf")
response = model.generate_content([
"""Create marketing copy for our new product launch.
<context>
Our brand is: [company description]
Our audience is: [target demographic]
This product is: [product details]
</context>
<brand_guidelines>
Based on the attached style guide and logo, ensure the copy:
- Matches our tone (professional yet approachable)
- Uses our color scheme terminology
- Aligns with our brand values
</brand_guidelines>
Create:
1. Headline (5-7 words)
2. Subheadline (one sentence)
3. 3 bullet point benefits
4. Call-to-action
Ensure everything feels authentic to our brand.""",
logo,
style_guide
])---
Example 11: Data Analysis Pattern
<system_instruction>
You are a data scientist and business analyst.
</system_instruction>
<dataset>
[Large dataset - can use up to 1M tokens]
</dataset>
<analysis_request>
Perform exploratory data analysis and provide:
1. **Data Overview**: Structure, dimensions, types
2. **Summary Statistics**: Key metrics by category
3. **Patterns**: Trends, correlations, anomalies
4. **Insights**: Business-relevant findings
5. **Recommendations**: Data-driven suggestions
6. **Visualizations**: Suggested charts/plots with descriptions
</analysis_request>
<output_format>
## Data Overview
[summary of dataset]
## Summary Statistics
| Metric | Value |
|--------|-------|
[statistics table]
## Key Findings
### Trend 1: [description]
- **Evidence**: [supporting data]
- **Impact**: [business implication]
- **Action**: [recommendation]
### Trend 2: [...]
## Anomalies
[unexpected findings worth investigating]
## Recommendations
Prioritized list of actions based on insights.
</output_format>---
Example 12: Agent Reasoning for Complex Tasks
{
"system_instruction": {
"parts": [{
"text": "You are an autonomous agent that plans and executes complex multi-step tasks. Before taking any action:\n\n1. **Plan**: Break down the task into steps\n2. **Dependencies**: Identify what each step needs\n3. **Risks**: Consider what could go wrong\n4. **Alternatives**: Have backup plans\n\nOnly after thorough planning, execute the steps systematically."
}]
},
"contents": [{
"parts": [{
"text": "Help me migrate this WordPress site to a headless architecture with Next.js.\n\n<current_site>\n- URL: example.com\n- Posts: 1,200\n- Pages: 50\n- Plugins: 15 active\n- Theme: Custom\n- Traffic: 50k monthly visitors\n</current_site>\n\nPlan and execute the migration considering:\n- Content migration\n- SEO preservation\n- Performance optimization\n- Downtime minimization\n- Rollback plan"
}]
}]
}---
Example Analysis Table
| Example | Key Techniques | Why Effective |
|---|---|---|
| 1. System Instruction | Agent reasoning framework | Systematic thinking |
| 2. Multimodal | Image + structured output | Clear formatting requirements |
| 3. Long Context | Full document analysis | Leverages 1M token window |
| 4. Code Generation | System instruction for standards | Consistent code quality |
| 5. Video Analysis | Timestamped extraction | Structured video understanding |
| 6. Comparison | Criteria-based evaluation | Framework-driven analysis |
| 7. Research Synthesis | Pattern recognition across papers | Comprehensive synthesis |
| 8. Educational | Progressive difficulty | Learning-oriented structure |
| 9. Strategic Planning | 12-month breakdown | Actionable business planning |
| 10. Multimodal RAG | Brand consistency | Combines multiple references |
| 11. Data Analysis | Statistical + business | Technical + practical |
| 12. Agent Planning | Multi-step reasoning | Complex task breakdown |
Key Takeaways
1. System Instructions are powerful for setting behavior 2. Long Context enables analysis not possible elsewhere 3. Multimodal combinations create unique capabilities 4. Structured Output ensures consistent formatting 5. Agent Reasoning pattern improves complex task handling 6. Few-Shot examples guide format and style
Gemini Multimodal Prompting Guide
Gemini is natively multimodal - designed from the ground up to understand and generate text, images, audio, video, and code.
Supported Modalities
| Modality | Input | Output | Notes |
|---|---|---|---|
| Text | ✅ | ✅ | Primary modality |
| Images | ✅ | ✅ | JPG, PNG, GIF, WebP |
| Audio | ✅ | ✅ | WAV, MP3, FLAC, etc. |
| Video | ✅ | ✅ | MP4, MOV, AVI, etc. |
| Code | ✅ | ✅ | All major languages |
Image Understanding
Basic Image Analysis (Legacy SDK)
import google.generativeai as genai
import PIL.Image
model = genai.GenerativeModel("gemini-2.5-flash")
image = PIL.Image.open("photo.jpg")
response = model.generate_content([
"Describe what you see in this image.",
image
])Basic Image Analysis (New SDK)
from google import genai
import PIL.Image
client = genai.Client()
image = PIL.Image.open("photo.jpg")
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[
"Describe what you see in this image.",
image
]
)Detailed Image Prompting
<system_instruction>
You are a visual analysis assistant.
</system_instruction>
Analyze this image and provide:
1. Main subject identification
2. Mood and atmosphere
3. Color palette description
4. Suggested use cases (marketing, editorial, etc.)
5. Technical quality assessment
[image]Few-Shot with Images
Here are examples of how I want you to analyze images:
Example 1:
[Image 1: A sunset over mountains]
Analysis: Landscape photography featuring golden hour lighting. Warm orange and purple tones. Peaceful, serene mood. Suitable for travel marketing or nature publications. Good composition with rule of thirds.
Example 2:
[Image 2: Busy city street]
Analysis: Urban street photography with high contrast. Candid human moment. Dynamic, energetic mood. Editorial or documentary style. Good use of leading lines.
Now analyze this image:
[Your image]Image Generation
Gemini can describe images for generation tools:
Describe an image that would work well for [purpose]. Include:
- Subject and composition
- Lighting and mood
- Color scheme
- Style and aestheticAudio Understanding
Transcription and Analysis
model = genai.GenerativeModel("gemini-2.5-pro")
audio_file = genai.upload_file("recording.mp3")
response = model.generate_content([
"Transcribe this audio and summarize the key points.",
audio_file
])Audio Prompting Template
<system_instruction>
You are an audio content analyst.
</system_instruction>
For this audio file, provide:
1. Transcription (if speech)
2. Speaker identification (if multiple)
3. Key topics discussed
4. Sentiment and tone
5. Action items or decisions made
[audio file]Video Understanding
Video Analysis
video_file = genai.upload_file("presentation.mp4")
response = model.generate_content([
"Summarize the main topics covered in this video presentation.",
video_file
])Video Prompting Template
<system_instruction>
You are a video content analyst.
</system_instruction>
Analyze this video and extract:
1. Main topic and purpose
2. Key segments with timestamps
3. Important visual elements
4. Speaker key points (if applicable)
5. Overall structure and flow
[video file]Multimodal Combinations
Text + Image
I'm writing a blog post about sustainable architecture.
[image of green building]
Based on this image, write:
1. A catchy headline
2. Opening paragraph
3. 3 key features of sustainable architecture shown
4. Closing call-to-actionImage + Image Comparison
Compare these two designs:
[Image A]
[Image B]
Analyze:
- Aesthetic differences
- Functional differences
- Target audience for each
- Which is more effective and whyText + Image + Audio
I have a product photo, customer review audio, and product description.
Product: [description]
Image: [product photo]
Review: [audio file]
Create a comprehensive product summary combining all information.Code + Multimodal
Image to Code
Convert this UI mockup into HTML/CSS code.
[image]
Requirements:
- Use Tailwind CSS
- Make it responsive
- Include hover statesDiagram to Code
[architecture diagram]
Implement this system architecture in Python. Include:
- Class structure
- Key methods
- Error handling
- Example usageMultimoral RAG
Image + Text Retrieval
<system_instruction>
You are a multimodal search assistant.
</system_instruction>
I have these reference images:
[Image 1: Modern kitchen]
[Image 2: Traditional kitchen]
[Image 3: Industrial kitchen]
Based on my description "bright, minimalist kitchen with white cabinets and marble countertops", which reference image is most similar and why?Video + Document Q&A
<system_instruction>
You are a technical trainer.
</system_instruction>
Reference materials:
[Training manual PDF]
[Training video]
User question: "How do I reset the device if it freezes?"
Answer using information from both the manual and video.Best Practices for Multimodal
1. Specify Modality: Tell Gemini what type of input to expect
2. Order Matters: Text prompt usually comes first, then media
3. Be Specific: Describe what you want from each modality
4. Use Few-Shot: Show examples of desired analysis
5. Consider File Size: Large files may need processing time
6. Combine Intelligently: Use each modality for its strength
Modality Selection Guide
| Goal | Best Modality | Why |
|---|---|---|
| Describe scene | Image | Visual context |
| Transcribe | Audio | Speech-to-text |
| Tutorial | Video | Step-by-step visual |
| Explain concept | Text | Precise language |
| Analyze design | Image | Visual elements |
| Code review | Text | Code structure |
| UX feedback | Video | User behavior |
Common Patterns
Image Captioning
Write a caption for this image suitable for [platform/context].
[image]
Keep it [length] and [tone].Visual QA
<system_instruction>
You answer questions about images.
</system_instruction>
Question: [your question]
[image]
Answer:Content Generation Based on Image
Based on this image, write a [type of content].
[image]
Include:
- [requirement 1]
- [requirement 2]
- [requirement 3]Style Transfer Description
Describe the artistic style of this image so an artist could recreate it.
[image]
Include:
- Art movement or period
- Color palette
- Brush/stroke technique
- Composition style
- Mood and atmosphereGemini Prompt Patterns
Reusable prompt patterns optimized for Gemini's system instructions and multimodal capabilities.
---
Document & Long-Context Patterns
Large Document Analysis
{
"system_instruction": {
"parts": [{
"text": "You are a document analysis specialist. You synthesize information from large texts and identify patterns, themes, and insights."
}]
},
"contents": [{
"parts": [{
"text": "Analyze this collection of research papers and synthesize:\n1. Common themes across all papers\n2. Contradictions or debates\n3. Research gaps\n4. Future directions suggested\n\n<documents>\n[up to 1M tokens of papers]\n</documents>"
}]
}]
}Multi-Document Comparison
<system_instruction>
You are a research analyst specializing in comparative analysis.
</system_instruction>
Compare these documents on [criteria]:
<document id="1">
[content]
</document>
<document id="2">
[content]
</document>
<output_format>
<comparison>
<similarities>
[what they agree on]
</similarities>
<differences>
[where they diverge]
</differences>
<synthesis>
[integrated understanding]
</synthesis>
</comparison>
</output_format>---
Code Patterns
Function Generation
{
"system_instruction": {
"parts": [{
"text": "You are a senior software engineer. You write clean, well-documented, efficient code with proper error handling."
}]
},
"contents": [{
"parts": [{
"text": "Write a Python function that:\n- Validates email addresses using regex\n- Returns (is_valid: bool, error: str | None)\n- Includes comprehensive docstring\n- Handles edge cases\n\nInclude usage examples."
}]
}]
}Code Review Pattern
<system_instruction>
You are a code reviewer. You focus on: correctness, performance, readability, security, and best practices.
</system_instruction>
Review this code:
[code]
<output_format>
<review>
<summary>[overall assessment]</summary>
<issues>
<issue>
<severity>[critical/major/minor]</severity>
<location>[where]</location>
<description>[problem]</description>
<fix>[suggested fix]</fix>
</issue>
</issues>
<positives>
[what's done well]
</positives>
<improved_code>[improved version]
</improved_code>
</review>
</output_format>---
Multimodal Patterns
Image Analysis + Text Generation
<system_instruction>
You are a content creator who writes engaging social media posts based on visual content.
</system_instruction>
[image]
Create an Instagram post for this image:
- Captivating headline
- 3-5 emoji-rich bullet points
- Relevant hashtags
- Call-to-action
Tone: [enthusiastic/professional/funny]Diagram to Implementation
<system_instruction>
You are a full-stack developer who implements systems based on architectural diagrams.
</system_instruction>
[system diagram]
Implement this architecture as:
1. Database schema (SQL)
2. API endpoints (OpenAPI spec)
3. Frontend component structure (React)
4. Deployment configuration (docker-compose.yml)
Include error handling and validation.Video to Tutorial
<system_instruction>
You are a technical writer who creates step-by-step tutorials from video content.
</system_instruction>
[video file]
Create a written tutorial covering the same content:
- Prerequisites
- Step-by-step instructions
- Code examples
- Troubleshooting section---
Analysis Patterns
SWOT Analysis
<system_instruction>
You are a strategic business analyst.
</system_instruction>
Conduct a SWOT analysis for:
<subject>
[company/product/strategy]
</subject>
<context>
[relevant background]
</context>
<output_format>
<swot>
<strengths>
[internal advantages]
</strengths>
<weaknesses>
[internal limitations]
</weaknesses>
<opportunities>
[external possibilities]
</opportunities>
<threats>
[external risks]
</threats>
<strategic_recommendations>
[prioritized action items]
</strategic_recommendations>
</swot>
</output_format>Root Cause Analysis
<system_instruction>
You are a problem-solving analyst who uses systematic approaches to identify root causes.
</system_instruction>
<problem>
[description of issue]
</problem>
<available_data>
[what we know]
</available_data>
Use the 5 Whys technique to identify root cause, then provide recommended actions.
<output_format>
<analysis>
<symptoms>[what we observe]</symptoms>
<five_whys>
<why level="1">[question and answer]</why>
<why level="2">[question and answer]</why>
[...]
</five_whys>
<root_cause>[fundamental issue]</root_cause>
<recommended_actions>
<priority>[high/medium/low]</priority>
<action>[what to do]</action>
<expected_outcome>[result]</expected_outcome>
</recommended_actions>
</analysis>
</output_format>---
Creative Patterns
Brainstorming
<system_instruction>
You are a creative ideation specialist who generates innovative solutions.
</system_instruction>
I need ideas for [challenge].
Generate 10 diverse options ranging from:
- Conservative to radical
- Low cost to high investment
- Quick implementation to long-term
<output_format>
<ideas>
<idea>
<title>[catchy name]</title>
<description>[what it is]</description>
<pros>[why it works]</pros>
<cons>[potential issues]</cons>
<effort>[implementation difficulty]</effort>
<impact>[expected benefit]</impact>
</idea>
</ideas>
</output_format>Story Generation
<system_instruction>
You are a creative writer specializing in [genre].
</system_instruction>
Write a short story based on this prompt:
<prompt>
[story premise]
</prompt>
Requirements:
- Approximately [word count] words
- [tone] tone
- Include [specific elements]
- Surprise ending
<output_format>
<title>[story title]</title>
<story>
[story content]
</story>
</output_format>---
Educational Patterns
Lesson Creation
<system_instruction>
You are an educator who creates engaging, effective learning materials.
</system_instruction>
Create a lesson plan for teaching [topic] to [audience level].
<requirements>
- Learning objectives
- Prerequisites
- Lesson duration: [time]
- Include hands-on activities
- Assessment method
</requirements>
<output_format>
<lesson>
<title>[lesson title]</title>
<objectives>
<objective>[SMART objective]</objective>
</objectives>
<prerequisites>
[what students need to know]
</prerequisites>
<materials>
[required resources]
</materials>
<outline>
<segment time="[duration]">
<title>[segment title]</title>
<activity>[what happens]</activity>
</segment>
</outline>
<assessment>
[how to check understanding]
</assessment>
</lesson>
</output_format>Explanation Generation
<system_instruction>
You are [subject] expert who excels at explaining complex topics clearly.
</system_instruction>
Explain [topic] to [target audience].
<approach>
- Start with a hook or real-world example
- Use analogies where helpful
- Build understanding step by step
- Include examples
- Address common misconceptions
- End with key takeaways
</approach>
<output_format>
<explanation>
<hook>[engaging opening]</hook>
<core_concept>
<definition>[clear explanation]</definition>
<analogy>[relatable comparison]</analogy>
<example>[concrete illustration]</example>
</core_concept>
<misconceptions>
<misconception>
<belief>[wrong idea]</belief>
<reality>[correct understanding]</reality>
</misconception>
</misconceptions>
<key_takeaways>
<takeaway>[essential point]</takeaway>
</key_takeaways>
</explanation>
</output_format>---
Decision Support Patterns
Option Evaluation
<system_instruction>
You are a decision analyst who uses structured frameworks to evaluate options.
</system_instruction>
I need to decide between [options] for [purpose].
<options>
<option id="A">
[name + key features]
</option>
<option id="B">
[name + key features]
</option>
<option id="C">
[name + key features]
</option>
</options>
<criteria>
[criteria that matter]
</criteria>
<output_format>
<evaluation>
<comparison_table>
[markdown table comparing options on criteria]
</comparison_table>
<analysis>
<option>
<name>[option name]</name>
<pros>[strengths]</pros>
<cons>[weaknesses]</cons>
<score>[overall assessment]</score>
</option>
</analysis>
<recommendation>
[which option and why]
</recommendation>
<confidence>
[how confident and what could change it]
</confidence>
</evaluation>
</output_format>Risk Assessment
<system_instruction>
You are a risk management specialist.
</system_instruction>
Assess the risks of [proposed action/initiative].
<proposal>
[what's being proposed]
</proposal>
<context>
[relevant environment/constraints]
</context>
<output_format>
<risk_assessment>
<risks>
<risk>
<description>[what could go wrong]</description>
<probability>[low/medium/high]</probability>
<impact>[low/medium/high]</impact>
<mitigation_strategy>[how to prevent/reduce]</mitigation_strategy>
<contingency_plan>[what to do if it happens]</contingency_plan>
</risk>
</risks>
<overall_risk>
[level: low/medium/high]
<rationale>[why this level]</rationale>
<go_no_go>
[recommendation to proceed/not/with conditions]
</go_no_go>
</overall_risk>
</risk_assessment>
</output_format>---
Research Patterns
Literature Synthesis
<system_instruction>
You are a research scientist who synthesizes findings across multiple studies.
</system_instruction>
Synthesize these research papers on [topic]:
<papers>
[paper content - can use full 1M context]
</papers>
<output_format>
<synthesis>
<themes>
<theme>
[name>[theme name]</name>
<consensus>[what papers agree on]</consensus>
<disagreements>[where they differ]</disagreements>
<evidence>[key studies]</evidence>
</theme>
</themes>
<methodologies>
<common_approaches>[how studies were done]</common_approaches>
<limitations>[methodological weaknesses]</limitations>
</methodologies>
<research_gaps>
<gap>[what hasn't been studied]</gap>
</research_gaps>
<future_directions>
<direction>[promising research areas]</direction>
</future_directions>
</synthesis>
</output_format>Market Analysis
<system_instruction>
You are a market research analyst.
</system_instruction>
Analyze the market for [product/service] in [region/segment].
<data>
[market data, trends, competitive landscape]
</data>
<output_format>
<market_analysis>
<market_overview>
[size, growth rate, trends]
</market_overview>
<competitive_landscape>
[key players, positioning, market share]
</competitive_landscape>
<opportunities>
[gaps, underserved segments, trends to leverage]
</opportunities>
<threats>
[challenges, risks, competitive pressures]
</threats>
<recommendations>
[strategic recommendations for entry/growth]
</recommendations>
</market_analysis>
</output_format>---
Pattern Selection Guide
| Goal | Pattern | Why |
|---|---|---|
| Analyze large docs | Large Document Analysis | Leverages 1M context |
| Generate code | Function Generation | Clear requirements |
| Review code | Code Review Pattern | Structured feedback |
| Create from image | Image + Text Generation | Multimodal strength |
| Analyze options | Option Evaluation | Framework-based |
| Teach topic | Lesson Creation | Educational structure |
| Research synthesis | Literature Synthesis | Pattern recognition |
| Assess risks | Risk Assessment | Systematic analysis |
Gemini System Instructions Guide
Comprehensive guide to system instructions for Gemini models.
What Are System Instructions?
System instructions are Gemini's primary mechanism for defining model behavior, role, and constraints. They set the context for all messages in a conversation and persist throughout.
Basic Structure
{
"system_instruction": {
"parts": [{"text": "[Your instruction here]"}]
}
}Official Template from Google
From Gemini API documentation:
<role>
You are Gemini, a specialized assistant for [Insert Domain].
You are precise, analytical, and persistent.
</role>
<instructions>
1. **Plan**: Analyze the task and create a step-by-step plan.
2. **Execute**: Carry out the plan.
3. **Validate**: Review your output against the user's task.
4. **Format**: Present the final answer in the requested structure.
</instructions>
<constraints>
- Verbosity: [Specify Low/Medium/High]
- Tone: [Specify Formal/Casual/Technical]
</constraints>
<output_format>
Structure your response as follows:
1. **Executive Summary**: [Short overview]
2. **Detailed Response**: [The main content]
</output_format>Component Breakdown
Role Definition
Define who Gemini is:
You are a senior software engineer specializing in Python and distributed systems.You are a creative writing assistant focused on science fiction and fantasy.You are a data analyst with expertise in financial modeling and visualization.Behavioral Instructions
How Gemini should approach tasks:
When given a task:
1. Break it down into smaller components
2. Identify the key requirements
3. Consider multiple approaches
4. Recommend the best option with reasoningOutput Formatting
Define response structure:
Always structure your responses as:
- **Summary**: 2-3 sentence overview
- **Analysis**: Detailed breakdown
- **Recommendation**: Actionable advice
- **Caveats**: Limitations or risksConstraints
Limit behavior:
- Never make up facts - say "I don't know" if uncertain
- Always cite sources when making factual claims
- Keep responses under 500 words unless asked for more detail
- Use simple language accessible to non-expertsAgent Reasoning System Instruction
From official Google documentation - for agent-like behavior:
You are a very strong reasoner and planner. Use these critical instructions to structure your plans, thoughts, and responses.
Before taking any action (either tool calls or responses to the user), you must proactively, methodically, and independently plan and reason about:
1) Logical dependencies and constraints:
- Policy-based rules and mandatory prerequisites
- Order of operations
- Other prerequisites
- Explicit user constraints or preferences
2) Risk assessment:
- Consequences of taking the action
- Whether new state will cause future issues
- For exploratory tasks, missing optional parameters is LOW risk
3) Abductive reasoning and hypothesis exploration:
- Identify most logical reason for problems
- Look beyond immediate causes
- Generate and test hypotheses
4) Outcome evaluation and adaptability:
- Does observation require plan changes?
- Generate new hypotheses if disproven
5) Information availability:
- Using available tools
- All policies, rules, checklists
- Previous observations and history
- Information from user
6) Precision and Grounding:
- Be extremely precise
- Quote exact applicable information
- Verify claims
7) Completeness:
- Exhaustively incorporate requirements
- Resolve conflicts by priority
- Avoid premature conclusions
8) Persistence and patience:
- Don't give up unless reasoning exhausted
- Retry on transient errors
- Change strategy on other errors
9) Inhibit your response: Only act after completing above reasoningCommon Patterns
Technical Expert
You are a [domain] expert with [X] years of experience.
Your responses are:
- Technically accurate
- Well-structured with clear explanations
- Include code examples when relevant
- Address edge cases and error handling
When unsure, state your assumptions and confidence level.Creative Writer
You are a creative writing assistant specializing in [genre].
Your writing is:
- Engaging and original
- Rich in sensory details
- Character-driven
- Appropriate for the target audience
Avoid clichés and overused tropes.Analyst
You are a [type] analyst focused on [domain].
Your approach is:
- Data-driven and evidence-based
- Objective and balanced
- Conscious of biases and limitations
- Clear about confidence levels
Always show your work and explain your reasoning.Teacher
You are a [subject] teacher for [level] students.
Your teaching style:
- Starts with basics before advanced topics
- Uses analogies and real-world examples
- Checks for understanding
- Encourages questions and curiosity
- Adapts to student's pace
Simplify complex ideas without losing accuracy.Customer Support
You are a customer support specialist for [company/product].
You are:
- Empathetic and patient
- Solution-oriented
- Knowledgeable about products
- Professional but friendly
Always:
- Acknowledge the user's frustration
- Provide clear next steps
- Escalate when appropriate
- Follow up to ensure resolutionMulti-Turn System Instructions
For complex behaviors, use structured system instructions:
<core_identity>
You are a research assistant specializing in [field].
</core_identity>
<approach>
For research tasks:
1. Identify key questions and information needs
2. Gather relevant data from multiple sources
3. Synthesize findings into coherent insights
4. Present conclusions with supporting evidence
5. Note limitations and areas for further research
</approach>
<output_style>
- Use Markdown for structure
- Include section headers
- Provide bullet points for lists
- Use tables for comparisons
- Cite sources when applicable
</output_style>
<constraints>
- Don't fabricate sources
- Indicate speculation clearly
- Respect intellectual property
- Consider multiple viewpoints
</constraints>
<quality_standards>
- Verify factual claims
- Update knowledge based on new information
- Admit uncertainty rather than guess
- Provide balanced perspectives on controversial topics
</quality_standards>Best Practices
1. Be Specific: "You are helpful" → "You are a Python tutor specializing in data science"
2. Set Output Format: Tell Gemini how to structure responses
3. Define Constraints: What Gemini should and shouldn't do
4. Use Examples: Show, don't just tell
5. Iterate: Test and refine system instructions
6. Keep Focused: One clear role is better than many
7. Match Model: Flash for speed, Pro for complexity
System Instruction vs. Prompt Content
| Aspect | System Instruction | Prompt Content |
|---|---|---|
| Purpose | Set behavior | Specific task |
| Persistence | Entire conversation | Single message |
| Visibility | Hidden from user | Visible |
| Best For | Role, style, constraints | Data, examples, questions |
Example Comparison
Without System Instruction:
You are a code reviewer. Review this Python function for bugs, style issues, and potential improvements.
[code]With System Instruction:
{
"system_instruction": {
"parts": [{
"text": "You are a senior Python engineer conducting code reviews. You focus on: correctness, performance (time/space complexity), readability, and Python best practices (PEP 8). You provide specific, actionable feedback with code examples."
}]
},
"contents": [{
"parts": [{"text": "Review this function:\n\n[code]"}]
}]
}The system instruction version ensures consistent behavior across all messages in the conversation.
Gemini Prompt Engineering - Techniques
Detailed guide to universal prompting techniques adapted specifically for Gemini.
---
1. Zero-Shot Prompting
What It Is
Asking Gemini to perform a task without providing examples.
Gemini-Specific Approach
Gemini excels at zero-shot when paired with effective system instructions.
Examples
Simple Query:
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain the difference between supervised and unsupervised machine learning."
)With System Instruction:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Classify this customer review sentiment.",
config=genai.types.GenerateContentConfig(
system_instruction="You are a sentiment analyst. Classify text as positive, negative, or neutral."
)
)Structured Output Request:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
Extract the following information from this text:
- Company names
- Technologies mentioned
- Key challenges
Text: [paste text]
Output as JSON.
"""
)Tips
- Always specify output format when structure matters
- Use system instructions to set behavior
- Be explicit about requirements
- Leverage Gemini's instruction following
---
2. Few-Shot Prompting
What It Is
Providing examples to guide Gemini's responses through in-context learning.
Gemini-Specific Approach
Use clear, well-formatted examples. Gemini learns patterns from demonstrations.
Template
from google import genai
client = genai.Client()
examples = """
Example 1:
Input: This product is amazing!
Output: {"sentiment": "positive", "confidence": 0.95}
Example 2:
Input: Terrible experience, would not recommend.
Output: {"sentiment": "negative", "confidence": 0.92}
Example 3:
Input: It's okay, does what it says.
Output: {"sentiment": "neutral", "confidence": 0.75}
"""
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=examples + "\nInput: The delivery was fast and the quality is great!\nOutput:"
)Example: Code Style
response = client.models.generate_content(
model="gemini-2.5-flash",
config=genai.types.GenerateContentConfig(
system_instruction="You are a Python code formatter following PEP 8 standards."
),
contents="""
Here are examples of properly formatted Python code:
Example 1:
def calculate_sum(a,b):return a+b
Formatted:
def calculate_sum(a: int, b: int) -> int:
\"\"\"Calculate the sum of two integers.\"\"\"
return a + b
Example 2:
def get_user(id):return db.query(f'SELECT * FROM users WHERE id={id}')
Formatted:
def get_user(user_id: int) -> User:
\"\"\"Retrieve a user by ID from the database.\"\"\"
query = 'SELECT * FROM users WHERE id = ?'
return db.query(query, (user_id,)).fetchone()
Now format this code:
def process(data):results=[transform(x)for x in data if x];return results
"""
)Tips
- 3-5 examples usually sufficient
- Examples should cover edge cases
- Format examples exactly as you want output
- Show both input and expected output clearly
---
3. Chain-of-Thought Prompting
What It Is
Prompting Gemini to show its reasoning step-by-step.
Gemini-Specific Approach
Use explicit reasoning prompts. Gemini's strong reasoning capabilities shine with structured CoT.
Template
response = client.models.generate_content(
model="gemini-2.5-flash",
config=genai.types.GenerateContentConfig(
system_instruction="You are a strong reasoner. Always show your step-by-step thinking process."
),
contents="""
The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.
Let's think through this systematically:
"""
)Example: Math Problem
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="""
A train leaves Station A at 2:00 PM traveling at 60 mph. Another train leaves Station B at 3:00 PM traveling at 80 mph toward Station A. The stations are 300 miles apart.
At what time do the trains meet?
Think through this step by step:
1. Identify what we know
2. Determine when both trains are moving
3. Calculate the combined speed
4. Find the meeting time
Show your work.
"""
)Example: Logical Reasoning
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="""
If all Bloops are Razzles and all Razzles are Lazzles, then all Bloops are definitely Lazzles.
Is this reasoning valid? Think through it step by step:
1. Understand the given premises
2. Identify the logical structure
3. Apply transitive property
4. Verify the conclusion
Explain each step.
"""
)Tips
- Use "step by step" or "systematically" as triggers
- For complex problems, enumerate the steps
- Gemini Pro is better for complex reasoning
- Useful for math, logic, planning problems
---
4. Zero-Shot CoT
What It Is
Adding a simple phrase to trigger reasoning without examples.
Gemini-Specific Triggers
| Trigger | Best For |
|---|---|
| "Think step by step" | Sequential reasoning |
| "Let's work through this systematically" | Structured analysis |
| "Show your reasoning" | Explanatory responses |
| "Walk me through your thinking" | Teaching/explaining |
| "Break this down" | Complex problems |
Examples
# Math problem
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
If 3 machines can produce 15 widgets in 6 minutes, how many widgets can 5 machines produce in 12 minutes?
Let's think step by step.
"""
)
# Decision making
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
Should I invest in index funds or individual stocks?
Let's work through this systematically by considering:
- Risk tolerance
- Time horizon
- Investment goals
- Market conditions
"""
)
# Debugging
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
This code is throwing a NullReferenceException. Help me debug it.
[code]
Walk me through your reasoning process.
"""
)Tips
- Simple addition to any prompt
- Effective for both simple and complex tasks
- Combine with system instruction for consistency
- Pro model gives deeper reasoning
---
5. Prompt Chaining
What It Is
Breaking complex tasks into sequential prompts, where each prompt's output informs the next.
Gemini-Specific Advantage
Ultra-long context (1M+ tokens) enables extensive chaining without losing context.
Example: Document Analysis Chain
Chain Step 1: Extract
response1 = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
<task>
Extract all mentions of "AI safety" and "alignment" from this document.
</task>
<document>
[paste large document]
</document>
<output_format>
Extract relevant quotes using <quote> tags.
</output_format>
"""
)
extracted_quotes = response1.textChain Step 2: Synthesize
response2 = client.models.generate_content(
model="gemini-2.5-flash",
contents=f"""
<task>
Synthesize these extracted quotes into key themes about AI safety.
</task>
<quotes>
{extracted_quotes}
</quotes>
<output_format>
<themes>
<theme>
<name>[theme name]</name>
<summary>[description]</summary>
<related_quotes>[list]</related_quotes>
</theme>
</themes>
</output_format>
"""
)
themes = response2.textChain Step 3: Generate Report
response3 = client.models.generate_content(
model="gemini-2.5-pro",
contents=f"""
<task>
Create a comprehensive report on AI safety based on the themes extracted.
</task>
<themes>
{themes}
</themes>
<original_document>
[paste document]
</original_document>
<output_format>
<report>
<executive_summary>[2-3 paragraphs]</executive_summary>
<key_findings>[bullet points]</key_findings>
<recommendations>[action items]</recommendations>
</report>
</output_format>
"""
)Benefits
- Each step is verifiable
- Can adjust based on intermediate results
- Reduces complexity of individual prompts
- Leverages Gemini's long context window
Tips
- Use clear delimiters between chain steps
- Pass full context when needed (Gemini can handle it)
- Document the chain for reproducibility
- Can run chains in parallel if independent
---
6. ReAct Prompting (Reason + Act)
What It Is
Interleaving reasoning with actions (tool use, API calls, searches).
Gemini's Strength
Excellent tool use with native function calling support.
Pattern
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
<question>
What is the current stock price of NVIDIA and what was the price one week ago?
</question>
<thought_1>
I need to find current NVIDIA stock information and historical data from one week ago.
</thought_1>
<action_1>
<tool>search</tool>
<query>NVDA stock price today current</query>
</action_1>
<observation_1>
[search result with current price]
</observation_1>
<thought_2>
Now I need to find the price from one week ago. One week ago from today was [specific date].
</thought_2>
<action_2>
<tool>search</tool>
<query>NVDA stock price [date one week ago]</query>
</action_2>
<observation_2>
[historical price data]
</observation_2>
<thought_3>
I now have both pieces of information. Let me calculate the difference and provide the answer.
</thought_3>
<final_answer>
Based on my search:
- Current NVDA price: [current price]
- Price one week ago: [past price]
- Change: [difference and percentage]
</final_answer>
"""
)With Actual Function Calling
from google import genai
from google.genai import types
client = genai.Client()
# Define tools
get_weather = types.FunctionDeclaration(
name="get_weather",
description="Get current weather for a location",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"location": types.Schema(
type=types.Type.STRING,
description="City name, e.g., San Francisco"
)
},
required=["location"]
)
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What's the weather like in Tokyo and Paris?",
config=types.GenerateContentConfig(
tools=[get_weather]
)
)Tips
- Gemini handles tool natively with function calling
- Specify clear thought/action/observation structure
- Useful for research, data gathering, multi-step tasks
- Flash model is fast and capable for most ReAct patterns
---
7. Tree of Thoughts (ToT)
What It Is
Exploring multiple reasoning paths before concluding, with lookahead and backtracking.
Gemini-Specific Approach
Use structured XML to organize thought branches. Gemini's strong reasoning excels at exploration.
Template
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="""
<problem>
Our startup needs to choose a pricing strategy. Options: freemium, free trial, or paid-only.
We have $50K in funding, 5K active users, and 20% month-over-month growth.
</problem>
<thought_paths>
<path_1>
<strategy>Freemium</strategy>
<reasoning>
Pros:
- Largest user base potential
- Data collection for product improvement
- Network effects
Cons:
- High conversion costs
- Free users don't pay
- Support burden
Expected: 50K free users, 500 paying (1% conversion)
Revenue: $500/month at $10/month
</reasoning>
<expected_outcome>
Large user base but low revenue initially. Break-even in ~20 months.
</expected_outcome>
</path_1>
<path_2>
<strategy>Free Trial (14 days)</strategy>
<reasoning>
Pros:
- Higher conversion rates than freemium
- Users experience full value
- Clear upgrade path
Cons:
- Smaller top of funnel
- Users may not sign up without free tier
Expected: 10K trial users, 2K paying (20% conversion)
Revenue: $20,000/month at $10/month
</reasoning>
<expected_outcome>
Smaller user base but better revenue. Break-even in ~3 months.
</expected_outcome>
</path_2>
<path_3>
<strategy>Paid-Only ($29/month)</strategy>
<reasoning>
Pros:
- Revenue from day one
- Serious, committed users
- Lower support costs
Cons:
- Highest barrier to entry
- Smallest total addressable market
Expected: 2K paying users directly
Revenue: $58,000/month
</reasoning>
<expected_outcome>
Highest immediate revenue but slowest growth.
</expected_outcome>
</path_3>
</thought_paths>
<recommendation>
For our situation ($50K funding, need runway), I recommend:
<strong>Free Trial (14 days)</strong>
Rationale:
1. Within our runway constraints
2. 20% conversion is realistic for our product
3. $20K/month gives us 7.5 months of runway
4. Can pivot to freemium later if needed
<strong>Not recommended:</strong> Paid-only (too risky for our stage) or Freemium (burns cash too fast)
</recommendation>
"""
)Example: Technical Decision
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="""
<problem>
We need to choose a database for our new SaaS application:
- 100K daily active users expected
- Heavy read workload (95% reads, 5% writes)
- Need real-time analytics
- Budget: $2K/month for infrastructure
</problem>
<thought_paths>
<path_1>
<choice>PostgreSQL with read replicas</choice>
<analysis>
Strengths:
- Mature, reliable
- ACID compliance
- Good for complex queries
Weaknesses:
- Write scaling is vertical only
- Real-time analytics requires separate system
- Cost scales with load
Cost estimate: $1,500/month for primary + replicas
</analysis>
<verdict>Good fit, but analytics will need separate solution</verdict>
</path_1>
<path_2>
<choice> MongoDB with sharding</choice>
<analysis>
Strengths:
- Horizontal scaling
- Good write performance
- Flexible schema
Weaknesses:
- No joins for complex queries
- Eventual consistency
- Higher operational complexity
Cost estimate: $1,200/month for sharded cluster
</analysis>
<verdict>Strong candidate if we can handle eventual consistency</verdict>
</path_2>
<path_3>
<choice>Amazon Aurora PostgreSQL</choice>
<analysis>
Strengths:
- Auto-scaling storage
- Read replicas up to 15
- 5x performance improvement
- Managed service
Weaknesses:
- Vendor lock-in
- Higher cost per compute
- Learning curve
Cost estimate: $1,800/month
</analysis>
<verdict>Over budget but excellent capabilities</verdict>
</path_3>
<path_4>
<choice>PostgreSQL + Redis + ClickHouse</choice>
<analysis>
Strengths:
- PostgreSQL for transactional data
- Redis for caching (reduces DB load)
- ClickHouse for real-time analytics
Weaknesses:
- Three systems to manage
- Data synchronization complexity
- Higher operational overhead
Cost estimate: $1,000/month total
<analysis>
Most flexible solution within budget
</analysis>
</path_4>
</thought_paths>
<synthesis>
<recommendation>
<path_4>PostgreSQL + Redis + ClickHouse</path_4>
<justification>
1. Fits within $2K budget at $1K/month
2. Meets all requirements: transactions, real-time analytics, read-heavy workload
3. Industry-standard stack (PostgreSQL) with proven caching strategy (Redis)
4. ClickHouse is purpose-built for real-time analytics
5. Room to grow within budget constraints
<implementation_plan>
Phase 1: PostgreSQL + Redis (start)
Phase 2: Add ClickHouse when analytics needs grow
Phase 3: Scale PostgreSQL read replicas as needed
</implementation_plan>
<risks>
- Operational complexity of three systems
- Mitigation: Use managed services (RDS, ElastiCache, ClickHouse Cloud)
</risks>
</justification>
</recommendation>
</synthesis>
"""
)Tips
- Use Gemini Pro for complex ToT (better reasoning)
- Structure thoughts clearly with XML
- Consider 2-5 paths (not too many)
- Include expected outcomes for each path
- Provide clear recommendation with justification
---
Technique Selection Guide for Gemini
| Scenario | Best Technique | Why |
|---|---|---|
| Quick question | Zero-shot | Fast, direct |
| Format-sensitive task | Few-shot | Shows exact pattern |
| Complex reasoning | CoT or Zero-Shot CoT | Shows thinking process |
| Multi-step workflow | Prompt chaining | Verifiable steps |
| Research with tools | ReAct | Tool calling support |
| Strategic exploration | Tree of Thoughts | Explores options |
| Large document analysis | Zero-shot + chaining | 1M context handles it |
| Image analysis | Zero-shot + system instruction | Multimodal native |
| Code generation | Zero-shot + few-shot | Strong code capabilities |
---
Advanced: Combining Techniques
Few-Shot + CoT
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
Here are examples of how I want you to reason through problems:
Example 1:
Input: If it takes 5 machines 5 minutes to make 5 widgets, how long for 100 machines to make 100 widgets?
Reasoning:
- Each machine makes 1 widget in 5 minutes
- 100 machines operating simultaneously
- Each makes 1 widget in 5 minutes
- Total: 5 minutes
Answer: 5 minutes
Example 2:
Input: A bat and ball cost $1.10. The bat costs $1.00 more than the ball. How much does the ball cost?
Reasoning:
- Let ball cost = x
- Then bat cost = x + $1.00
- Total: x + (x + $1.00) = $1.10
- 2x + $1.00 = $1.10
- 2x = $0.10
- x = $0.05
Answer: The ball costs $0.05
Now solve this showing your reasoning:
Input: 3 machines can produce 15 widgets in 6 minutes. How many widgets can 5 machines produce in 12 minutes?
"""
)Prompt Chaining + ReAct
# Step 1: Research
response1 = client.models.generate_content(
model="gemini-2.5-flash",
contents="""
<task>
Research the latest developments in AI regulation in the EU.
</task>
<thought_1>
I need to search for current EU AI regulations and recent updates.
</thought_1>
<action_1>
<tool>search</tool>
<query>EU AI Act 2025 latest developments compliance</query>
</action_1>
"""
)
# Step 2: Analyze
response2 = client.models.generate_content(
model="gemini-2.5-flash",
contents=f"""
<task>
Analyze the research findings and identify key compliance requirements for a startup.
</task>
<research_findings>
{response1.text}
</research_findings>
<thought>
I need to extract the most relevant requirements for a small AI startup.
</thought>
"""
)
# Step 3: Recommend
response3 = client.models.generate_content(
model="gemini-2.5-pro",
contents=f"""
<task>
Provide actionable compliance recommendations based on the analysis.
</task>
<analysis>
{response2.text}
</analysis>
<context>
We are a 10-person AI startup building a content moderation tool.
</context>
"""
)Tree of Thoughts + Multimodal
response = client.models.generate_content(
model="gemini-2.5-pro",
config=genai.types.GenerateContentConfig(
system_instruction="You are a UX consultant analyzing design options."
),
contents=[
"Analyze these three UI mockups and recommend the best approach:",
"\n\n<thought_paths>",
"\n<path_1>",
"\n<mockup_a_description>",
"\n<analysis>",
"\nStrengths: Clean layout, clear CTA",
"\nWeaknesses: Low information density",
"\n</analysis>",
"\n</path_1>",
"\n<path_2>",
"\n<mockup_b_description>",
"\n<analysis>",
"\nStrengths: High information density",
"\nWeaknesses: May overwhelm users",
"\n</analysis>",
"\n</path_2>",
"\n<path_3>",
"\n<mockup_c_description>",
"\n<analysis>",
"\nStrengths: Balanced approach",
"\nWeaknesses: CTA not prominent enough",
"\n</analysis>",
"\n</path_3>",
"\n</thought_paths>",
"\n<recommendation>",
"\nChoose path_3 with modifications: increase CTA prominence.",
"\n</recommendation>"
]
)---
Troubleshooting
Issue: Not Following Instructions
Symptoms: Gemini ignores format requirements or constraints.
Solutions: 1. Move requirements to system instruction 2. Be more specific about output format 3. Use few-shot examples to demonstrate 4. Use explicit output tags like <output_format>
Issue: Too Verbose
Symptoms: Responses are longer than needed.
Solutions: 1. Add verbosity constraint to system instruction 2. Specify word/character limits 3. Use "be concise" in task description 4. Use Flash model (faster, more concise)
Issue: Missing Key Information
Symptoms: Responses omit important details.
Solutions: 1. Provide comprehensive examples 2. List all required output fields 3. Use CoT to force thorough reasoning 4. Ask for specific details explicitly
Issue: Inconsistent Format
Symptoms: Output format varies between requests.
Solutions: 1. Use few-shot examples 2. Specify exact output structure 3. Use JSON schema with structured outputs 4. Add format validation in system instruction