Ran Wei/ AI Agents/Module 2
中文
AI Agent Series — Ran Wei

Module 2: Environment Setup & API Configuration

Setting up your development environment with Python, API keys, and project structure.

1

Prerequisites

Before building AI agents, you need a properly configured development environment. This module walks you through every step — from installing Python to verifying your first API connection. By the end, you will have a working project scaffold ready for the rest of this tutorial series.

Here is what you need before starting:

NOTE

Both OpenAI and Anthropic offer free trial credits for new accounts. OpenAI typically provides $5–$18 in free credits, and Anthropic provides $5. This is more than enough to complete every exercise in this tutorial series.

Checking Your Python Version

Open a terminal and verify your Python installation:

# Check Python version (must be 3.10 or higher)
python --version
# Output: Python 3.12.4

# On some systems, you may need to use python3
python3 --version

If you do not have Python installed, download it from python.org. On macOS, you can also use brew install python. On Ubuntu/Debian, use sudo apt install python3.

2

Install Dependencies

We strongly recommend using a virtual environment to isolate your project dependencies. This prevents version conflicts between different Python projects on your machine.

Create a Virtual Environment

# Create project directory
mkdir ai-agent-tutorial
cd ai-agent-tutorial

# Create a virtual environment
python -m venv venv

# Activate it (macOS / Linux)
source venv/bin/activate

# Activate it (Windows)
venv\Scripts\activate

# You should see (venv) in your terminal prompt

Install the Required Packages

# Install all dependencies at once
pip install openai anthropic python-dotenv

# Verify installation
pip list | grep -E "openai|anthropic|dotenv"

This installs three packages:

PackagePurposeVersion (as of 2026)
openaiOfficial OpenAI Python SDK — provides the client for GPT-4o, o3, etc.1.x+
anthropicOfficial Anthropic Python SDK — provides the client for Claude Sonnet/Opus0.40+
python-dotenvLoads environment variables from a .env file — keeps secrets out of code1.x+
TIP

Pin your dependency versions in a requirements.txt file for reproducibility. Run pip freeze > requirements.txt after installing. This way, anyone cloning your project can run pip install -r requirements.txt and get the exact same environment.

3

Project Structure

A well-organised project structure will save you headaches as your agent grows in complexity. Here is the structure we will build throughout this tutorial series:

ai-agent-tutorial/
├── .env                 # API keys (NEVER commit this file!)
├── .gitignore           # Must include .env
├── requirements.txt     # Pinned dependencies
├── config.py            # Centralised configuration
├── agent_openai.py      # OpenAI-based agent implementation
├── agent_anthropic.py   # Anthropic-based agent implementation
├── tools.py             # Tool definitions and implementations
├── memory.py            # Memory management (short + long term)
├── evaluator.py         # Agent evaluation and testing
└── main.py              # Entry point

Each file has a clear responsibility. This separation of concerns makes it easy to swap components — for example, switching from OpenAI to Anthropic by changing one import.

Create the .gitignore File

If you are using Git (you should be), create a .gitignore immediately to prevent accidentally committing sensitive files:

# .gitignore
.env
venv/
__pycache__/
*.pyc
.DS_Store
PITFALL

Create your .gitignore before your first commit. If you accidentally commit a .env file with API keys, the keys are in your Git history forever (even if you delete the file later). If this happens, immediately rotate your API keys on the provider's dashboard.

4

Configure API Keys

API keys are how OpenAI and Anthropic identify and bill your account. They are secrets that must never appear in your source code, commit history, or public repositories.

Getting Your API Keys

OpenAI: Go to platform.openai.com/api-keys, click "Create new secret key", give it a name, and copy the key. You will only see it once.

Anthropic: Go to console.anthropic.com/settings/keys, click "Create Key", name it, and copy. Same rule — you will only see it once.

Store Keys in a .env File

Create a .env file in your project root. This file is loaded at runtime but never committed to version control:

# .env
OPENAI_API_KEY=sk-proj-your-key-here
ANTHROPIC_API_KEY=sk-ant-your-key-here
WARNING

Never hard-code API keys directly in your Python files. Never share them in chat messages, screenshots, or documentation. If a key is compromised, anyone can make API calls billed to your account.

Alternative: System Environment Variables

For production deployments, you may prefer to set keys as system environment variables rather than using a .env file:

# macOS / Linux (add to ~/.bashrc or ~/.zshrc for persistence)
export OPENAI_API_KEY="sk-proj-your-key-here"
export ANTHROPIC_API_KEY="sk-ant-your-key-here"

# Windows PowerShell
$env:OPENAI_API_KEY="sk-proj-your-key-here"
$env:ANTHROPIC_API_KEY="sk-ant-your-key-here"
NOTE

Both the OpenAI and Anthropic Python SDKs automatically look for OPENAI_API_KEY and ANTHROPIC_API_KEY environment variables. If these are set, you do not need to pass the key explicitly when creating a client.

