Articles

How to Build AI Agents with Gemini 3 in 10 Minutes

  • Learn to build stateful AI agents with persistent memory using Letta's MemGPT architecture—designed for developers and ML engineers.
    • Beginner Friendly.
      1 hour
  • Discover the world of data in this fully conceptual course where you will learn how to think about, visualize, and analyze data.
    • Beginner Friendly.
      4 hours

What is Gemini 3?

Gemini 3 is Google’s latest multimodal AI model designed especially for creating autonomous AI agents. Gemini 3 is excellent at agentic tasks like tool use, code execution, and multi-step reasoning, in contrast to traditional language models that only react to prompts. It can use autonomous workflows to accomplish real-world tasks by reading and interpreting text, images, files, and code. Gemini 3 agents are capable of autonomous planning, execution, and adaptation, whereas previous models required continuous prompting.

Gemini 3 is accessible via the Gemini API, Gemini CLI, Agent Designer, or Antigravity (Google’s agent-focused IDE for building agents). This flexibility allows you to create intelligent agents that handle data analysis, perform research, provide coding assistance, and make complex decisions. From simple chat-based interactions to creating production-ready agentic AI systems that reason, plan, and produce structured outcomes, Gemini 3 signifies a fundamental change in AI development.

But what exactly makes something an “agent” instead of just another AI chatbot?

What is an agent?

An AI agent is a system that does more than just provide answers. An agent comprehends your objective, breaks it down into steps, and carries out a plan to completion while a standard language model waits for your next prompt. It can make decisions about which tools to use, run code, read files, analyze data, fix mistakes, and generate organized outcomes. Agents are not text predictors, rather, they are independent problem solvers.

These agents handle the entire workflow from beginning to end, they don’t merely give you instructions.

Let us try to understand agents by building one ourselves.

Build a data analysis mini agent using Gemini 3

Using the Gemini 3 model, we will create an agent that automatically examines CSV files. It loads data, computes statistics, identifies trends, and makes recommendations for business actions. Real business reporting, sales dashboards, and any other task requiring insights from spreadsheet data can all benefit from this method.

First, let’s configure the Gemini toolkit.

Step 1: Installing the Gemini 3 toolkit

Follow these steps to install the Gemini 3 toolkit on your machine:

1. First, install the Gemini SDK. Open your terminal and run:

pip install google-generativeai

2. Next, we need the API key, so, visit the Google API key page and select “Create API key”. Give the required naming, generate the key, and copy it.

3. Set your API key as an environment variable. For Windows, open PowerShell and run:

$env:GEMINI_API_KEY='your-api-key-here'

Mac/Linux users can run the following command:

export GEMINI_API_KEY='your-api-key-here'

4. Test your setup with a quick Python script:

import google.generativeai as genai
import os
genai.configure(api_key=os.getenv('GEMINI_API_KEY'))
model = genai.GenerativeModel('gemini-3-pro-preview')
response = model.generate_content('Hello, Gemini!')
print(response.text)

If you see a response, you’re ready to build your agent.

Step 2: Setting up the project folder

1. Create a working directory for your agent project with this command on the terminal:

mkdir gemini-data-agent
cd gemini-data-agent # use this to navigate inside the directory created

2. Now, create a sample dataset. This CSV file contains sales data across different products and regions. Save this as sales.csv:

date,product,sales,region,quantity
2024-01-15,Widget A,1200,North,45
2024-01-16,Widget B,850,South,30
2024-01-17,Widget A,1100,East,42
2024-01-18,Widget C,2000,West,50
2024-01-19,Widget B,750,North,25
2024-01-20,Widget A,1300,South,48
2024-01-21,Widget C,1900,East,47
2024-01-22,Widget B,900,West,32
2024-01-23,Widget A,1150,North,44
2024-01-24,Widget C,2100,South,52
2024-01-25,Widget B,820,East,28
2024-01-26,Widget A,1250,West,46
2024-01-27,Widget C,1950,North,49
2024-01-28,Widget B,880,South,31
2024-01-29,Widget A,1180,East,43

This dataset contains 15 transactions with information about dates, products (Widget A, B, and C), sales amounts, regions, and quantities sold. This information will be used by the agent to compute performance metrics, spot trends, and produce business insights.

