Pydantic AI是2025年底发布的AI应用开发框架由Pydantic团队打造将Python类型系统深度融入AI应用开发。它在生产环境的可靠性和开发体验上带来了显著提升2026年已在企业级AI工程师中快速普及。—## 为什么需要类型安全的AI框架传统LLM应用开发中最让工程师头疼的问题不是AI不够聪明而是AI输出的不可预测性python# 典型问题不知道LLM会返回什么response openai.chat.completions.create(...)data json.loads(response.choices[0].message.content)# 报错格式不对缺少字段运行时才知道result data[user_info][name] # KeyError!Pydantic AI通过类型系统从根本上解决了这个问题pythonfrom pydantic import BaseModelfrom pydantic_ai import Agentclass UserInfo(BaseModel): name: str age: int email: stragent Agent(openai:gpt-4o, result_typeUserInfo)# 保证返回UserInfo实例否则自动重试直到得到正确格式result await agent.run(提取以下文本中的用户信息: 张三28岁邮箱 zhangsanexample.com)user: UserInfo result.data # 类型安全print(user.name) # 张三—## 核心概念### Agent最小执行单元Pydantic AI的核心是Agent它封装了- 模型选择- 系统提示- 工具集合- 输出类型pythonfrom pydantic_ai import Agentfrom pydantic_ai.models.openai import OpenAIModel# 基础Agentsimple_agent Agent( modelopenai:gpt-4o, system_prompt你是一位专业的代码审查专家。)# 带输出类型的Agentfrom pydantic import BaseModelfrom typing import listclass CodeReviewResult(BaseModel): issues: list[str] severity: str # low / medium / high / critical suggestions: list[str] approved: boolreview_agent Agent( modelopenai:gpt-4o, result_typeCodeReviewResult, system_prompt你是专业代码审查专家。 分析代码并返回结构化的审查结果包括问题列表、严重程度、改进建议和是否通过。)# 执行result await review_agent.run(请审查以下代码pythondef get_user(id): sql fSELECT * FROM users WHERE id {id} # SQL注入漏洞 return db.execute(sql))review: CodeReviewResult result.dataprint(f严重程度: {review.severity}) # criticalprint(f是否通过: {review.approved}) # Falseprint(f问题: {review.issues}) # [SQL注入漏洞: 使用了字符串拼接构造SQL...]—### 工具Tools赋予Agent行动能力pythonfrom pydantic_ai import Agent, RunContextfrom pydantic_ai.tools import Toolimport httpx# 方式一函数装饰器review_agent.toolasync def get_codebase_context(ctx: RunContext, file_path: str) - str: 读取项目文件为代码审查提供上下文 try: with open(file_path, r, encodingutf-8) as f: return f.read() except FileNotFoundError: return f文件不存在: {file_path}# 方式二Tool类更精确的类型控制from pydantic import Fieldasync def search_cve_database( ctx: RunContext[dict], library_name: str Field(description要查询的库名称), version: str Field(description库的版本号)) - dict: 查询CVE漏洞数据库检查依赖库是否有已知安全漏洞 async with httpx.AsyncClient() as client: resp await client.get( fhttps://cve-api.example.com/search, params{library: library_name, version: version} ) return resp.json()security_agent Agent( modelopenai:gpt-4o, result_typeCodeReviewResult, tools[Tool(search_cve_database, takes_ctxTrue)], system_prompt你是代码安全专家会主动查询CVE数据库检查依赖安全性。)—### 依赖注入干净的上下文传递Pydantic AI通过依赖注入传递运行时上下文避免了全局变量和闭包的混乱pythonfrom dataclasses import dataclassfrom pydantic_ai import Agent, RunContextdataclassclass ReviewContext: 代码审查的运行时上下文 project_name: str author: str db_client: DatabaseClient github_token: strreview_agent Agent( modelopenai:gpt-4o, deps_typeReviewContext, # 声明依赖类型 result_typeCodeReviewResult, system_prompt你是代码审查专家。 审查时请参考项目的历史问题和作者的代码风格。)review_agent.toolasync def get_author_history(ctx: RunContext[ReviewContext]) - dict: 获取该作者历史的代码质量数据 # ctx.deps 是类型安全的 ReviewContext 实例 history await ctx.deps.db_client.query( SELECT * FROM code_quality WHERE author ?, ctx.deps.author ) return historyreview_agent.system_promptasync def dynamic_system_prompt(ctx: RunContext[ReviewContext]) - str: 动态生成系统提示包含项目上下文 return f你在审查项目 {ctx.deps.project_name} 的代码。作者{ctx.deps.author}请根据项目规范严格审查。# 执行时注入依赖context ReviewContext( project_nameMyApp, authorzhangsan, db_clientdb, github_tokenos.environ[GITHUB_TOKEN])result await review_agent.run(code_content, depscontext)—## 多Agent系统构建pythonfrom pydantic_ai import Agentclass AnalysisReport(BaseModel): summary: str key_findings: list[str] risk_level: str recommendations: list[str]# 专门分析安全漏洞的Agentsecurity_agent Agent( openai:gpt-4o, result_typelist[str], system_prompt你是安全专家列举所有潜在安全漏洞。)# 专门分析性能问题的Agentperformance_agent Agent( openai:gpt-4o, result_typelist[str], system_prompt你是性能优化专家识别所有性能瓶颈。)# 综合报告Agent协调其他Agentreport_agent Agent( openai:gpt-4o, result_typeAnalysisReport, system_prompt你是技术主管综合各专家意见生成最终报告。)async def comprehensive_code_review(code: str) - AnalysisReport: 多Agent并行分析综合生成报告 # 并行执行专项分析 security_result, performance_result await asyncio.gather( security_agent.run(f分析以下代码的安全漏洞\n{code}), performance_agent.run(f分析以下代码的性能问题\n{code}) ) # 综合报告 combined_findings f安全问题{chr(10).join(security_result.data)}性能问题{chr(10).join(performance_result.data)} report_result await report_agent.run( f基于以下专项分析为代码生成综合审查报告\n{combined_findings} ) return report_result.data—## 测试Pydantic AI的测试友好设计Pydantic AI内置了测试模式无需真实调用API即可测试业务逻辑pythonimport pytestfrom pydantic_ai import Agentfrom pydantic_ai.models.test import TestModelpytest.mark.asyncioasync def test_code_review_agent(): 测试代码审查Agent不调用真实API agent Agent( TestModel(), # 使用测试模型 result_typeCodeReviewResult ) # TestModel按照类型自动生成测试数据 result await agent.run(测试代码) assert isinstance(result.data, CodeReviewResult) assert hasattr(result.data, issues) assert hasattr(result.data, severity)pytest.mark.asyncioasync def test_with_custom_response(): 使用自定义响应测试特定场景 from pydantic_ai.models.test import TestModel, ModelTextResponse model TestModel( custom_responseModelTextResponse( {issues: [SQL注入], severity: critical, suggestions: [使用参数化查询], approved: false} ) ) agent Agent(model, result_typeCodeReviewResult) result await agent.run(有SQL注入的代码) assert result.data.severity critical assert result.data.approved False assert SQL注入 in result.data.issues—## 与其他框架的对比| 特性 | Pydantic AI | LangChain | LlamaIndex ||------|------------|-----------|------------|| 类型安全 | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐ || 测试友好 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ || 学习曲线 | 平缓 | 陡峭 | 中等 || 生态丰富度 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ || 生产稳定性 | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ || RAG支持 | 需要自己集成 | 完整支持 | 专项支持 |—## 选型建议选Pydantic AI如果你- 重视代码质量和可维护性- 需要在CI/CD中运行AI相关测试- 团队已在大量使用Pydantic- 构建需要可靠结构化输出的生产系统不选Pydantic AI如果你- 需要丰富的预构建组件RAG pipeline等- 快速原型验证不关注类型安全- 需要大量现成的集成选LangChainPydantic AI代表了AI应用开发的一个重要方向将AI能力与Python最佳工程实践深度融合。随着AI应用从原型走向生产这种类型安全、可测试的开发范式将变得越来越重要。