Runoob Tutorial ArchiveEnglish

Python Agent Environment Configuration

Python Agent Environment Configuration

Before starting to build an AI Agent, we need to set up a suitable development environment.

Python is the most popular language in the field of AI and machine learning, with rich library and tool support.

1. Python Version Selection

For AI Agent development, we recommend usingPython 3.9 or higher version.

The following versions are common choices:

NoteSome libraries may have specific requirements for the Python version; please refer to the official documentation.

2. Install Python

Windows system

macOS system

macOS usually comes pre-installed with Python, but it might be an old version. It is recommended to install using Homebrew:

Original prompt (Chinese, left untranslated)

# 安装 Homebrew(如果尚未安装)

/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 pre-installed with Python. If a specific version is required:

Original prompt (Chinese, left untranslated)

# 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 a virtual environment can isolate dependencies of different projects, avoiding version conflicts.

Create a virtual environment

Original prompt (Chinese, left untranslated)

# 创建项目目录

mkdir ai-agent-project

cd ai-agent-project

Use uv to create and activate a virtual environment; more related content can be read at uv Tutorial.

Install uv

pip install uv

Use the uv command to create:

Original prompt (Chinese, left untranslated)

# 创建名为 .venv 的虚拟环境(默认)

uv venv



# Activate environment (macOS/Linux)

source .venv/bin/activate



# Activate environment (Windows)

.venv\Scripts\activate

Other tools:

Original prompt (Chinese, left untranslated)



# Using venv, built-in Python 3.3+

python -m venv venv



# or use conda (if Anaconda/Miniconda is installed)

conda create -n ai-agent python=3.9

conda activate ai-agent

Activate the virtual environment

Windows:



venv\Scripts\activate

** macOS/Linux:**



source venv/bin/activate

After activation, the command prompt usually displays the virtual environment name (e.g., (venv)).

Deactivate virtual environment



deactivate

4. Package management tool pip

pip is Python's package management tool used to install third-party libraries.

Common commands:

Original prompt (Chinese, left untranslated)

# 升级 pip 到最新版本

pip install --upgrade pip



# 安装包

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 with code management and maintenance:

Original prompt (Chinese, left untranslated)

ai-agent-project/

├── .env                    # 环境变量文件(不提交到Git)

├── .gitignore             # Git忽略文件

├── requirements.txt       # 项目依赖

├── README.md             # 项目说明

├── src/                  # 源代码目录

│   ├── __init__.py

│   ├── agents/          # Agent相关代码

│   │   ├── __init__.py

│   │   ├── base_agent.py

│   │   └── weather_agent.py

│   ├── tools/           # 工具定义

│   │   ├── __init__.py

│   │   ├── calculator.py

│   │   └── web_search.py

│   ├── memory/          # 记忆系统

│   │   ├── __init__.py

│   │   ├── short_term.py

│   │   └── vector_memory.py

│   └── utils/           # 工具函数

│       ├── __init__.py

│       ├── config.py

│       └── logger.py

├── tests/               # 测试代码

│   ├── __init__.py

│   ├── test_agents.py

│   └── test_tools.py

├── examples/            # 示例代码

│   ├── basic_agent.py

│   └── multi_tool_agent.py

└── notebooks/           # Jupyter笔记本

    └── experiments.ipynb


Required Library Installation

AI Agent development requires support from a series of third-party libraries. The installation methods and brief introductions of the core libraries are as follows.

Core Library Installation

Createrequirements.txta file containing the following content:

Original prompt (Chinese, left untranslated)

# 基础库

python-dotenv>=1.0.0      # 环境变量管理

pydantic>=2.0.0           # 数据验证和设置管理

loguru>=0.7.0             # 日志记录



# 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 模型

chromadb>=0.4.0           # 向量数据库



# Agent Framework

langchain>=0.1.0          # LangChain 框架

langchain-community>=0.0.10 # LangChain 社区工具