3. Next, create a configuration file that defines how your agent should behave. Save this as agent_config.json:

{
"role": "Data Analysis Agent",
"goal": "Load CSV file, analyze data, and generate actionable insights",
"tasks": [
"Read the CSV content and verify data quality",
"Calculate summary statistics for all numerical columns",
"Identify trends, patterns, or outliers in the data",
"Generate natural-language insights with recommendations"
],
"allowed_tools": ["code_execution", "file_read"],
"restrictions": "Only access files in the project directory. Execute safe Python code only.",
"output_format": "Structured report with statistics, visualizations, and insights"
}

This configuration file tells the agent its role, the tasks it must complete, the tools it can use, and the limitations it should follow. This is how your project structure should now appear:

gemini-data-agent/
├── sales.csv
├── agent_config.json
└── agent.py (we'll create this in the next step)

We have your data and configuration ready. The next step is to define how the agent should think and behave.

Step 3: Defining the agent’s goal and behavior

Now we need to tell the agent exactly what to do and how to do it. This happens in two parts:

  • The configuration file we just created
  • The system instructions that guide the agent’s behavior

The agent_config.json file already defines the high-level goals. Next, create a new file called agent.py and start with the configuration loader:

import google.generativeai as genai
import json
import os
class DataAnalysisAgent:
def __init__(self, config_path='agent_config.json', api_key=None):
"""Initialize the agent with configuration and API key."""
self.config = self.load_config(config_path)
self.api_key = api_key or os.getenv('GEMINI_API_KEY')
if not self.api_key:
raise ValueError("Gemini API key is required.")
self.setup_gemini()
def load_config(self, config_path):
"""Load agent configuration from JSON file."""
with open(config_path, 'r') as f:
return json.load(f)

Now add the method that builds the system instructions. This is where you define exactly how the agent should approach analysis tasks:

def build_system_instruction(self):
"""Build the system instruction for the Gemini agent."""
instruction = f"""
You are a {self.config['role']}.
Your goal: {self.config['goal']}
Tasks to complete:
{chr(10).join(f"- {task}" for task in self.config['tasks'])}
Available tools: {', '.join(self.config['allowed_tools'])}
Restrictions: {self.config['restrictions']}
Code execution rules:
- Execute Python code silently without showing the code itself
- Use pandas for data manipulation
- Generate clear, actionable insights
- Present results in clean, formatted tables
When analyzing data:
1. Load the CSV file using pandas
2. Calculate comprehensive summary statistics
3. Analyze performance by product and region
4. Identify outliers using statistical methods (IQR)
5. Generate 5-7 key insights in natural language
6. Provide actionable recommendations
IMPORTANT OUTPUT FORMATTING:
- DO NOT show Python code blocks or code execution details
- Show ONLY the results in clean formatted sections with headers
- After tables, provide a comprehensive analysis section with key insights and recommendations
- Use clear section headers and professional formatting
"""
return instruction.strip()

Note: All methods here are part of the DataAnalysisAgent class, so they’re indented with two spaces under the class definition.

These instructions tell the agent:

  • What role does it plays (Data Analysis Agent)
  • What its main goal is (analyze data and generate insights)
  • What specific tasks to complete (load data, calculate stats, find patterns)
  • What tools can it use (code execution and file reading)
  • What restrictions to follow (only access project files, use safe code)
  • How to format the output (clean tables, no code shown, professional structure)

The agent will use these instructions every time it analyzes data. This is like giving the agent a detailed playbook that it follows autonomously.

Step 4: Configuring tools (file access and code execution)

Gemini agents work by calling tools to complete tasks. For data analysis, we need two main tools:

  1. Code execution
  2. File access.

Add this method to your DataAnalysisAgent class:

def setup_gemini(self):
"""Set up Gemini 3 model with tools and system instructions."""
# Configure the API
genai.configure(api_key=self.api_key)
# Create the model with code execution tool
self.model = genai.GenerativeModel(
'gemini-3-pro-preview',
tools='code_execution',
system_instruction=self.build_system_instruction()
)
print("Initializing Gemini 3 Agent...")
print(f"Role: {self.config['role']}")
print(f"Goal: {self.config['goal']}")
print(f"Tools: {', '.join(self.config['allowed_tools'])}")

Note: The method here is a part of the DataAnalysisAgent class, so it is indented with two spaces under the class definition.

Here’s what happens in this setup:

1. API configuration: The genai.configure() call authenticates your connection to Gemini using the API key.

2. Model creation: We initialize the Gemini model with three key components:

  • Model name: gemini-3-pro-preview (the latest Gemini agent model)
  • Tools: code_execution (allows the agent to write and run Python code)
  • System instruction: The detailed behavior guide we created in the previous step

3. Tool safety: Gemini executes code in a sandboxed environment. This means:

  • The agent can only read files you explicitly provide
  • Code runs in isolation without access to your system
  • You control what directories and files the agent can access
  • All operations are logged and transparent

The code_execution tool makes this agent truly autonomous. Instead of just describing what analysis to perform, the agent actually writes Python code, executes it, interprets the results, and generates insights.

Step 5: Writing the agent definition

Now we’ll create the main analysis method that ties everything together. This method takes a CSV file, sends it to Gemini with instructions, and returns the analysis. Add this to your DataAnalysisAgent class:

def analyze_data(self, file_path):
"""Main method to analyze a CSV file using Gemini 3."""
print(f"Analyzing: {file_path}\n")
# Read the CSV file content
with open(file_path, 'r') as f:
csv_content = f.read()
# Create the prompt for analysis
prompt = f"""
I have a CSV file with the following content:
```csv
{csv_content}
```
Analyze this data comprehensively and present results in the following format:
1. Show summary statistics table with headers "--- Summary Statistics for Sales and Quantity ---"
2. Show product performance table with header "--- Performance by Product ---"
3. Show regional performance table with header "--- Performance by Region ---"
4. Show outlier detection results with header "--- Outlier Detection (IQR Method) ---"
5. Provide comprehensive analysis with:
- Data Loading and Quality Verification
- Key Insights (numbered list)
- Actionable Recommendations (numbered list)
Execute Python code to perform analysis but DO NOT show the code itself - only show the formatted results and insights.
Use pandas for analysis and present all tables in clean DataFrame format.
"""
# Send request to Gemini
response = self.model.generate_content(prompt)
# Print the results
print(response.text)
return response.text

Note: This method is a part of the DataAnalysisAgent class, so it is indented with two spaces under the class definition.

Your complete agent definition is now ready. Here’s what this analyze_data() method does:

  • Reads the CSV file content from your local directory
  • Creates a detailed prompt telling Gemini exactly what analysis to perform and how to format it
  • Sends the request to Gemini along with the data
  • Returns the formatted analysis results

The agent now has everything it needs: configuration, system instructions, tool access, and the analysis method.

Step 6: Creating the main execution function

Now let’s create the main function that will run the agent. Add this at the end of your agent.py file (outside the class, with no indentation):

def main():
"""Main execution function."""
print("\nGEMINI 3 DATA ANALYSIS AGENT (Production)\n")
# Initialize agent
agent = DataAnalysisAgent('agent_config.json')
# Run analysis
agent.analyze_data('sales.csv')
if __name__ == "__main__":
main()

This function does three things:

  • Prints a header to show the agent is starting.
  • Creates an agent instance by loading the configuration file we created earlier.
  • Calls analyze_data() with the path to our CSV file.

Step 7: Improving and debugging the agent

What happens when the API key is missing, the CSV file doesn’t exist, or the data has unexpected problems? Without error handling, your agent crashes with cryptic messages. Let’s make it robust.

Wrap your main() function with proper error handling:

def main():
"""Main execution function."""
print("\nGEMINI 3 DATA ANALYSIS AGENT (Production)\n")
# Check for API key
api_key = os.getenv('GEMINI_API_KEY')
if not api_key:
print("ERROR: GEMINI_API_KEY environment variable not set.")
print("\nTo use this agent:")
print("1. Get your API key from: https://ai.google.dev/")
print("2. Set it as environment variable:")
print(" export GEMINI_API_KEY='your-api-key-here'")
return
try:
# Initialize agent
agent = DataAnalysisAgent('agent_config.json')
# Run analysis
agent.analyze_data('sales.csv')
except FileNotFoundError as e:
print(f"Error: File not found - {str(e)}")
print("Make sure sales.csv and agent_config.json exist in the current directory")
except Exception as e:
print(f"Error: {str(e)}")
print("\nMake sure:")
print("1. You have installed: pip install google-generativeai")
print("2. Your API key is valid")
print("3. All required files exist in the current directory")
if __name__ == "__main__":
main()

And there we go, everything is set up correctly!

Step 8: Testing the agent

Now let’s run the agent and see if it gives us the insights. Run the agent from your terminal:

python agent.py

If everything is set up correctly, you’ll see output like this:

GEMINI 3 DATA ANALYSIS AGENT (Production)
Initializing Gemini 3 Agent...
Role: Data Analysis Agent
Goal: Load CSV file, analyze data, and generate actionable insights
Tools: code_execution, file_read
Analyzing: sales.csv
--- Summary Statistics for Sales and Quantity ---
sales quantity
count 15.000000 15.000000
mean 1288.666667 40.800000
std 468.414753 8.993649
min 750.000000 25.000000
25% 890.000000 31.500000
50% 1180.000000 44.000000
75% 1600.000000 47.500000
max 2100.000000 52.000000
--- Performance by Product ---
total_sales average_sales total_quantity average_quantity transaction_count
product
Widget C 7950 1987.500000 198 49.500000 4
Widget A 7180 1196.666667 268 44.666667 6
Widget B 4200 840.000000 146 29.200000 5
--- Performance by Region ---
total_sales average_sales total_quantity average_quantity transaction_count
region
South 5130 1282.500000 161 40.250000 4
North 5050 1262.500000 163 40.750000 4
East 5000 1250.000000 160 40.000000 4
West 4150 1383.333333 128 42.666667 3
--- Outlier Detection (IQR Method) ---
No outliers detected for 'sales' or 'quantity' using the IQR method.
### Data Loading and Quality Verification
The CSV data was successfully loaded into a pandas DataFrame. The dataset contains 15 entries and 5 columns: date, product, sales, region, and quantity. All columns have the correct data types, with sales and quantity as numerical (integers), and date, product, region as objects/strings. There are no missing values in any of the columns, indicating good data quality.
### Key Insights
1. **Product C Leads in Sales and Quantity per Transaction:** Widget C has the highest total sales (7950) and the highest average sales per transaction (1987.50), as well as the highest average quantity sold per transaction (49.50). This suggests it is the most valuable product.
2. **Product B is the Lowest Performer:** Widget B consistently shows the lowest total sales (4200), average sales (840.00), and average quantity sold (29.20) among all products, indicating it is the least performing product.
3. **Product A Has the Most Transactions:** Widget A recorded the highest number of transactions (6), contributing significantly to overall activity, though its average sales and quantity are moderate.
4. **Balanced Regional Sales Distribution:** Total sales are fairly evenly distributed across the regions, with South, North, and East regions showing similar total sales (around 5000-5130). West has slightly lower total sales but also fewer transactions.
5. **West Region Shows Highest Average Sales Per Transaction:** Despite having the fewest transactions (3), the West region boasts the highest average sales per transaction (1383.33) and average quantity per transaction (42.67), suggesting high-value individual transactions.
6. **No Outliers Detected:** The analysis using the IQR method found no significant outliers in 'sales' or 'quantity', indicating a relatively consistent sales pattern within the observed period.
### Actionable Recommendations
1. **Capitalize on Widget C's Success:** Invest more in marketing and production for Widget C, exploring opportunities to expand its market reach or introduce variations, given its high sales value and quantity per transaction.
2. **Improve Widget B's Performance:** Investigate the reasons behind Widget B's lower performance. This could involve price adjustments, marketing campaigns, product improvements, or bundling it with higher-performing products.
3. **Target High-Value Regions:** Analyze the factors contributing to the higher average transaction value in the West region. Replicate successful strategies from the West region, if any, in other regions to boost average sales.
4. **Optimize Regional Strategy based on Transaction Count:** While total sales are similar, the number of transactions differs. For regions with high transaction counts (like North, South, East), focus on increasing average transaction value. For regions with fewer but higher-value transactions (like West), focus on increasing transaction frequency without compromising value.
5. **Monitor Product A's Consistent Performance:** Widget A has the highest transaction count. Ensure consistent supply and customer satisfaction to maintain its steady contribution to overall sales. Consider cross-selling Widget C to Widget A customers.
6. **Conduct Deeper Regional Analysis:** Despite similar total sales, slight differences exist. Further analysis into specific customer demographics, local market trends, or competitive landscape in each region could uncover localized growth opportunities or threats.

The agent has successfully analyzed your data. Here’s what happened behind the scenes:

  • The agent loaded your configuration and understood its role as a data analyst.
  • Gemini read the CSV content and planned the analysis steps autonomously.
  • The agent wrote Python code to calculate statistics, group data by product and region, and detect outliers.
  • Gemini executed the code in a secure sandbox and interpreted the results.
  • The agent synthesized findings into clear insights and business recommendations.

Try it with your own data. Replace sales.csv with any CSV file containing numerical data, and the agent will adapt its analysis to your data structure. You can also modify agent_config.json to change the agent’s goals and get different types of insights.

So, what makes Gemini 3 capable of building agents like this in the first place?

Features of Gemini 3

Here are the key features that make Gemini 3 powerful:

  • Gemini 3 carries out multi-step processes without requiring continuous human supervision. It determines what actions to take, simplifies complicated requests into logical steps, and adjusts when things don’t go as planned.

  • The model has access to external tools such as web search, file reading, code execution, and API calls.

  • In a single request, Gemini 3 handles text, images, PDFs, CSV files, and more.

  • Before taking action, the model develops plans for execution. It describes how to load the file, compute statistics, spot trends, and produce insights when you ask it to analyze sales data.

  • Gemini 3 can read, write, debug, and run code in a variety of languages. It can refactor entire codebases, recognize errors, recommend fixes, and comprehend code context.

These features combine to create an AI that doesn’t just answer questions but actually completes work.

Conclusion

Gemini 3 is Google’s latest multimodal AI model built for autonomous agents that plan tasks, execute code, and deliver results. The data analysis agent you built demonstrates this as it loads data, runs analysis, and generates insights without manual coding. This same approach works for research automation, development tasks, and any workflow where AI needs to complete the work autonomously.

Ready to level up your AI skills? Check out Codecademy’s Learn How to Use ChatGPT course to explore prompt engineering and learn how to get the most out of AI tools in your work.

Frequently asked questions

1. What does Gemini 3 do?

Gemini 3 is an AI model that builds autonomous agents capable of planning tasks, executing code, reading files, and generating structured outputs. It goes beyond answering questions by actually completing workflows like data analysis, research, and coding tasks.

2. Is Gemini 3 free?

Yes, Gemini 3 offers a free tier with rate limits. You get 15 requests per minute and 1,500 requests per day at no cost. For higher usage, paid plans are available with increased quotas and faster response times.

3. Is Gemini better than ChatGPT?

Gemini 3 and ChatGPT excel at different things. Gemini 3 is designed for agentic workflows with tool use and code execution, making it ideal for data analysis and autonomous tasks. ChatGPT focuses on conversational AI and creative content. The best choice depends on your specific use case.

4. Who launched Gemini 3?

Google launched Gemini 3 as part of their Gemini family of AI models developed by Google DeepMind and Google AI teams.

5. What is the Gemini app used for?

The Gemini app provides conversational AI assistance for everyday tasks like writing, learning, planning, and problem-solving. It works across devices and integrates with Google services for productivity and creative work.

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team

Learn more on Codecademy

  • Learn to build stateful AI agents with persistent memory using Letta's MemGPT architecture—designed for developers and ML engineers.
    • Beginner Friendly.
      1 hour
  • Discover the world of data in this fully conceptual course where you will learn how to think about, visualize, and analyze data.
    • Beginner Friendly.
      4 hours
  • BI Data Analysts use Python and SQL to query, analyze, and visualize data — and Tableau and Excel to communicate findings.
    • Includes 18 Courses
    • With Certificate
    • Beginner Friendly.
      50 hours