Skip to content

How to Build a Simple AI Agent in Python

Automating repetitive tasks with an AI agent is easier than ever using Python and the Google Gemini API. In this guide, we’ll walk you through creating a simple Python agent capable of interacting with the file system, executing shell commands, and handling errors with automatic retries.

Why Use a Python Agent?

A Python-based agent allows developers to automate tasks such as file management, system commands, or even data processing. By connecting it with AI models like Gemini, your agent can intelligently interpret tasks and perform them with minimal input.

Setting Up Your Python Package

  1. Clone the template: Use the Python package template for a structured and maintainable project.

  2. Dev Containers: Ensure you have Docker installed and use the VS Code Dev Containers extension to run your environment consistently.

  3. Recommended VS Code Extensions: Python, Pylance, Python Debugger, and Dev Containers.

Configuration and API Key

Set your Gemini API key as an environment variable:

GEMINI_API_KEY="YOUR_GEMINI_API_KEY"

Configure your agent in my_package/config.py:

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
gemini_model: str = “gemini-2.5-flash”
initial_backoff_seconds: int = 5
max_backoff_seconds: int = 120

settings = Settings()

These settings allow you to choose the model and configure retry delays.

Using the Agent

Here’s a simple example of how to run tasks with your agent:

import os
from my_package.agent import Agent
api_key = os.getenv(“GEMINI_API_KEY”)
if not api_key:
print(“Error: GEMINI_API_KEY not found.”)
else:
agent = Agent(api_key=api_key)
agent.run_task(“List all files in the current directory and save to ‘file_list.txt’.”)

Features of This Simple AI Agent

  • Interacts with the file system

  • Executes shell commands

  • Automatic retries with exponential backoff

  • Easy configuration via a config.py file

  • PEP8-compliant Python code

Running and Testing

  • Reopen your folder in a Dev Container

  • Run your scripts using VS Code Run & Debug

  • Use the built-in Test Panel for testing

With this setup, you have a fully functional AI agent capable of performing real tasks intelligently, saving time, and automating repetitive workflows.

Leave a Reply

Discover more from Sowft | Transforming Ideas into Digital Success

Subscribe now to keep reading and get access to the full archive.

Continue reading