Skip to content

项目结构建议

构建 LangChain 应用时,良好的项目结构能显著提升代码的可维护性、可测试性和可扩展性。本文档推荐几种经过实践验证的项目布局方式。

基础结构

对于一个典型的 LangChain Agent 应用,推荐以下目录结构:

my-agent/
├── agent.py              # Agent 定义与入口
├── tools/                # 自定义工具
│   ├── __init__.py
│   ├── search_tool.py    # 搜索工具
│   ├── calculator.py     # 计算工具
│   └── database.py       # 数据库查询工具
├── models/               # 模型配置
│   ├── __init__.py
│   └── config.py         # 模型初始化与 provider 配置
├── prompts/              # 提示词模板
│   ├── __init__.py
│   ├── system.md         # 系统提示词
│   └── templates.py      # 动态提示词
├── memory/               # 记忆模块
│   ├── __init__.py
│   └── store.py          # 记忆存储实现
├── requirements.txt      # 依赖清单
├── .env                  # 环境变量(API Key 等)
├── .env.example          # 环境变量示例
└── README.md             # 项目说明

按功能分层

对于更复杂的项目,建议按功能模块分层:

my-rag-app/
├── ingestion/            # 数据摄入层
│   ├── loaders.py        # 文档加载器
│   ├── splitters.py      # 文本分割器
│   └── embeddings.py     # 嵌入向量生成
├── retrieval/            # 检索层
│   ├── vector_store.py   # 向量存储配置
│   ├── retriever.py      # 检索器实现
│   └── reranker.py       # 重排序逻辑
├── agent/                # Agent 层
│   ├── agent.py          # Agent 定义
│   ├── tools/            # 工具集合
│   └── prompts/          # Agent 提示词
├── api/                  # API 服务层
│   ├── app.py            # FastAPI/Flask 入口
│   ├── routes.py         # 路由定义
│   └── schemas.py        # 请求/响应 Schema
├── config/               # 配置层
│   ├── settings.py       # 全局配置
│   └── constants.py      # 常量定义
└── tests/                # 测试
    ├── test_agent.py
    ├── test_tools.py
    └── test_retrieval.py

快速启动示例

以下是最小化项目的 agent.py 文件示例:

python
from langchain import create_agent
from langchain.chat_models import init_chat_model

# 初始化模型
model = init_chat_model("openai/gpt-4o")

# 定义工具(直接从 tools 模块导入)
from tools.search_tool import web_search
from tools.calculator import calculate

# 创建 Agent
agent = create_agent(
    model=model,
    tools=[web_search, calculate],
    system_prompt="你是一个有用的助手,可以搜索网络和进行计算。"
)

# 运行 Agent
result = agent.invoke({"messages": [{"role": "user", "content": "2024 年诺贝尔物理学奖得主是谁?"}]})
print(result)

工具模块示例

tools/search_tool.py:

python
import httpx
from langchain.tools import tool

@tool
def web_search(query: str) -> str:
    """搜索互联网并返回结果摘要。"""
    response = httpx.get("https://api.duckduckgo.com/", params={
        "q": query,
        "format": "json"
    })
    results = response.json()
    return results.get("AbstractText", "未找到结果")

提示词管理

将系统提示词放在独立文件中便于维护和版本控制:

prompts/system.md:

markdown
你是 {agent_name},一个智能助手。

## 行为准则
- 始终使用中文回复
- 在不确定时坦诚告知
- 使用工具获取最新信息

prompts/templates.py:

python
from langchain.prompts import @dynamic_prompt

system_prompt = open("prompts/system.md").read()

@dynamic_prompt
def agent_prompt(context: dict) -> str:
    """根据对话上下文动态生成提示词。"""
    user_name = context.get("user_name", "用户")
    return system_prompt.format(agent_name=f"{user_name}的助手")

配置管理

推荐使用 pydantic-settings 管理配置:

config/settings.py:

python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    openai_api_key: str = ""
    gemini_api_key: str = ""
    anthropic_api_key: str = ""
    model_provider: str = "openai/gpt-4o"
    temperature: float = 0.7
    max_tokens: int = 4096
    
    class Config:
        env_file = ".env"

settings = Settings()

大型项目结构

对于涉及微服务或多 Agent 协作的大型项目:

enterprise-agent-platform/
├── agents/               # Agent 定义
│   ├── customer_support/ # 客服 Agent
│   ├── data_analyst/     # 数据分析 Agent
│   └── coding_assistant/ # 编码助手 Agent
├── shared/               # 共享模块
│   ├── tools/            # 通用工具
│   ├── models/           # 模型配置
│   └── middleware/       # 中间件
├── services/             # 微服务
│   ├── auth/             # 认证服务
│   ├── monitoring/       # 监控服务
│   └── cache/            # 缓存服务
├── deployment/           # 部署配置
│   ├── Dockerfile
│   ├── docker-compose.yml
│   └── k8s/
└── docs/                 # 文档

最佳实践

  1. 关注点分离:工具、模型、提示词应分属不同模块
  2. 配置外部化:API Key 等敏感信息使用 .env 文件
  3. 尽早模块化:即使项目很小,也建议按目录组织
  4. 测试先行:为工具和 Agent 编写单元测试
  5. 类型注解:为所有函数添加类型注解,便于 IDE 提示

下一步

本站为非官方中文学习站点,不代表 LangChain 官方。部分内容参考官方文档并重新整理为中文学习笔记。