langchain-openai>=0.0.5   # LangChain OpenAI 集成

llama-index>=0.10.0       # LlamaIndex(可选)

semantic-kernel>=0.9.0    # Semantic Kernel(可选)



# Tools and utilities

requests>=2.31.0          # HTTP 请求

beautifulsoup4>=4.12.0    # HTML 解析

pandas>=2.0.0             # 数据处理

numpy>=1.24.0             # 数值计算



# Development Tools

pytest>=7.4.0             # 测试框架

black>=23.0.0             # 代码格式化

flake8>=6.0.0             # 代码检查

jupyter>=1.0.0            # Jupyter 笔记本

Install all dependencies:

pip install -r requirements.txt

Introduction to Main Libraries

1. LangChain

LangChain is the most popular AI Agent development framework, providing tools to build Chain and Agent applications.

Original prompt (Chinese, left untranslated)

# LangChain 基本使用示例

from langchain.llms import OpenAI

from langchain.chat_models import ChatOpenAI

from langchain.agents import initialize_agent, AgentType

from langchain.tools import Tool



# 初始化 LLM

llm = ChatOpenAI(temperature=0.7, model="gpt-3.5-turbo")



# Create tool

tools = [

    Tool(

        name="Calculator",

        func=lambda x: str(eval(x)),

        description="用于数学计算"

    )

]



# Create Agent

agent = initialize_agent(

    tools=tools,

    llm=llm,

    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,

    verbose=True

)



# Run Agent

result = agent.run("计算 25 的平方根")

print(result)

2. LlamaIndex

LlamaIndex (formerly GPT Index) focuses on document indexing and retrieval, suitable for building document-based Q&A systems.

Original prompt (Chinese, left untranslated)

# LlamaIndex 基本使用示例

from llama_index import VectorStoreIndex, SimpleDirectoryReader

from llama_index.llms import OpenAI



# Load document

documents = SimpleDirectoryReader("./data").load_data()



# Create index

index = VectorStoreIndex.from_documents(documents)



# Create query engine

query_engine = index.as_query_engine()



# 查询

response = query_engine.query("文档中提到了哪些AI技术?")

print(response)

3. Semantic Kernel

Semantic Kernel is a framework launched by Microsoft, emphasizing extensibility and enterprise-grade applications.

Original prompt (Chinese, left untranslated)

# Semantic Kernel 基本使用示例

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 skills

skill = kernel.import_semantic_skill_from_directory("./skills", "ExampleSkill")



# Run skill

context = kernel.create_new_context()

context["input"] = "介绍一下人工智能"

result = skill["Summarize"](context)

print(result)

Installation verification

Create a verification scriptverify_installation.py:

Instance

verify_installation.py

import

sys

def

check_package

(

package_name

,

import_name

=

None

)

:

   