5

Load Keys in Python

Now let us write a configuration module that loads and validates your API keys. This pattern ensures you catch missing keys early, before any API calls are attempted.

Basic Key Loading

# config.py
import os
from dotenv import load_dotenv

# Load variables from .env file into environment
load_dotenv()

# Read keys from environment
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")

# Validate - fail fast if keys are missing
assert OPENAI_API_KEY, "Missing OPENAI_API_KEY in .env file"
assert ANTHROPIC_API_KEY, "Missing ANTHROPIC_API_KEY in .env file"

print("API keys loaded successfully.")

Verifying Your Connection

Before moving to the next module, let us verify that your keys work by making a minimal API call to each provider:

# verify_setup.py
import os
from dotenv import load_dotenv
from openai import OpenAI
import anthropic

load_dotenv()

# --- Test OpenAI ---
print("Testing OpenAI connection...")
oai_client = OpenAI()  # Automatically reads OPENAI_API_KEY
response = oai_client.chat.completions.create(
    model="gpt-4o-mini",   # Use the cheapest model for testing
    messages=[{"role": "user", "content": "Say 'hello' and nothing else."}],
    max_tokens=10
)
print(f"  OpenAI response: {response.choices[0].message.content}")

# --- Test Anthropic ---
print("Testing Anthropic connection...")
ant_client = anthropic.Anthropic()  # Automatically reads ANTHROPIC_API_KEY
message = ant_client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=10,
    messages=[{"role": "user", "content": "Say 'hello' and nothing else."}]
)
print(f"  Anthropic response: {message.content[0].text}")

print("\nAll connections verified! Your environment is ready.")

Run this file:

python verify_setup.py
# Expected output:
# Testing OpenAI connection...
#   OpenAI response: hello
# Testing Anthropic connection...
#   Anthropic response: hello
# All connections verified! Your environment is ready.
TIP

We used gpt-4o-mini for the OpenAI test instead of gpt-4o because it is significantly cheaper. For verification purposes, any model will do. Save the expensive models for when you actually need their reasoning capabilities.

Troubleshooting Common Errors

Error MessageCauseFix
AuthenticationErrorInvalid or expired API keyRegenerate key on provider dashboard
RateLimitErrorToo many requests or no creditsWait, add billing info, or reduce request rate
ModuleNotFoundError: No module named 'openai'Package not installed or wrong Python environmentActivate your venv, then pip install openai
AssertionError: Missing OPENAI_API_KEY.env file missing or key not setCheck .env exists in the right directory and contains the key

A Robust Configuration Module

For a production-quality setup, use a configuration class that handles multiple environments (development, testing, production) and provides sensible defaults:

# config.py - production-quality configuration
import os
from dataclasses import dataclass
from dotenv import load_dotenv

load_dotenv()

@dataclass
class Config:
    """Centralised configuration for the AI agent project."""
    openai_api_key: str = ""
    anthropic_api_key: str = ""
    default_provider: str = "anthropic"  # or "openai"
    default_model: str = "claude-sonnet-4-20250514"
    max_tokens: int = 1024
    temperature: float = 0.0
    max_agent_steps: int = 10
    log_file: str = "agent_log.jsonl"

    @classmethod
    def from_env(cls) -> "Config":
        """Load configuration from environment variables."""
        return cls(
            openai_api_key=os.getenv("OPENAI_API_KEY", ""),
            anthropic_api_key=os.getenv("ANTHROPIC_API_KEY", ""),
            default_provider=os.getenv("DEFAULT_PROVIDER", "anthropic"),
            max_agent_steps=int(os.getenv("MAX_AGENT_STEPS", "10")),
        )

    def validate(self) -> list[str]:
        """Return a list of configuration errors (empty = all good)."""
        errors = []
        if not self.openai_api_key:
            errors.append("OPENAI_API_KEY is not set")
        if not self.anthropic_api_key:
            errors.append("ANTHROPIC_API_KEY is not set")
        return errors

# Usage
config = Config.from_env()
errors = config.validate()
if errors:
    print("Configuration errors:")
    for e in errors:
        print(f"  - {e}")
else:
    print("Configuration OK")
NOTE

Using a Config dataclass gives you a single source of truth for all agent settings. When you later add parameters like max_agent_steps or temperature, they live in one place rather than being scattered across multiple files. This becomes invaluable as your project grows.

VS Code Recommended Extensions

If you are using VS Code, install these extensions for the best development experience with AI agent projects:

Python

Microsoft's official extension. Provides IntelliSense, linting, debugging, and Jupyter support.

Pylance

Advanced type checking and auto-completion. Catches type errors in tool definitions and API calls.

Python Dotenv

Syntax highlighting for .env files. Makes it easy to spot formatting errors in your keys.

REST Client

Test API endpoints directly from VS Code. Useful for debugging tool implementations.

Up Next

Module 3 — Prompt Engineering