Table of Contents
Learn how to build an AI agent with gemini 3 in 10 minutes with practical instructions, useful tips, and troubleshooting guidance for common issues.
Using the Gemini 3 model, we will create an automated agent that analyzes CSV files. This agent loads data, calculates statistics, identifies trends, and provides recommendations for business actions. Actual business reports, sales dashboards, and any other tasks requiring insights from spreadsheet data can benefit from this approach.
First, let's configure the Gemini toolkit.
Step 1: Install the Gemini 3 Toolkit
Follow these steps to install the Gemini 3 toolkit on your computer:
1. First, install the Gemini SDK. Open the terminal and run the command:
pip install google-generativeai
2. Next, we need the API key, so go to Google's API key page and select 'Create API key' . Name it as required, generate the key, and copy it.
3. Set your API key as an environment variable. For Windows, open PowerShell and run the following command:
$env:GEMINI_API_KEY='English example text'
Mac/Linux users can run the following command:
export GEMINI_API_KEY='English example text'
4. Test your setup with a short Python code snippet:
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 feedback, you're ready to build your agent.
Step 2: Set up the Project Directory
1. Create a working directory for your agent project using the following command in the terminal:
English example text
2. Now, let's create a sample dataset. This CSV file contains sales data across different products and regions. Save this file 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 on date, product (Widget A, B, and C), revenue, region, and quantity sold. This information will be used by the agent to calculate performance metrics, identify trends, and generate business insights.
3. Next, create a configuration file that defines how your agent should behave. Save this file as agent_config.json:
{ "role": "Data Analysis Agent", "goal": "English example text", "tasks": [ "English example text", "English example text", "English example text", "English example text" ], "allowed_tools": ["code_execution", "file_read"], "restrictions": "English example text", "output_format": "English example text" }
This configuration file tells the agent its role, the tasks it must complete, the tools it can use, and the limitations it should adhere to. Your project structure will now look like this:
English example text
We already have the data and configuration ready. The next step is to define how the agent will operate and think.
Step 3: Identify the Agent's Goals 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 was just created.
- The system instructions control the agent's behavior.
The `agent_config.json` file has defined the high-level targets. Next, create a new file named `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'English example text'GEMINI_API_KEY'English example text'r') as f: return json.load(f)
Now, let's add a method for building system commands. This is where you define exactly how the agent should approach analysis tasks:
def build_system_instruction(self): """English example text""" instruction = f"""English example text"- {task}"English example text""" return instruction.strip()
Note : All methods here belong to the DataAnalysisAgent class, so they are indented two spaces below the class definition.
These instructions inform the agent:
- What is its role (Data Analysis Agent)?
- What is its main goal (analyzing data and generating insights)?
- Specific tasks to be completed (loading data, calculating statistics, searching for patterns)
- The tools it can use (to execute code and read files)
- Restrictions to follow (only access project files, use safe code)
- How to format the output (clean table, no code displayed, professional structure)
The agent will use these instructions every time it analyzes data. This is like providing the agent with a detailed manual that it will automatically follow.
Step 4: Configure the Tool (Access Files and Execute Code)
Gemini agents operate by calling tools to complete tasks. For data analysis, we need two main tools:
- Execute code
- Access the file.
Add this method to your DataAnalysisAgent class:
def setup_gemini(self): """English example text"""English example text"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 : This method is part of the DataAnalysisAgent class and is indented two spaces below the class definition.
Here's what happens in this setup:
1. API Configuration : The genai.configure() command authenticates your connection to Gemini using your API key.
2. Creating the Model : We initialize the Gemini model with 3 main components:
- Model name: gemini-3-pro-preview (latest Gemini agent model)
- Tool: code_execution (allows the agent to write and run Python code)
- System instructions: Detailed behavioral instructions that we created in the previous step.
3. Tool safety : Gemini executes code in a sandbox environment. This means:
- The agent can only read files that you explicitly provide.
- The code runs independently without needing to access your system.
- You control the directories and files that the agent can access.
- All operations are logged and transparent.
The code_execution tool makes this agent truly autonomous. Instead of just describing the analysis to be performed, the agent actually writes Python code, executes it, interprets the results, and generates insights.
Step 5: Write the Agent Definition
Now, we'll create the main analysis method that links everything together. This method takes a CSV file, sends it to Gemini along with the instructions, and returns the analysis results. Add this code to your DataAnalysisAgent class:
English example text
Note : This method is part of the DataAnalysisAgent class, so it is indented two spaces below the class definition.
Your complete agent definition is now ready. The `analyze_data()` method performs the following:
- Read the contents of a CSV file from your local directory.
- Create a detailed prompt for Gemini that tells them exactly which analysis to perform and how to format the results.
- Send the request to Gemini along with the data.
- Returns the formatted analysis results.
Now the agent has everything it needs: configuration, system instructions, tool access, and analytical methods.
Step 6: Create the Main Implementation Function
Now, let's create the main function that will run the agent. Add this code to the end of your agent.py file (outside the class, without indentation):
def main(): """English example text""" print("nGEMINI 3 DATA ANALYSIS AGENT (Production)n"English example text"__main__": main()
This function performs three tasks:
- Print the title to show the agent that is starting up.
- Create an agent instance by loading the configuration file we created earlier.
- Call the analyze_data() function with the path to our CSV file.
Step 7: Improve and Debug the Agent
What happens when the API key is missing, the CSV file doesn't exist, or the data unexpectedly gets corrupted? Without error handling mechanisms, your agent will crash with confusing messages. Let's make it more robust.
Wrap your main() function with appropriate error handling:
def main(): """English example text""" print("nGEMINI 3 DATA ANALYSIS AGENT (Production)n"English example text"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'English example text'agent_config.json'English example text'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 that's it, everything is set up correctly!
Step 8: Check the Agent
Now, let's run the agent and see if it provides us with the necessary details. Run the agent from the command line window:
python agent.py
If everything is set up correctly, you will see the following result:
English example text
The agent has successfully analyzed your data. Here's what happened:
- The tool has loaded your configuration and understands its role as a data analyst.
- Gemini read the CSV content and automatically planned the analysis steps.
- The tool used Python code to calculate statistics, group data by product and region, and detect outliers.
- Gemini executed the code in a safe sandbox environment and interpreted the results.
- The tool has synthesized the 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 tool will adjust its analysis to suit your data structure. You can also modify agent_config.json to change the tool's target and get different types of insights.
FAQ
What is the best way to build an ai agent with gemini 3 in 10 minutes?
Learn how to build an AI agent with gemini 3 in 10 minutes with practical instructions, useful tips, and troubleshooting guidance for common issues.
What should you prepare before you build an ai agent with gemini 3 in 10 minutes?
Key takeaway: Learn how to build an AI agent with gemini 3 in 10 minutes with practical instructions, useful tips, and troubleshooting guidance for common issues.
What common mistakes should you avoid?
Using the Gemini 3 model, we will create an automated agent that analyzes CSV files.
Reader Comments 0
Sign in with email or Google to join the discussion.