"""Check if the 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} is 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 the requirements, requires 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 framework

check_package

(

"langchain"

)

check_package

(

"llama_index"

,

"llama_index"

)

   

Tool library

check_package

(

"requests"

)

check_package

(

"pandas"

)

check_package

(

"numpy"

)

   

print

(

"\n"

"="

50

)

   

print

(

"Environment check completed!"

)

if

name

==

"main"

:

    main

(

)

Run verification:

python verify_installation.py

Common installation issues resolution

1. Slow installation speed or timeout

Original prompt (Chinese, left untranslated)

# 使用国内镜像源

pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple



# or use Alibaba Cloud mirror

pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/

2. Version conflict

Original prompt (Chinese, left untranslated)

# 创建新的虚拟环境

python -m venv new_venv

source new_venv/bin/activate  # 或 venv\Scripts\activate



# Reinstall, letting pip automatically resolve dependencies

pip install --upgrade pip

pip install langchain openai

3. Specific platform issues (e.g., Apple Silicon)

Original prompt (Chinese, left untranslated)

# 对于 Apple Silicon (M1/M2/M3),可能需要特定版本

pip install grpcio==1.48.2  # 解决某些兼容性问题



# or use conda

conda install -c conda-forge grpcio


API Key management

Developing AI Agents requires accessing various API services (such as OpenAI, Anthropic, DeepSeek, etc.), and securely and effectively managing API Keys is crucial.

1. Why is secure API Key management necessary?

2. Environment Variable Management (Recommended)

Use.envfiles to manage sensitive information, and do not commit them to the version control system.

Create.envfile

Original prompt (Chinese, left untranslated)

# API Keys

OPENAI_API_KEY=sk-你的OpenAI密钥

ANTHROPIC_API_KEY=你的Claude密钥

GOOGLE_API_KEY=你的Gemini密钥

SERPAPI_API_KEY=你的搜索API密钥



# 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.gitignoreFiles

Ensure.envfiles are not committed to Git:

Original prompt (Chinese, left untranslated)

# Python

__pycache__/

*.py[cod]

*$py.class

*.so

.Python

env/

venv/

ENV/

env.bak/

venv.bak/



# Environment variables

.env

.env.local

.env.*.local



# Data file

data/

*.db

*.sqlite

*.sqlite3



# 日志

logs/

*.log



# 编辑器

.vscode/

.idea/

*.swp

*.swo

Use python-dotenv to load environment variables

Instance

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:

   

"""Application configuration"""

   

API Keys

OPENAI_API_KEY

=

os

.

getenv

(

"OPENAI_API_KEY"

)

    ANTHROPIC_API_KEY

=

os

.

getenv

(

"ANTHROPIC_API_KEY"

)

GOOGLE_API_KEY

=

os

.

getenv

(

"GOOGLE_API_KEY"

)

SERPAPI_API_KEY

=

os

.

getenv

(

"SERPAPI_API_KEY"

)

   

Application configuration

APP_ENV

=

os

.

getenv

(

"APP_ENV"

,

"development"

)

LOG_LEVEL

=

os

.

getenv

(

"LOG_LEVEL"

,

"INFO"

)

DEBUG

=

os

.

getenv

(

"DEBUG"

,

"false"

)

.

lower

(

)

==

"true"

   

Database configuration

VECTOR_DB_PATH

=

os

.

getenv

(

"VECTOR_DB_PATH"

,

"./data/vector_db"

)

MAX_MEMORY_ITEMS

=

int

(

os

.

getenv

(

"MAX_MEMORY_ITEMS"

,

"1000"

)

)

   

@

classmethod

   

def

validate

(

cls

)

:

       

"""Validate necessary configurations"""

missing

=

[

]

       

if

not

cls.

OPENAI_API_KEY

:

missing.

append

(

"OPENAI_API_KEY"

)

       

if

missing:

           

raise

ValueError

(

f

"Missing required environment variables: {', '.join(missing)}"

)

Usage example

config

=

Config

(

)

print

(

f

"Environment: {config.APP_ENV}"

)

print

(

f

"Debug mode: {config.DEBUG}"

)

3. Securely use API Key

Use environment variables in code

Original prompt (Chinese, left untranslated)

import os

from openai import OpenAI



# Read API Key from environment variable

api_key = os.getenv("OPENAI_API_KEY")



if not api_key:

    raise ValueError("OPENAI_API_KEY 环境变量未设置")



# Initialize OpenAI client

client = OpenAI(api_key=api_key)



# Use client

response = client.chat.completions.create(

    model="gpt-3.5-turbo",

    messages=[{"role": "user", "content": "你好"}]

)

Use configuration class

instance

from

langchain.

llms

import

OpenAI

from

langchain.

chat_models

import

ChatOpenAI

from

config

import

Config

class

LLMClientFactory:

   

"""LLM Client Factory"""

   

@

staticmethod

   

def

create_openai_client

(

model

=

"gpt-3.5-turbo"

,

**kwargs

)

:

       

"""Create OpenAI client"""

Config.

validate

(

)

 

Validate configuration

       

return

ChatOpenAI

(

model

=

model

,

openai_api_key

=

Config.

OPENAI_API_KEY

,

temperature

=

kwargs.

get

(

"temperature"

,

0.7

)

,

max_tokens

=

kwargs.

get

(

"max_tokens"

,

1000

)

       

)

   

@

staticmethod

   

def

create_anthropic_client

(

model

=

"claude-3-sonnet-20240229"

,

**kwargs

)

:

       

"""Create Anthropic client"""

       

from

langchain.

chat_models

import

ChatAnthropic

Config.

validate

(

)

       

return

ChatAnthropic

(

model

=

model

,

anthropic_api_key

=

Config.

ANTHROPIC_API_KEY

,

temperature

=

kwargs.

get

(

"temperature"

,

0.7

)

,

max_tokens

=

kwargs.

get

(

"max_tokens"

,

1000

)

       

)

Usage Example

llm

=

LLMClientFactory.

create_openai_client

(

)

response

=

llm.

predict

(

"Hello, please introduce yourself"

)

print

(

response

)

4. Multi-environment Configuration

For large projects, different environment configurations may be required:

Environment-specific.envFiles

Original prompt (Chinese, left untranslated)

# .env.development (开发环境)

OPENAI_API_KEY=sk-dev-key

APP_ENV=development

DEBUG=true



# .env.production (production environment)

OPENAI_API_KEY=sk-prod-key

APP_ENV=production

DEBUG=false

Dynamic loading of environment configuration

Original prompt (Chinese, left untranslated)

# config_manager.py

import os

from pathlib import Path

from dotenv import load_dotenv



class ConfigManager:

    """配置管理器"""



    def __init__(self, env=None):

        self.env = env or os.getenv("APP_ENV", "development")

        self.load_config()



    def load_config(self):

        """加载配置"""

        # Load general configuration

        load_dotenv(dotenv_path=Path('.') / '.env')



        # Load environment-specific configuration

        env_file = Path('.') / f'.env.{self.env}'

        if env_file.exists():

            load_dotenv(dotenv_path=env_file, override=True)



        # Load local override configuration (not committed to Git)

        local_file = Path('.') / f'.env.{self.env}.local'

        if local_file.exists():

            load_dotenv(dotenv_path=local_file, override=True)



    def get(self, key, default=None):

        """获取配置值"""

        return os.getenv(key, default)



# Usage example

config = ConfigManager(env="development")

print(f"当前环境: {config.get('APP_ENV')}")

print(f"API Key: {config.get('OPENAI_API_KEY')[:10]}...")  # 只显示前10个字符

5. Key rotation and monitoring

For production environments, it is recommended to implement key rotation and monitoring:

Original prompt (Chinese, left untranslated)

# key_manager.py

import os

import time

from datetime import datetime, timedelta



class APIKeyManager:

    """API Key 管理器"""



    def __init__(self):

        self.keys = {}

        self.key_history = []

        self.load_keys()



    def load_keys(self):

        """加载 API Keys"""

        # Can be loaded from environment variables, database, or key management service

        self.keys = {

            "openai": {

                "current": os.getenv("OPENAI_API_KEY"),

                "previous": os.getenv("OPENAI_API_KEY_PREVIOUS"),

                "created_at": datetime.now(),

                "rotation_days": 30  # 30天轮换一次

            },

            "anthropic": {

                "current": os.getenv("ANTHROPIC_API_KEY"),

                "previous": None,

                "created_at": datetime.now(),

                "rotation_days": 30

            }

        }



    def get_key(self, service):

        """获取当前可用的 Key"""

        key_info = self.keys.get(service)

        if not key_info:

            raise ValueError(f"未配置服务 {service} 的 API Key")



        # Check if rotation is needed

        if self.should_rotate(key_info):

            self.rotate_key(service)



        return key_info["current"]



    def should_rotate(self, key_info):

        """检查是否需要轮换 Key"""

        rotation_days = key_info.get("rotation_days", 30)

        created_at = key_info.get("created_at", datetime.now())



        age = datetime.now() - created_at

        return age.days >= rotation_days



    def rotate_key(self, service):

        """轮换 API Key"""

        # In a real application, a new Key would be fetched from the key management service here

        print(f"轮换 {service} 的 API Key...")



        key_info = self.keys[service]

        key_info["previous"] = key_info["current"]

        # Should get new Key from a secure place

        # key_info["current"] = get_new_key_from_vault(service)

        key_info["created_at"] = datetime.now()



        # Record history

        self.key_history.append({

            "service": service,

            "rotated_at": datetime.now(),

            "old_key": key_info["previous"][:10] + "..." if key_info["previous"] else None

        })



# Usage example

key_manager = APIKeyManager()

openai_key = key_manager.get_key("openai")

print(f"OpenAI Key: {openai_key[:10]}...")


Recommended development tools

Choosing appropriate development tools can greatly improve development efficiency. Here are some recommended development tools.

1. Code editor/IDE

Visual Studio Code (Recommended)

Download address:https://code.visualstudio.com/

Recommended extensions:

VS Code configuration(.vscode/settings.json):

{

    "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python",

    "python.terminal.activateEnvironment": true,

    "python.linting.enabled": true,

    "python.linting.pylintEnabled": false,

    "python.linting.flake8Enabled": true,

    "python.formatting.provider": "black",

    "python.formatting.blackArgs": [

        "--line-length",

        "88"

    ],

    "python.testing.pytestEnabled": true,

    "[python]": {

        "editor.formatOnSave": true,

        "editor.codeActionsOnSave": {

            "source.organizeImports": "always"

        }

    },

    "files.exclude": {

        "**/__pycache__": true,

        "**/.pytest_cache": true,

        "**/.venv": true,

        "**/venv": true

    }

}

PyCharm (Professional)

Download address:https://www.jetbrains.com/pycharm/

Features:

2. Version Control: Git

Git is an essential version control tool.

Basic Configuration:

Original prompt (Chinese, left untranslated)

# 配置用户信息

git config --global user.name "你的姓名"

git config --global user.email "你的邮箱"



# Configure default editor (optional)

git config --global core.editor "code --wait"



# Create Git repository

cd ai-agent-project

git init



# Add all files

git add .



# 提交

git commit -m "初始提交:AI Agent 项目"



# Connect to a remote repository (e.g., GitHub)

git remote add origin https://github.com/你的用户名/ai-agent-project.git

git branch -M main

git push -u origin main

3. Debugging Tools

Python Debugger (pdb)

Original prompt (Chinese, left untranslated)

# 在代码中插入断点

import pdb



def complex_function(x):

    pdb.set_trace()  # 这里会进入调试器

    result = x * 2

    return result



# Common pdb commands:

# n(ext) - execute next line

# s(tep) - Enter function

# c(ontinue) - continue execution

# l(ist) - Show code

# p(rint) - print variable value

# q(uit) - exit debugger

VS Code Debug Configuration

.vscode/launch.json:

Original prompt (Chinese, left untranslated)

{

    "version": "0.2.0",

    "configurations": [

        {

            "name": "Python: 当前文件",

            "type": "python",

            "request": "launch",

            "program": "${file}",

            "console": "integratedTerminal",

            "justMyCode": true,

            "envFile": "${workspaceFolder}/.env"

        },

        {

            "name": "Python: 测试",

            "type": "python",

            "request": "launch",

            "program": "${workspaceFolder}/tests",

            "console": "integratedTerminal",

            "justMyCode": true,

            "envFile": "${workspaceFolder}/.env"

        }

    ]

}

4. Testing Tools

pytest

Original prompt (Chinese, left untranslated)

# tests/test_agent.py

import pytest

from src.agents.base_agent import BaseAgent



def test_agent_initialization():

    """测试 Agent 初始化"""

    agent = BaseAgent(name="Test Agent")

    assert agent.name == "测试Agent"

    assert agent.messages == []



def test_agent_add_message():

    """测试添加消息"""

    agent = BaseAgent()

    agent.add_message("user", "你好")



    assert len(agent.messages) == 1

    assert agent.messages[0]["role"] == "user"

    assert agent.messages[0]["content"] == "你好"

Run tests:

Original prompt (Chinese, left untranslated)

# 运行所有测试

pytest



# Run specific test file

pytest tests/test_agent.py



# Run specific test function

pytest tests/test_agent.py::test_agent_initialization



# Show detailed output

pytest -v



# Show coverage report

pytest --cov=src

5. Code Quality and Formatting

black (code formatting)

Original prompt (Chinese, left untranslated)

# 格式化所有 Python 文件

black .



# Check which files need formatting

black --check .



# Format a single file

black src/agents/base_agent.py

flake8 (code checking)

Original prompt (Chinese, left untranslated)

# 检查代码质量

flake8 src/



# Ignore specific errors

flake8 --ignore=E501,W503 src/



# Display error statistics

flake8 --statistics src/

pre-commit (Git hooks)

Create.pre-commit-config.yaml:

repos:

  - repo: https://github.com/pre-commit/pre-commit-hooks

    rev: v4.5.0

    hooks:

      - id: trailing-whitespace

      - id: end-of-file-fixer

      - id: check-yaml

      - id: check-added-large-files



  - repo: https://github.com/psf/black

    rev: 23.12.1

    hooks:

      - id: black



  - repo: https://github.com/pycqa/flake8

    rev: 6.1.0

    hooks:

      - id: flake8

        args: [--max-line-length=88]

Install pre-commit:

pip install pre-commit

pre-commit install

6. Documentation Tools

Jupyter Notebook

For experiments and documentation:

Original prompt (Chinese, left untranslated)

# 启动 Jupyter

jupyter notebook



# or use JupyterLab

jupyter lab

MkDocs (documentation generation)

Createdocs/directory andmkdocs.yml:

Original prompt (Chinese, left untranslated)

site_name: AI Agent 项目文档

site_url: https://your-project.com

nav:

  - 首页: index.md

  - API文档: api.md

  - 使用指南: guide.md

theme: readthedocs

Generate documentation:

Original prompt (Chinese, left untranslated)

# 安装 MkDocs

pip install mkdocs mkdocs-material



# Local preview

mkdocs serve



# Build documentation

mkdocs build

7. Containerization Tools (Optional)

Docker

Dockerfile:

Original prompt (Chinese, left untranslated)

FROM python:3.9-slim



WORKDIR /app



# Copy dependency files

COPY requirements.txt .



# Install dependencies

RUN pip install --no-cache-dir -r requirements.txt



# Copy application code

COPY src/ ./src/

COPY .env.example .env



# Set environment variables

ENV PYTHONPATH=/app



# Run application

CMD ["python", "src/main.py"]

docker-compose.yml:

version: '3.8'



services:

  ai-agent:

    build: .

    ports:

      - "8000:8000"

    environment:

      - OPENAI_API_KEY=${OPENAI_API_KEY}

    volumes:

      - ./data:/app/data

      - ./logs:/app/logs

8. Monitoring and Logging

loguru (logging library)

Original prompt (Chinese, left untranslated)

from loguru import logger

import sys



# Configure logging

logger.remove()  # 移除默认处理器

logger.add(

    sys.stderr,

    format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",

    level="INFO"

)



logger.add(

    "logs/app_{time}.log",

    rotation="500 MB",  # 每500MB轮转

    retention="30 days",  # 保留30天

    compression="zip",  # 压缩旧日志

    level="DEBUG"

)



# Use logging

logger.info("应用启动")

logger.debug(f"配置加载: {config}")

logger.error("API调用失败", exc_info=True)