pydantic/pydantic-ai

GitHub: pydantic/pydantic-ai

Pydantic AI 是一个由 Pydantic 团队出品的 Python GenAI Agent 框架,以类型安全、结构化验证和深度可观测性帮助开发者高效构建生产级 AI 代理应用。

Stars: 16614 | Forks: 1982

Pydantic AI

GenAI Agent Framework, the Pydantic way

CI Coverage PyPI versions license Join Slack
**文档**:[ai.pydantic.dev](https://ai.pydantic.dev/) ### Pydantic AI 是一个 Python 代理框架,旨在帮助您快速、自信且轻松地构建生成式 AI 的生产级应用和工作流。 FastAPI 通过提供创新且符合人体工程学的设计,建立在 [Pydantic Validation](https://docs.pydantic.dev) 以及类型提示等现代 Python 特性的基础之上,彻底改变了 Web 开发。 然而,尽管几乎每个 Python 代理框架和 LLM 库都在使用 Pydantic Validation,但当我们在 [Pydantic Logfire](https://pydantic.dev/logfire) 中开始使用 LLM 时,却找不到任何能给我们带来同样感觉的工具。 我们构建 Pydantic AI 的唯一目的就是:将 FastAPI 的开发体验带入 GenAI 应用和代理开发中。 ## 为什么使用 Pydantic AI 1. **由 Pydantic 团队构建**: [Pydantic Validation](https://docs.pydantic.dev/latest/) 是 OpenAI SDK、Google ADK、Anthropic SDK、LangChain、LlamaIndex、AutoGPT、Transformers、CrewAI、Instructor 等众多项目的验证层。*既然可以直接使用源头,何必用派生品呢?* :smiley: 2. **模型无关**: 支持几乎所有[模型](https://ai.pydantic.dev/models/overview)和提供商:OpenAI、Anthropic、Gemini、DeepSeek、Grok、Cohere、Mistral 和 Perplexity;Azure AI Foundry、Amazon Bedrock、Google Vertex AI、Ollama、LiteLLM、Groq、OpenRouter、Together AI、Fireworks AI、Cerebras、Hugging Face、GitHub、Heroku、Vercel、Nebius、OVHcloud、阿里云、SambaNova 和 Outlines。如果您最喜欢的模型或提供商未被列出,您可以轻松实现一个[自定义模型](https://ai.pydantic.dev/models/overview#custom-models)。 3. **无缝可观测性**: 与我们的通用 OpenTelemetry 可观测性平台 [Pydantic Logfire](https://pydantic.dev/logfire) 紧密[集成](https://ai.pydantic.dev/logfire),用于实时调试、基于评估的性能监控,以及行为、链路追踪和成本追踪。如果您已经拥有支持 OTel 的可观测性平台,也可以[直接使用它](https://ai.pydantic.dev/logfire#alternative-observability-backends)。 4. **完全类型安全**: 旨在为您的 IDE 或 AI 编程助手提供尽可能多的上下文,以实现自动补全和[类型检查](https://ai.pydantic.dev/agents#static-type-checking),将整类错误从运行时提前到编写时,带来一点 Rust “只要编译通过,就能正常运行”的感觉。 5. **强大的评估**: 让您能够系统地测试和[评估](https://ai.pydantic.dev/evals)所构建代理系统的性能和准确性,并在 Pydantic Logfire 中持续监控其表现。 6. **设计上的高度可扩展**: 从可组合的[能力](https://ai.pydantic.dev/capabilities)构建代理,这些能力将工具、钩子、指令和模型设置捆绑为可复用的单元。使用内置能力进行[网页搜索](https://ai.pydantic.dev/capabilities#provider-adaptive-tools)、[思考](https://ai.pydantic.dev/capabilities#thinking)和 [MCP](https://ai.pydantic.dev/capabilities#provider-adaptive-tools),或者从 [Pydantic AI Harness](https://ai.pydantic.dev/harness/overview) 能力库中挑选,还可以构建您自己的能力,或安装[第三方能力包](https://ai.pydantic.dev/extensibility)。完全使用 [YAML/JSON](https://ai.pydantic.dev/agent-spec) 定义代理——无需编写代码。 7. **MCP、A2A 和 UI**: 集成了 [Model Context Protocol](https://ai.pydantic.dev/mcp/overview)、[Agent2Agent](https://ai.pydantic.dev/a2a) 以及各种 [UI 事件流](https://ai.pydantic.dev/ui/overview)标准,让您的代理能够访问外部工具和数据,与其他代理实现互操作,并通过基于流式事件的通信构建交互式应用程序。 8. **人在回路中的工具审批**: 轻松标记特定工具调用在继续执行前[需要审批](https://ai.pydantic.dev/deferred-tools#human-in-the-loop-tool-approval),这可能取决于工具调用参数、对话历史或用户偏好。 9. **持久化执行**: 支持构建[持久化代理](https://ai.pydantic.dev/durable_execution/overview/),能够在短暂的 API 故障、应用程序错误或重启中保留进度,并以生产级的可靠性处理长时间运行、异步以及人在回路中的工作流。 10. **流式输出**: 支持持续[流式传输](https://ai.pydantic.dev/output#streamed-results)结构化输出,并进行即时验证,确保实时访问生成的数据。 11. **图支持**: 提供了一种使用类型提示定义[图](https://ai.pydantic.dev/graph)的强大方式,适用于标准控制流可能退化为面条代码的复杂应用。 不过实际上,没有任何列表会比[亲自试一试](#next-steps)并看看它带给您的感受更有说服力! ## Hello World 示例 这是一个 Pydantic AI 的极简示例: ``` from pydantic_ai import Agent # Define a very simple agent including the model to use, you can also set the model when running the agent. agent = Agent( 'anthropic:claude-sonnet-4-6', # Register static instructions using a keyword argument to the agent. # For more complex dynamically-generated instructions, see the example below. instructions='Be concise, reply with one sentence.', ) # Run the agent synchronously, conducting a conversation with the LLM. result = agent.run_sync('Where does "hello world" come from?') print(result.output) """ The first known use of "hello, world" was in a 1974 textbook about the C programming language. """ ``` _(此示例是完整的,可以“原样”运行,前提是您已经[安装了 `pydantic_ai` 包](https://ai.pydantic.dev/install))_ 这次交互会非常简短:Pydantic AI 会将指令和用户提示发送给 LLM,模型随后会返回一个文本响应。 目前看起来没什么特别的,但我们可以轻松添加[工具](https://ai.pydantic.dev/tools)、[动态指令](https://ai.pydantic.dev/agents#instructions)、[结构化输出](https://ai.pydantic.dev/output)或可组合的[能力](https://ai.pydantic.dev/capabilities)来构建更强大的代理。 以下是添加了[思考](https://ai.pydantic.dev/capabilities#thinking)和[网页搜索](https://ai.pydantic.dev/capabilities#provider-adaptive-tools)能力的同一代理: ``` from pydantic_ai import Agent from pydantic_ai.capabilities import Thinking, WebSearch agent = Agent( 'anthropic:claude-sonnet-4-6', instructions='Be concise, reply with one sentence.', capabilities=[Thinking(), WebSearch()], ) result = agent.run_sync('What was the mass of the largest meteorite found this year?') print(result.output) ``` ## 工具与依赖注入示例 以下是使用 Pydantic AI 为银行构建客服代理的简明示例: **([文档中](https://ai.pydantic.dev/#tools-dependency-injection-example)有更详细的示例说明)** ``` from dataclasses import dataclass from pydantic import BaseModel, Field from pydantic_ai import Agent, RunContext from bank_database import DatabaseConn # SupportDependencies is used to pass data, connections, and logic into the model that will be needed when running # instructions and tool functions. Dependency injection provides a type-safe way to customise the behavior of your agents. @dataclass class SupportDependencies: customer_id: int db: DatabaseConn # This Pydantic model defines the structure of the output returned by the agent. class SupportOutput(BaseModel): support_advice: str = Field(description='Advice returned to the customer') block_card: bool = Field(description="Whether to block the customer's card") risk: int = Field(description='Risk level of query', ge=0, le=10) # This agent will act as first-tier support in a bank. # Agents are generic in the type of dependencies they accept and the type of output they return. # In this case, the support agent has type `Agent[SupportDependencies, SupportOutput]`. support_agent = Agent( 'openai:gpt-5.2', deps_type=SupportDependencies, # The response from the agent will be guaranteed to be a SupportOutput, # if validation fails the agent is prompted to try again. output_type=SupportOutput, instructions=( 'You are a support agent in our bank, give the ' 'customer support and judge the risk level of their query.' ), ) # Dynamic instructions can make use of dependency injection. # Dependencies are carried via the `RunContext` argument, which is parameterized with the `deps_type` from above. # If the type annotation here is wrong, static type checkers will catch it. @support_agent.instructions async def add_customer_name(ctx: RunContext[SupportDependencies]) -> str: customer_name = await ctx.deps.db.customer_name(id=ctx.deps.customer_id) return f"The customer's name is {customer_name!r}" # The `tool` decorator let you register functions which the LLM may call while responding to a user. # Again, dependencies are carried via `RunContext`, any other arguments become the tool schema passed to the LLM. # Pydantic is used to validate these arguments, and errors are passed back to the LLM so it can retry. @support_agent.tool async def customer_balance( ctx: RunContext[SupportDependencies], include_pending: bool ) -> float: """Returns the customer's current account balance.""" # The docstring of a tool is also passed to the LLM as the description of the tool. # Parameter descriptions are extracted from the docstring and added to the parameter schema sent to the LLM. balance = await ctx.deps.db.customer_balance( id=ctx.deps.customer_id, include_pending=include_pending, ) return balance ... # In a real use case, you'd add more tools and a longer system prompt async def main(): deps = SupportDependencies(customer_id=123, db=DatabaseConn()) # Run the agent asynchronously, conducting a conversation with the LLM until a final response is reached. # Even in this fairly simple case, the agent will exchange multiple messages with the LLM as tools are called to retrieve an output. result = await support_agent.run('What is my balance?', deps=deps) # The `result.output` will be validated with Pydantic to guarantee it is a `SupportOutput`. Since the agent is generic, # it'll also be typed as a `SupportOutput` to aid with static type checking. print(result.output) """ support_advice='Hello John, your current account balance, including pending transactions, is $123.45.' block_card=False risk=1 """ result = await support_agent.run('I just lost my card!', deps=deps) print(result.output) """ support_advice="I'm sorry to hear that, John. We are temporarily blocking your card to prevent unauthorized transactions." block_card=True risk=8 """ ``` ## 后续步骤 要亲自尝试 Pydantic AI,请[安装](https://ai.pydantic.dev/install)它并按照[示例](https://ai.pydantic.dev/examples/setup)中的说明进行操作。 阅读[文档](https://ai.pydantic.dev/agents/)以了解更多关于使用 Pydantic AI 构建应用的信息。 阅读 [API 参考](https://ai.pydantic.dev/api/agent/)以理解 Pydantic AI 的接口。 如果您有任何问题,请加入 [Slack](https://logfire.pydantic.dev/docs/join-slack/) 或在 [GitHub](https://github.com/pydantic/pydantic-ai/issues) 上提交 issue。
标签:AI Agent框架, AV绕过, DLL 劫持, FastAPI, GenAI, Homebrew安装, LLM, Pydantic, Python, Unmanaged PE, 大语言模型, 工作流, 开发框架, 开源, 数据验证, 无后门, 生产级, 生成式AI, 用户代理, 类型提示, 索引, 网络调试, 自动化, 逆向工具