AI Agent Development Guide

Learn to build powerful AI agents for specific tasks

Set Up Your Development Environment

A step-by-step guide to preparing your development environment for AI agent creation

Overview

Setting up a proper development environment is crucial for efficient AI agent development. This guide will walk you through installing the necessary tools, setting up API access, and configuring your workspace for building AI agents with popular frameworks.

Before You Begin

This guide assumes you have basic familiarity with:

  • Command line interfaces (Terminal, Command Prompt, or PowerShell)
  • Python programming fundamentals
  • Package management with pip

Development Environment Checklist

  • Python environment setup (Python 3.9+ recommended)
  • Virtual environment for dependency management
  • Required libraries and frameworks installation
  • API keys and authentication setup
  • Basic project structure
  • Environment variable configuration

Step 1: Install Python

Most AI agent frameworks require Python 3.9 or newer. Here's how to install Python on different operating systems:

Installing Python on Windows

  1. Visit the official Python website
  2. Download the latest Python installer for Windows
  3. Run the installer and check "Add Python to PATH"
  4. Click "Install Now"
  5. Verify installation by opening Command Prompt and typing:
python --version

Alternatively, you can install Python using Windows Package Manager:

winget install Python.Python.3.11

Installing Python on macOS

Option 1: Using Homebrew (recommended):

  1. Install Homebrew if you don't have it already:
  2. /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  3. Install Python using Homebrew:
  4. brew install python

Option 2: Using the installer:

  1. Visit the official Python website
  2. Download the latest macOS installer
  3. Run the installer and follow the instructions

Verify installation by opening Terminal and typing:

python3 --version

Installing Python on Linux

For Ubuntu/Debian:

sudo apt update
sudo apt install python3 python3-pip python3-venv

For Fedora:

sudo dnf install python3 python3-pip

For Arch Linux:

sudo pacman -S python python-pip

Verify installation:

python3 --version

Step 2: Set Up a Virtual Environment

Virtual environments keep your project dependencies isolated, preventing conflicts with other Python projects.

Setting Up a Virtual Environment on Windows

  1. Create a project directory:
  2. mkdir ai-agent-project
    cd ai-agent-project
  3. Create a virtual environment:
  4. python -m venv venv
  5. Activate the virtual environment:
  6. source venv\Scripts\activate

    You should see (venv) at the beginning of your command prompt, indicating that the virtual environment is active.

Setting Up a Virtual Environment on macOS/Linux

  1. Create a project directory:
  2. mkdir ai-agent-project
    cd ai-agent-project
  3. Create a virtual environment:
  4. python3 -m venv venv
  5. Activate the virtual environment:
  6. source venv/bin/activate

    You should see (venv) at the beginning of your command prompt, indicating that the virtual environment is active.

Tip

To deactivate the virtual environment when you're done working on your project, simply run the deactivate command.

Step 3: Install Framework Dependencies

Different AI agent frameworks have their own dependencies. Here's how to install the most popular ones:

Important

Make sure your virtual environment is activated before installing packages.

Option A: Framework-Specific Installation

Installing LangChain

pip install langchain langchain-openai

For additional functionality:

pip install langchain[all]

Common integrations:

pip install langchain-anthropic langchain-community langchain-experimental chroma chromadb

Installing AutoGen

pip install pyautogen

For enhanced functionality:

pip install pyautogen[retrievers,blendsearch]

For OpenAI integrations:

pip install openai

Installing LlamaIndex

pip install llama-index llama-index-llms-openai

For additional integrations:

pip install llama-index-llms-anthropic llama-index-embeddings-openai llama-index-vector-stores-chroma

Installing CrewAI

pip install crewai crewai_tools

For LLM providers:

pip install openai anthropic

Option B: All-in-One Installation

If you want to experiment with multiple frameworks, you can create a requirements.txt file with the following content:

# Core frameworks
langchain>=0.1.0
langchain-openai>=0.0.2
langchain-anthropic>=0.1.1
langchain-community>=0.0.16
pyautogen>=0.2.0
llama-index>=0.9.0
crewai>=0.28.0

# LLM providers
openai>=1.0.0
anthropic>=0.8.0

# Vector stores and embeddings
chromadb>=0.4.18
sentence-transformers>=2.2.2

# Utilities
python-dotenv>=1.0.0
pydantic>=2.5.0
tiktoken>=0.5.0

Then install all dependencies at once:

pip install -r requirements.txt

Tip

Keep your dependencies up-to-date, especially for rapidly evolving frameworks:

pip install --upgrade -r requirements.txt

Step 4: Set Up API Access

Most AI agent frameworks require access to LLM APIs. Here's how to set up the most common ones:

OpenAI API Setup

  1. Create an account on OpenAI's platform
  2. Navigate to the API section
  3. Create an API key
  4. Store your API key securely (see Environment Variables section below)

Anthropic API Setup

  1. Sign up for Anthropic's API access
  2. Once approved, generate an API key from the console
  3. Store your API key securely

Other Providers

Similar processes apply for other providers like:

  • Mistral AI
  • Cohere
  • Google Vertex AI

Security Warning

Never hardcode API keys in your source code or commit them to version control. Always use environment variables or secure key management solutions.

Step 5: Configure Environment Variables

