Py学习  »  Python

Python专业级智能体框架Pydantic AI,高效创建生产级智能体

AI科技论谈 • 3 月前 • 156 次点击  

Pydantic AI 降临 Python 生态,开启智能开发新时代。



在 Python 的生态系统中,Pydantic 是一款相当实用的工具。它每月的下载量超过 2.85 亿次,一直是 Python 项目进行可靠数据验证的重要基础。

如今,Pydantic 的开发者开始涉足前沿的人工智能领域,推出了 Pydantic AI。这是一个框架,主要用来搭建生产级别的应用程序,这些程序由生成式人工智能提供支持。

本文带你全方位认识 Pydantic AI,了解其特点和功能,同时与其他框架做对比,快速明晰其优势。

一、为何选择Pydantic AI? 

Pydantic AI 的底层依托于可信赖的 Pydantic,Pydantic 为FastAPI、LangChain和AutoGPT等诸多热门Python库提供支持。

Pydantic AI 能简化智能体应用开发,优势有:

  • 易用:利用Python原生类型系统创建类型安全、可扩展的智能体。
  • 适配生产:专注构建强大应用,支持动态提示、结构化响应,可集成Logfire等可观测性工具。
  • 灵活兼容:采用模型无关设计,支持OpenAI、Anthropic和Gemini等模型,未来还将支持更多。

其目标是解决智能体框架领域缺乏生产级工具的问题。

二、Pydantic AI核心特性 

Pydantic AI能在众多框架中崭露头角,关键在于以下特性:

  1. 动态系统提示:可依据运行时数据编程调整系统提示,让响应贴合上下文,在客户支持等场景优势显著。
  2. 结构化响应验证:基于Pydantic验证能力,确保响应包含必填字段,减少生产环境错误。
  3. 与大语言模型无缝集成:和OpenAI、Gemini等集成,未来还支持Claude,切换模型不影响核心逻辑,适应性强且成本效益高。
  4. 类型安全的依赖注入:新颖的依赖注入系统简化测试开发,保障代码可重用、易维护。
  5. 流式响应:支持逐令牌流式响应,适合聊天机器人等交互式应用。
  6. Logfire集成:与Pydantic Logfire集成,方便监控调试大语言模型驱动的应用,对实际部署意义重大。

三、代码示例 

Hello World示例

这是一个PydanticAI的简单示例:

from pydantic_ai 


    
import Agent

agent = Agent(  
    'gemini-1.5-flash',
    system_prompt='Be concise, reply with one sentence.'  
)

