ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Pydantic AI Agent 需求定义实战:用 INITIAL.md 启动 PRP 上下文工程工作流

Pydantic AI Agent 需求定义实战:用 INITIAL.md 启动 PRP 上下文工程工作流 Pydantic AI Agent 需求定义实战用 INITIAL.md 启动 PRP 上下文工程工作流【免费下载链接】context-engineering-introContext engineering is the new vibe coding - its the way to actually make AI coding assistants work. Claude Code is the best for this so thats what this repo is centered around, but you can apply this strategy with any AI coding assistant!项目地址: https://gitcode.com/gh_mirrors/co/context-engineering-intro导读本文聚焦 context-engineering-intro 仓库中use-cases/pydantic-ai模板的入口文档 PRPs/INITIAL.md——它是一份用于定义 Pydantic AI Agent 需求的结构化模板也是 PRPProduct Requirements Prompts三步工作流的起点。读完本文你将掌握如何正确填写 INITIAL.md 的七个章节FEATURE / TOOLS / DEPENDENCIES / SYSTEM PROMPT(S) / EXAMPLES / DOCUMENTATION / OTHER CONSIDERATIONS并能够结合仓库内置的五个示例与源码级模式把一段自然语言需求转化成可生成、可执行、可测试的生产级 Pydantic AI Agent。INITIAL.md 在 PRP 工作流中的位置在 use-cases/pydantic-ai/README.md 中模板定义了 3 步上下文工程工作流Define Requirements定义需求编辑PRPs/INITIAL.md把占位符替换为你要构建的 Agent 的完整描述Generate Implementation Plan生成实现计划在 Claude Code 中运行/generate-pydantic-ai-prp PRPs/INITIAL.md生成包含技术调研、架构设计、实现路线图与验证循环的 PRP 文档Execute Implementation执行实现运行/execute-pydantic-ai-prp PRPs/generated_prp.md按 PRP 产出完整 Agent 项目agent.py、tools.py、models.py、dependencies.py、tests/。如果不使用 Claude Code也可以把这两个 slash 命令的内容作为提示词喂给任何 AI 编码助手。而整个流程的第一步就是 PRPs/INITIAL.md 这份「需求问卷」——它的填写质量直接决定了后续 PRP 与最终 Agent 的质量。模板的复制由 copy_template.py 完成运行python copy_template.py /path/to/my-agent-project即可把 CLAUDE.md、PRP 模板、示例等全套文件部署到新项目。脚本内置的 validate_template_integrity() 会校验.claude/commands/generate-pydantic-ai-prp.md、PRPs/templates/prp_pydantic_ai_base.md、PRPs/INITIAL.md、examples/basic_chat_agent/agent.py、examples/testing_examples/test_agent_patterns.py等关键文件是否齐全保证复制出的模板可直接开工。章节一FEATURE —— 描述你要构建的 AgentINITIAL.md 的第一个章节要求你用方括号占位符替换为对自己 Agent 的完整描述原则是越详细越好。模板给出的极简示例是Build a simple research agent using Pydantic AI that can research topics with the Brave API and draft emails with Gmail to share insights.这并非空谈——仓库的 examples/main_agent_reference/research_agent.py 就是这一设想的落地形态research_agent Agent(get_llm_model(), deps_typeResearchAgentDependencies, system_promptSYSTEM_PROMPT)并通过research_agent.tool注册了search_web工具调用 Brave Search API同时组合了一个负责 Gmail 邮件草稿的邮件子 Agent。填写 FEATURE 时建议包含Agent 的核心职责、目标用户、输入输出形态对话 / 批处理、以及它与其他 Agent 的协作关系——这些信息会直接映射到 PRP 的 Agent Type ClassificationChat / Tool-Enabled / Workflow / Structured Output与 Success Criteria 中。章节二TOOLS —— 描述工具的功能、参数与返回值TOOLS 章节要求描述 Agent 需要的每个工具包括功能、参数、返回值同样「越具体越好」。仓库 examples/tool_enabled_agent/agent.py 是工具描述的范本它注册了四个工具工具参数返回值说明web_searchquery: str、max_results: Optional[int]格式化后的搜索结果字符串通过 DuckDuckGo Instant Answer API 搜索超时与结果数由依赖控制calculateexpression: str、description: Optional[str]计算结果字符串使用受限命名空间eval安全求值支持sqrt、sin、log、pi等数学符号format_datadata: str、format_type: str格式化字符串支持table/list/json三种格式get_current_time无当前时间戳字符串datetime.now()格式化输出工具全部通过tool_agent.tool装饰器注册见 agent.py#L105-L109并遵循两个关键模式上下文感知第一个参数是ctx: RunContext[ToolDependencies]通过ctx.deps访问 HTTP session、超时、结果上限等依赖如max_results or ctx.deps.max_search_results优雅降级每个工具都包在try/except中超时返回 Search timed out...异常返回错误描述字符串保证单工具失败不会导致整个 Agent 运行崩溃。填写 INITIAL.md 的 TOOLS 章节时应逐条写明上述字段agent.tool需要 RunContext与agent.tool_plain无依赖的纯工具的选择也应在此阶段确定。章节三DEPENDENCIES —— 描述 RunContext 依赖DEPENDENCIES 章节要求描述工具依赖的外部资源——API keys、数据库连接、HTTP 客户端等它们会进入 Pydantic AI 的deps_type依赖注入系统。仓库中两类典型依赖定义1. 配置类依赖main_agent_reference——research_agent.py#L42-L48 定义了纯配置 dataclass不持有工具实例dataclass class ResearchAgentDependencies: Dependencies for the research agent - only configuration, no tool instances. brave_api_key: str gmail_credentials_path: str gmail_token_path: str session_id: Optional[str] None2. 资源类依赖tool_enabled_agent——tool_enabled_agent/agent.py#L69-L76 的ToolDependencies持有aiohttp.ClientSession、api_timeout10、max_search_results5、calculation_precision6等可调参数并由调用方在运行时通过tool_agent.run(question, depsdependencies)注入。在 INITIAL.md 中写清这些依赖后PRP 会将其映射为 prp_pydantic_ai_base.md 中的 dependency injection 规范依赖保持简单、类型明确避免复杂依赖图——这是模板反复强调的防过度设计原则。章节四SYSTEM PROMPT(S) —— 编写静态与动态指令SYSTEM PROMPT(S) 章节允许你直接写出完整系统提示词或给出指导性描述。仓库展示了两种写法静态提示词直接作为字符串常量传入Agent(..., system_prompt...)例如 basic_chat_agent/agent.py#L71-L86 定义了角色性格warm, humble, patient与行为准则保持对话自然、追问、记住上下文。动态提示词通过chat_agent.system_prompt注册函数在每次运行时根据ctx.deps拼装上下文信息——basic_chat_agent/agent.py#L97-L111 会根据用户是否提供了名字、对话轮数、偏好语言追加 The users name is Alex. 等动态片段chat_agent.system_prompt def dynamic_context_prompt(ctx) - str: prompt_parts [] if ctx.deps.user_name: prompt_parts.append(fThe users name is {ctx.deps.user_name}.) if ctx.deps.conversation_count 0: prompt_parts.append(fThis is message #{ctx.deps.conversation_count 1} in your conversation.) return .join(prompt_parts) if prompt_parts else 这也是「上下文工程」在 Agent 开发中的直接体现把会话状态注入提示词让模型感知对话历史与用户画像而不是依赖外部记忆插件。章节五EXAMPLES —— 模板内置的五套示例库INITIAL.md 明确列出了模板已随附的示例它们是从「聊天」到「多 Agent 组合」的递进学习路径。读者可把自研 Agent 的实现方案或从过去项目中沉淀的工具实现追加到examples/目录并在本章节引用1. basic_chat_agent —— 带对话记忆的基础聊天 Agent代码位于 examples/basic_chat_agent/agent.py。核心演示点默认字符串输出不设result_type用ConversationContextdataclass 承载用户姓名、对话轮数、偏好语言提供chat_with_agentasync与chat_with_agent_sync两个入口后者内部asyncio.run包装便于同步场景直接调用。2. tool_enabled_agent —— 带工具能力的 Agent代码位于 examples/tool_enabled_agent/agent.py。演示agent.tool注册、RunContext 依赖注入、aiohttpHTTP session 生命周期管理ask_agent中finally关闭会话、以及工具的完整错误处理。3. structured_output_agent —— 结构化输出与数据校验代码位于 examples/structured_output_agent/agent.py。它演示了何时才使用result_type仅在需要校验输出结构时。核心是 DataAnalysisReport 这个 Pydantic 模型——confidence_score用ge0.0, le1.0约束区间data_quality用pattern^(excellent|good|fair|poor)$枚举取值key_insights用min_items1, max_items10限制数量Agent 实例化为Agent(..., result_typeDataAnalysisReport, ...)agent.py#L132-L138。4. testing_examples —— TestModel / FunctionModel 测试模式代码位于 examples/testing_examples/test_agent_patterns.py配套 pytest.ini。覆盖TestModel快速验证、TestModel(custom_output_text...)定制响应、TestModel(call_tools[tool_name])定向触发工具、FunctionModel自定义行为、Agent.override()测试隔离以及工具失败时的错误恢复断言详见下文「测试与验证」。5. main_agent_reference —— 最佳实践参考实现代码位于 examples/main_agent_reference/是模板钦定的「canonical reference」settings.pypydantic-settings 环境配置、providers.pyget_llm_model()模型抽象、research_agent.py多工具研究 Agent、tools.py纯函数工具可被任意 Agent 复用、cli.py带流式输出的对话式 CLI、models.pyPydantic 数据模型。新建 Agent 时应直接复用这套模式而不是自造轮子。章节六DOCUMENTATION —— 为 PRP 生成准备参考资料DOCUMENTATION 章节用于告诉生成 PRP 的编码助手需要研究哪些资料可以放入PRPs/ai_docs目录的精选文档也可以指向在线资源。INITIAL.md 推荐的研究面包括Pydantic AI 官方文档的入门指南、Agent 创建指南、工具集成、测试模式、模型提供方配置。仓库侧的补充依据是 use-cases/pydantic-ai/CLAUDE.md它把上述主题固化为全局开发规则例如使用python-dotenvpydantic-settings管理配置load_dotenv()加载环境变量agent.tool用于上下文感知工具RunContext[DepsType]agent.tool_plain用于无依赖纯工具测试优先使用TestModel与FunctionModelAgent 代码按agent.py/tools.py/models.py/dependencies.py模块化组织单文件不超过 500 行。章节七OTHER CONSIDERATIONS —— 关键开发守则INITIAL.md 末尾列出了四条必须传达给编码助手的守则每一条在仓库中都有源码级支撑用环境变量配置 API Key绝不硬编码模型字符串。参考 settings.pyllm_provider、llm_api_key、llm_model、llm_base_url均从环境读取且validate_api_keys校验器会拒绝空 Keyproviders.py#L12-L29 的get_llm_model()通过OpenAIProvider(base_url, api_key)OpenAIModel完成模型装配并支持model_choice覆盖。保持 Agent 简单默认字符串输出——只有明确需要结构化校验时才设置result_type。basic_chat_agent 与 tool_enabled_agent 都刻意省略result_type注释明确标注 no result_type, defaults to string。遵循 main_agent_reference 的配置与 providers 模式——即「复制-修改」而非「从零发明」。开发期始终用 TestModel 做全面测试避免消耗真实 API 调用。此外 CLAUDE.md 还总结了常见 gotchas 与反模式混用 async/sync 调用、忽略模型 token 上限、依赖图过深难调试、工具错误未处理导致整轮运行崩溃、把敏感信息写入日志等——这些都应作为「注意事项」写入 INITIAL.md让 PRP 生成时主动规避。从 INITIAL.md 到可运行 Agent测试与验证闭环INITIAL.md 的最终产出是需求但需求质量要靠验证循环兜底。test_agent_patterns.py 给出了四个可复制进自己项目的测试范式TestModel 快速验证L87-L96with test_agent.override(modelTestModel()): result test_agent.run_sync(Hello..., deps...)零 API 成本验证 Agent 装配与输出结构定制输出TestModel(custom_output_text{message: ...})精确控制模型返回断言字段值定向触发工具TestModel(call_tools[mock_database_query])配合AsyncMock/Mock依赖用assert_called()验证工具确实被调用用side_effect模拟异常并断言错误恢复FunctionModel 自定义行为L213-L242根据输入内容返回不同响应用于测试分支逻辑如检测到 error 时返回错误处理响应。配套的验证命令源自 prp_pydantic_ai_base.md可分层执行先用test -f agent.py echo Agent definition present检查结构再python -c验证 Agent 可实例化且工具已注册最后python -m pytest tests/ -v跑完整测试套件并用grep -r API_KEY确认没有把密钥写进代码。结语INITIAL.md 看似只是一张占位符模板实则是上下文工程工作流中最关键的「需求契约」它把模糊的产品想法结构化为 FEATURE / TOOLS / DEPENDENCIES / SYSTEM PROMPT(S) / EXAMPLES / DOCUMENTATION / OTHER CONSIDERATIONS 七个维度再由generate-pydantic-ai-prp与execute-pydantic-ai-prp两个命令接力完成「调研-规划-实现-测试」的全流程。结合本仓库的五套示例与 CLAUDE.md 的全局规则你可以在几十分钟内完成一个符合最佳实践环境配置、字符串输出默认、依赖注入、TestModel 全覆盖的 Pydantic AI Agent 项目骨架——这正是「Context Engineering」让 AI 编码助手真正可靠工作的核心方式。【免费下载链接】context-engineering-introContext engineering is the new vibe coding - its the way to actually make AI coding assistants work. Claude Code is the best for this so thats what this repo is centered around, but you can apply this strategy with any AI coding assistant!项目地址: https://gitcode.com/gh_mirrors/co/context-engineering-intro创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表