Using environment variables is a secure way to manage API keys and configuration.

Create a .env File

In your project root, create a file named .env with your API keys:

# API Keys
OPENAI_API_KEY=sk-your-openai-key-here
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here

# Configuration
DEFAULT_LLM_MODEL=gpt-4-turbo
VECTOR_DB_PATH=./data/vectorstore

Loading Environment Variables in Your Code

Use the python-dotenv package to load environment variables:

# Import at the top of your main script
from dotenv import load_dotenv
import os

# Load environment variables
load_dotenv()

# Access variables in your code
openai_api_key = os.getenv("OPENAI_API_KEY")
anthropic_api_key = os.getenv("ANTHROPIC_API_KEY")

Add .env to .gitignore

Create a .gitignore file in your project root to prevent committing sensitive information:

# Environment variables
.env

# Virtual environment
venv/

# Python cache
__pycache__/
*.py[cod]
*$py.class

# Distribution / packaging
dist/
build/
*.egg-info/

# Vector stores and local data
data/

Step 6: Set Up Project Structure

A well-organized project structure makes development easier. Here's a recommended structure for AI agent projects:

ai-agent-project/
├── .env                  # Environment variables
├── .gitignore            # Git ignore file
├── README.md             # Project documentation
├── requirements.txt      # Dependencies
├── main.py               # Entry point
├── agents/               # Agent definitions
│   ├── __init__.py
│   ├── base_agent.py
│   └── specialized_agents.py
├── tools/                # Custom tools
│   ├── __init__.py
│   └── tool_definitions.py
├── prompts/              # Prompt templates
│   ├── __init__.py
│   └── templates.py
├── memory/               # Agent memory components
│   ├── __init__.py
│   └── memory_handlers.py
├── data/                 # Data files and vector stores
│   ├── raw/
│   ├── processed/
│   └── vectorstore/
└── tests/                # Test files
    ├── __init__.py
    └── test_agents.py

Create this structure using the following commands:

mkdir agents tools prompts memory data data\raw data\processed data\vectorstore tests
type nul > .env
type nul > .gitignore
type nul > README.md
type nul > requirements.txt
type nul > main.py
type nul > agents\__init__.py
type nul > agents\base_agent.py
type nul > agents\specialized_agents.py
type nul > tools\__init__.py
type nul > tools\tool_definitions.py
type nul > prompts\__init__.py
type nul > prompts\templates.py
type nul > memory\__init__.py
type nul > memory\memory_handlers.py
type nul > tests\__init__.py
type nul > tests\test_agents.py
mkdir -p agents tools prompts memory data/raw data/processed data/vectorstore tests
touch .env .gitignore README.md requirements.txt main.py
touch agents/__init__.py agents/base_agent.py agents/specialized_agents.py
touch tools/__init__.py tools/tool_definitions.py
touch prompts/__init__.py prompts/templates.py
touch memory/__init__.py memory/memory_handlers.py
touch tests/__init__.py tests/test_agents.py

Step 7: Create a Basic Agent Template

To verify your setup, create a simple agent template. Here's an example using LangChain:

main.py

import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain.prompts import ChatPromptTemplate
from langchain.tools import tool

# Load environment variables
load_dotenv()

# Initialize LLM
llm = ChatOpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
    model="gpt-4-turbo"
)

# Define a simple tool
@tool
def calculator(expression: str) -> str:
    """Evaluate a mathematical expression"""
    try:
        return str(eval(expression))
    except Exception as e:
        return f"Error: {str(e)}"

# Define tools list
tools = [calculator]

# Create prompt template
prompt = ChatPromptTemplate.from_template(
    """You are a helpful AI assistant that can use tools to answer questions.
    
    {chat_history}
    Human: {input}
    {agent_scratchpad}
    """
)

# Create agent
agent = create_react_agent(llm, tools, prompt)

# Create agent executor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

def main():
    print("AI Agent initialized! Type 'exit' to quit.")
    
    while True:
        user_input = input("\nYou: ")
        
        if user_input.lower() == 'exit':
            print("Goodbye!")
            break
        
        try:
            response = agent_executor.invoke({"input": user_input})
            print(f"\nAI: {response['output']}")
        except Exception as e:
            print(f"\nError: {str(e)}")

if __name__ == "__main__":
    main()

Testing Your Setup

Run your agent to verify everything is working correctly:

python main.py

Try asking a question that uses the calculator tool, such as:

You: What is 42 * 3.14?

Troubleshooting Common Issues

  • API key errors: Double-check your .env file and ensure it's being loaded correctly
  • Import errors: Verify that all dependencies are installed in your virtual environment
  • Module not found: You may need to install additional packages based on your import statements

Step 8: Version Control Setup

Setting up version control is recommended for tracking changes and collaborating with others:

Initialize Git Repository

git init

Make Initial Commit

git add .gitignore README.md requirements.txt main.py agents/ tools/ prompts/ memory/ tests/
git commit -m "Initial project setup"

Reminder

Make sure your .env file is listed in .gitignore to prevent accidentally committing your API keys.

Create a Simple AI Assistant

Ready to get hands-on? Follow our step-by-step walkthrough to build your first basic AI assistant that can complete tasks independently.

Build Agent