result = agent.run_sync('Where does "hello world" come from?'
print(result.data)

输出结果:The first known use of "hello, world" was in a 1974 textbook about the C programming language.

解释

  1. 智能体初始化
  • 使用模型ID(gemini-1.5-flash)初始化Agent,该ID指定了所使用的人工智能模型。
  • system_prompt定义了智能体的行为。在这个例子中,提示确保智能体给出简洁的单句回复。
  • run_sync方法
    • run_sync方法用于同步执行智能体,并传入查询内容。
    • 这里,智能体被询问“hello world”的起源。
  • result.data
    • result包含人工智能的输出。通过访问result.data可以获取生成的响应。
  • 示例输出
    • “The first known use of 'hello, world' was in a 1974 textbook about the C programming language.”
    • 这展示了智能体如何提供事实性且简洁的答案。

    工具与依赖注入示例:银行客户支持智能体示例

    以下是使用PydanticAI为银行构建支持智能体的简单示例:

    # 安装与依赖
    python -m pydantic_ai_examples.bank_support
    from dataclasses import dataclass
    from pydantic import BaseModel, Field
    from pydantic_ai import Agent, RunContext

    class DatabaseConn:
        """这是用于示例的假数据库。
        在实际应用中,你需要连接到外部数据库(例如PostgreSQL)以获取客户信息。
        """

        @classmethod
        asyncdef customer_name(cls, *, id: int) -> str | None:
            if id == 123:
                return'John'

        @classmethod
        asyncdef customer_balance(cls, *, id: int, include_pending: bool) -> float:
            if id == 123:
                return123.45
            else:
                raise ValueError('Customer not found')

    @dataclass
    class SupportDependencies:
        customer_id: int
        db: DatabaseConn

    class SupportResult(BaseModel):
        support_advice: str = Field(description='Advice returned to the customer')
        block_card: bool = Field(description='Whether to block their')
        risk: int = Field(description='Risk level of query', ge=0, le=10)

    support_agent = Agent(
        'openai:gpt-4o',
        deps_type=SupportDependencies,
        result_type=SupportResult,
        system_prompt=(
            'You are a support agent in our bank, give the '
            'customer support and judge the risk level of their query. '
            "Reply using the customer's name."
        ),
    )

    @support_agent.system_prompt
    asyncdef add_customer_name(ctx: RunContext[SupportDependencies]) -> str:
        customer_name = await ctx.deps.db.customer_name(id=ctx.deps.customer_id)
        returnf"The customer's name is {customer_name!r}"

    @support_agent.tool
    asyncdef customer_balance(
        ctx: RunContext[SupportDependencies], include_pending: bool
    )
     -> str:

        """Returns the customer's current account balance."""
        balance = await ctx.deps.db.customer_balance(
            id=ctx.deps.customer_id,
            include_pending=include_pending,
        )
        returnf'${balance:.2f}'

    deps = SupportDependencies(customer_id=123, db=DatabaseConn())
    result = support_agent.run_sync('What is my balance?', deps=deps)
    print(result.data)

    输出结果:support_advice='Hello John, your current account balance, including pending transactions, is $123.45.' block_card=False risk=1

    result = support_agent.run_sync('I just lost my card!', deps=deps)
    print(result.data)

    输出结果:support_advice="I'm sorry to hear that, John. We are temporarily blocking your card to prevent unauthorized transactions." block_card=True risk=8

    关键概念

    1. 函数
    • customer_name:通过ID返回客户姓名(例如,ID 123对应“John”)。
    • customer_balance:检索客户的账户余额。
  • SupportDependencies
    • 一个数据类,包含客户ID和数据库连接对象。
    • 帮助聊天机器人确定要协助的客户。
  • SupportResult
    • 一个Pydantic模型,指定聊天机器人的响应格式:
    • support_advice:给客户的建议。
    • block_card:是否应封锁客户的卡。
    • risk:查询的风险等级(0 - 10)。
  • Agent
    • 定义支持智能体,包括:
    • 语言模型(openai:gpt-4o)。
    • deps_type:查询所需的依赖项(例如,客户信息)。
    • result_type:预期的响应格式。
    • system_prompt:指导聊天机器人行为的指令。
  • 智能体增强功能
    • add_customer_name:
    • 检索客户姓名,并个性化聊天机器人的系统行为。
    • customer_balance:
    • 一个工具,用于检索客户余额并格式化为字符串。
  • 运行智能体
    • 使用模拟数据库和客户ID 123初始化SupportDependencies。
    • run_sync模拟同步聊天机器人交互。

    Pydantic AI进入了一个竞争激烈的领域,由LangChain(lanGgraph)、Llama Agents、CrewAI和Microsoft AutoGen等框架主导的领域。

    四、总结与思考  

    在 Python 智能体框架的生态版图中,Pydantic AI 是一颗冉冉升起的新星。

    Pydantic AI 十分重视验证环节,能够与主流大语言模型实现良好协作,并且开发出的工具非常契合实际生产需求。凭借这些优势,Pydantic AI 极有可能在未来成为开发者们常用的框架。它的验证机制有助于减少开发过程中的错误,与大语言模型的集成拓展了应用的功能边界,而生产级工具则为项目的顺利落地提供了有力保障。

    但 Pydantic AI 也面临着挑战,它的成功依赖开发者的采用程度和持续创新能力。毕竟,在技术快速迭代的当下,只有不断进化,满足开发者日益增长的需求,才能在激烈的竞争中脱颖而出。

    如果你已经很熟悉 Pydantic 的开发,那么 Pydantic AI 更像是一次自然的技术进阶。两者一脉相承,从 Pydantic 过渡到 Pydantic AI,上手难度低,还能借助新框架解锁更多 AI 开发的新可能。

    推荐大家探索 Pydantic AI,将其融入到AI应用开发中,充分发挥其优势,打造更强大、可扩展的应用,在开发领域抢占先机!

    推荐书单 

    《LangChain大模型AI应用开发实践》

    本书是一本深度探索LangChain框架及其在构建高效AI应用中所扮演角色的权威教程。本书以实战为导向,系统介绍了从LangChain基础到高级应用的全过程,旨在帮助开发者迅速掌握这一强大的工具,解锁人工智能开发的新维度。

    本书内容围绕LangChain快速入门、Chain结构构建、大模型接入与优化、提示词工程、高级输出解析技术、数据检索增强(RAG)、知识库处理、智能体(agent)开发及其能力拓展等多个层面展开。通过详实的案例分析与步骤解说,读者可以学会整合如ChatGLM等顶尖大模型,运用ChromaDB进行高效的向量检索,以及设计与实现具有记忆功能和上下文感知能力的AI智能体。此外,书中还介绍了如何利用LangChain提升应用响应速度、修复模型输出错误、自定义输出解析器等实用技巧,为开发者提供了丰富的策略与工具。

    本书主要面向AI开发者、数据科学家、机器学习工程师,以及对自然语言处理和人工智能应用感兴趣的中级和高级技术人员。

    【5折促销中】购买链接:https://item.jd.com/14848506.html

    精彩回顾 

    数据分析神器PandasAI,帮你高效处理10项常见任务

    6款必知的AI Agent工作流,优缺点解析

    QwQ-32B本地部署教程来了,全新开源推理大模型,性能比肩DeepSeek满血版

    解读Deep Research:传统RAG已死,带你实现Agentic RAG

    大模型应用开发平台Dify推出1.0版本,基于向量数据库Milvus实现RAG

    从推理到编程,详细比较DeepSeek 32B、70B、R1实践性能


    长按访问【IT今日热榜】,发现每日技术热点
    长按访问【IT今日热榜】,发现每日技术热点

    Python社区是高质量的Python/Django开发社区
    本文地址:http://www.python88.com/topic/180370
     
    156 次点击