示例代码总说明¶
本目录是《AI Agent 开发工程师教程》各卷的配套 Python 示例代码集合。所有示例均可独立运行,配套 pytest 单元测试,不依赖外部 API Key 或运行中的服务即可完成测试。
目录结构¶
examples/
├── README.md # 本文件
├── conftest.py # pytest 公共 fixture(mock OpenAI client、临时目录等)
├── volume-01-ai-fundamentals/ # 第1卷:AI 基础
│ ├── hello_agent.py # 简单 Agent 示例(感知-思考-行动循环)
│ ├── token_counter.py # Token 计算与成本估算
│ ├── embedding_demo.py # Embedding 与相似度示例
│ └── test_basics.py
├── volume-02-python/ # 第2卷:Python 进阶
│ ├── async_demo.py # asyncio 异步编程
│ ├── fastapi_app.py # FastAPI + Pydantic 服务示例
│ ├── pydantic_models.py # Pydantic 数据模型
│ └── test_python.py
├── volume-03-openai-api/ # 第3卷:OpenAI API
│ ├── responses_api.py # Responses API 用法
│ ├── streaming.py # 流式响应
│ ├── function_calling.py # 函数调用 / 工具调用
│ └── test_openai.py
├── volume-04-prompt-engineering/ # 第4卷:提示工程
│ ├── system_prompt.py # 系统提示模板
│ ├── few_shot.py # Few-shot 示例
│ ├── structured_output.py # 结构化输出
│ └── test_prompt.py
├── volume-05-agent/ # 第5卷:Agent 开发
│ ├── agent_lifecycle.py # Agent 生命周期
│ ├── tool_execution.py # 工具执行引擎
│ ├── state_memory.py # 状态与记忆管理
│ └── test_agent.py
├── volume-06-rag/ # 第6卷:RAG
│ ├── chunking.py # 文本分块
│ ├── vector_search.py # 向量检索(内存版)
│ ├── hybrid_search.py # 混合检索(向量 + 关键词)
│ └── test_rag.py
├── volume-07-mcp/ # 第7卷:MCP
│ ├── mcp_server.py # MCP Server 概念实现
│ ├── mcp_client.py # MCP Client 概念实现
│ └── test_mcp.py
├── volume-08-langgraph/ # 第8卷:LangGraph
│ ├── hello_graph.py # 图工作流 Hello World
│ ├── state_graph.py # 状态图
│ └── test_langgraph.py
├── volume-09-multi-agent/ # 第9卷:多智能体
│ ├── crewai_demo.py # 多智能体协作(概念实现)
│ └── test_multi_agent.py
├── volume-11-system-design/ # 第11卷:系统设计
│ ├── caching.py # 缓存与限流
│ └── test_system.py
└── volume-12-deployment/ # 第12卷:部署
└── dockerfile_example.py # 容器化部署示例
设计原则¶
- 可离线运行:所有测试均可在无网络、无 API Key、无外部服务(Qdrant / Redis 等)环境下通过。需要外部依赖的部分通过依赖注入或内存实现替代。
- 代码风格统一:Python 3.11+ 语法、完整类型提示、Google 风格 docstring、PEP 8 规范,并通过 ruff 检查。
- 教学导向:每个文件聚焦一个核心概念,包含
if __name__ == "__main__":入口便于单文件学习。 - 可测试:每个示例配 pytest 测试,关键 LLM 调用使用 mock 或可注入的客户端。
依赖安装¶
pip install -r requirements.txt
# 或仅安装测试所需最小依赖:
pip install pytest pytest-asyncio pydantic fastapi httpx numpy
示例默认不真正调用 OpenAI API 以避免费用。如需运行真实调用,请设置环境变量
OPENAI_API_KEY并取消示例中相关注释。
运行示例¶
# 运行单个示例
python examples/volume-01-ai-fundamentals/hello_agent.py
python examples/volume-01-ai-fundamentals/token_counter.py
# 运行 FastAPI 示例(需 uvicorn)
uvicorn examples.volume-02-python.fastapi_app:app --reload
运行测试¶
# 运行全部示例测试
pytest examples/ -v
# 只运行某一卷
pytest examples/volume-01-ai-fundamentals/ -v
# 运行带覆盖率报告
pytest examples/ --cov=examples --cov-report=term-missing
# 跳过集成测试(默认已跳过)
pytest examples/ -m "not integration"
代码风格检查¶
ruff check examples/
black --check examples/
目录约定¶
- 每个子目录对应教程的一卷,目录名采用
volume-NN-主题形式。 - 测试文件统一命名为
test_*.py,与被测示例位于同一目录,使用同级导入(from hello_agent import ...)。 conftest.py位于examples/根目录,提供跨卷复用的 fixture(如fake_openai_client、sample_documents)。