Python Agent Environment Setup
Before building an AI Agent, we need to set up the appropriate development environment.
Python is the most popular language in AI and machine learning fields, with rich library and tool support.
1. Python Version Selection
For AI Agent development, we recommend using Python 3.9 or higher.
The following versions are common choices:
- Python 3.9: Best stability and compatibility
- Python 3.10: Performance improvements and new features
- Python 3.11+: Latest version with best performance
Note: Some libraries may have specific Python version requirements. Check official documentation.
2. Installing Python
Windows System
- Visit Python official website
- Download latest Python installer (3.9 or higher)
- Run installer, make sure to check Add Python to PATH
- After installation, open CMD or PowerShell and enter:
python --versionto verify installation
macOS System
macOS usually comes with Python pre-installed (possibly outdated). Recommended to use Homebrew:
# Install Homebrew (if not installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install Python
brew install python@3.9
# Verify installation
python3 --version
Linux System
Most Linux distributions come with Python pre-installed. For specific versions:
# Ubuntu/Debian
sudo apt update
sudo apt install python3.9 python3-pip
# CentOS/RHEL
sudo yum install python39 python39-pip
# Verify installation
python3 --version
3. Virtual Environment Configuration
Using virtual environments isolates project dependencies and avoids version conflicts.
Create Virtual Environment
# Create project directory
mkdir ai-agent-project
cd ai-agent-project
Create and activate virtual environment using uv. For more details, see uv tutorial.
Install uv:
pip install uv
Create environment:
# Create virtual environment named .venv (default)
uv venv
# Activate environment (macOS/Linux)
source .venv/bin/activate
# Activate environment (Windows)
.venvScriptsactivate
Alternative tools:
# Using venv (built-in for Python 3.3+)
python -m venv venv
# Or using conda (if Anaconda/Miniconda installed)
conda create -n ai-agent python=3.9
conda activate ai-agent
Activate Virtual Environment
Windows:
venvScriptsactivate
macOS/Linux:
source venv/bin/activate
After activation, command prompt usually shows virtual environment name (e.g., (venv)).
Exit Virtual Environment
deactivate
4. Package Management Tool pip
pip is Python's package manager for installing third-party libraries.
Common Commands:
# Upgrade pip to latest version
pip install --upgrade pip
# Install package
pip install package_name
# Install specific version
pip install package_name==1.2.3
# Install all dependencies from requirements.txt
pip install -r requirements.txt
# List installed packages
pip list
# Generate requirements.txt
pip freeze > requirements.txt
5. Recommended Development Directory Structure
A good project structure helps code management and maintenance:
ai-agent-project/
βββ .env # Environment variables file (not committed to Git)
βββ .gitignore # Git ignore file
βββ requirements.txt # Project dependencies
βββ README.md # Project documentation
βββ src/ # Source code directory
β βββ __init__.py
β βββ agents/ # Agent-related code
β β βββ __init__.py
β β βββ base_agent.py
β β βββ weather_agent.py
β βββ tools/ # Tool definitions
β β βββ __init__.py
β β βββ calculator.py
β β βββ web_search.py
β βββ memory/ # Memory system
β β βββ __init__.py
β β βββ short_term.py
β β βββ vector_memory.py
β βββ utils/ # Utility functions
β βββ __init__.py
β βββ config.py
β βββ logger.py
βββ tests/ # Test code
β βββ __init__.py
β βββ test_agents.py
β βββ test_tools.py
βββ examples/ # Example code
β βββ basic_agent.py
β βββ multi_tool_agent.py
βββ notebooks/ # Jupyter notebooks
βββ experiments.ipynb
Required Library Installation
AI Agent development requires various third-party libraries. Below are installation methods and brief introductions for core libraries.
Core Library Installation
Create a requirements.txt file with the following content:
# Base libraries
python-dotenv>=1.0.0 # Environment variable management
pydantic>=2.0.0 # Data validation and settings management
loguru>=0.7.0 # Logging
# AI/ML related
openai>=1.0.0 # OpenAI API
anthropic>=0.7.0 # Claude API
google-generativeai>=0.3.0 # Gemini API
sentence-transformers>=2.2.0 # Embedding models
chromadb>=0.4.0 # Vector database
# Agent frameworks
langchain>=0.1.0 # LangChain framework
langchain-community>=0.0.10 # LangChain community tools
langchain-openai>=0.0.5 # LangChain OpenAI integration
llama-index>=0.10.0 # LlamaIndex (optional)
semantic-kernel>=0.9.0 # Semantic Kernel (optional)
# Tools and utilities
requests>=2.31.0 # HTTP requests
beautifulsoup4>=4.12.0 # HTML parsing
pandas>=2.0.0 # Data processing
numpy>=1.24.0 # Numerical computing
# Development tools
pytest>=7.4.0 # Testing framework
black>=23.0.0 # Code formatting
flake8>=6.0.0 # Code checking
jupyter>=1.0.0 # Jupyter notebooks
Install all dependencies:
pip install -r requirements.txt
Main Library Introduction
1. LangChain
LangChain is the most popular AI Agent development framework, providing tools for building chain (Chain) and agent (Agent) applications.
# LangChain basic usage example
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
# Initialize LLM
llm = ChatOpenAI(temperature=0.7, model="gpt-3.5-turbo")
# Create tools
tools = [
Tool(
name="Calculator",
func=lambda x: str(eval(x)),
description="Used for mathematical calculations"
)
]
# Create Agent
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
# Run Agent
result = agent.run("Calculate the square root of 25")
print(result)
2. LlamaIndex
LlamaIndex (formerly GPT Index) focuses on document indexing and retrieval, suitable for building document-based Q&A systems.
# LlamaIndex basic usage example
from llama_index import VectorStoreIndex, SimpleDirectoryReader
from llama_index.llms import OpenAI
# Load documents
documents = SimpleDirectoryReader("./data").load_data()
# Create index
index = VectorStoreIndex.from_documents(documents)
# Create query engine
query_engine = index.as_query_engine()
# Query
response = query_engine.query("What AI technologies are mentioned in the documents?")
print(response)
3. Semantic Kernel
Semantic Kernel is a Microsoft framework emphasizing extensibility and enterprise applications.
# Semantic Kernel basic usage example
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAITextCompletion
# Initialize kernel
kernel = sk.Kernel()
api_key = "your-openai-api-key"
kernel.add_text_completion_service(
"dv",
OpenAITextCompletion("text-davinci-003", api_key)
)
# Define skill
skill = kernel.import_semantic_skill_from_directory("./skills", "ExampleSkill")
# Run skill
context = kernel.create_new_context()
context = "Introduce artificial intelligence"
result = skill(context)
print(result)
Installation Verification
Create a verification script verify_installation.py:
Example
# verify_installation.py
import sys
def check_package(package_name, import_name=None):
"""Check if package is installed"""
import_name = import_name or package_name
try:
__import__(import_name)
print(f"{package_name} installed successfully")
return True
except ImportError:
print(f"{package_name} not installed")
return False
def main():
print("Checking AI Agent development environment...")
print("=" * 50)
# Check Python version
python_version = sys.version_info
print(f"Python version: {python_version.major}.{python_version.minor}.{python_version.micro}")
if python_version.major == 3 and python_version.minor >= 9:
print("Python version meets requirements (>=3.9)")
else:
print("Python version does not meet requirements, needs 3.9 or higher")
print("nChecking core libraries...")
# Base libraries
check_package("dotenv", "dotenv")
check_package("pydantic")
check_package("loguru")
# AI/ML libraries
check_package("openai")
check_package("anthropic")
check_package("chromadb")
check_package("sentence_transformers", "sentence_transformers")
# Agent frameworks
check_package("langchain")
check_package("llama_index", "llama_index")
# Utility libraries
check_package("requests")
check_package("pandas")
check_package("numpy")
print("n" + "=" * 50)
print("Environment check complete!")
if __name__ == "__main__":
main()
Run verification:
python verify_installation.py
Common Installation Issues
1. Slow Installation or Timeout
# Use domestic mirror source
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# Or use Aliyun mirror
pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
2. Version Conflicts
# Create new virtual environment
python -m venv new_venv
source new_venv/bin/activate # or venvScriptsactivate
# Reinstall and let pip resolve dependencies
pip install --upgrade pip
pip install langchain openai
3. Platform-specific Issues (e.g., Apple Silicon)
# For Apple Silicon (M1/M2/M3), use specific version
pip install grpcio==1.48.2 # Resolve compatibility issues
# Or use conda
conda install -c conda-forge grpcio
API Key Management
AI Agent development requires access to various API services (e.g., OpenAI, Anthropic, DeepSeek). Secure and effective API Key management is critical.
1. Why Secure API Key Management Matters?
- Prevent leaks: API Key leaks may cause financial loss
- Access control: Use different keys for different environments
- Easy configuration: Unified configuration for team collaboration
- Environment isolation: Use different keys for development, testing, and production
2. Environment Variable Management (Recommended)
Use .env files for sensitive information and exclude them from version control.
Create .env File
# API Keys
OPENAI_API_KEY=sk-your-openai-key
ANTHROPIC_API_KEY=your-claude-key
GOOGLE_API_KEY=your-gemini-key
SERPAPI_API_KEY=your-search-api-key
# Application configuration
APP_ENV=development
LOG_LEVEL=INFO
DEBUG=true
# Database configuration (if used)
VECTOR_DB_PATH=./data/vector_db
MAX_MEMORY_ITEMS=1000
Create .gitignore File
Ensure .env file is not committed to Git:
# Python
__pycache__/
*.py
*$py.class*
*.so
.Python
env/
venv/
ENV/
env.bak/
venv.bak/
# Environment variables
.env
.env.local
.env.*
.local
# Data files
data/*.db
*.sqlite
*.sqlite3
# Logs
logs/*.log
# Editors
.vscode/
.idea/
*.swp
*.swo
Load Environment Variables with python-dotenv
Example
# config.py
import os
from pathlib import Path
from dotenv import load_dotenv
# Load .env file
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
class Config
YouTip