LLM之Agent(十三)| 使用 PydanticAI 框架构建多代理LLM 系统(保姆教程)

图片

       Pydantic 是 Python 生态系统中的强大平台,每月下载量超过 2.85 亿次。现在,Pydantic的创始人也正在通过 Pydantic AI 涉足 AI 的前沿领域,Pydantic AI 是一个专为构建由生成式 AI 提供支持的生产级应用程序的框架。在本文中,我们将深入探讨 Pydantic AI 的独特之处、它的主要功能以及它与其他代理框架的比较。

一、Pydantic、GenAI 中的 Pydantic、PydanticAI对比

1.1 Pydantic

from datetime import datefrom pydantic import BaseModelclass User(BaseModel):    id: int    name: str    dob: date
user = User(id='123', name='Samuel Colvin', dob='1987-01-28')#> User(id=123, name='Samuel Colvin', dob=date(1987, 1, 28))user = User.model_validate_json('{"id: 123, "name": "Samuel Colvin", "dob": "1987-01-28"}')#> User(id=123, name='Samuel Colvin', dob=date(1987, 1, 28))print(User.model_json_schema())s = {
  
      'properties': {
  
          'id': {'title': 'Id', 'type': 'integer'},        'name': {'title': 'Name', 'type': 'string'},        'dob': {'format': 'date', 'title': 'Dob', 'type': 'string'},    },    'required': ['id', 'name', 'dob'],    'title': 'User',    'type': 'object',}

1.2 Pydantic in GenAI​​​​​​​

from datetime import datefrom pydantic import BaseModelfrom openai import OpenAIclass User(BaseModel):    """Definition of a user"""    id: int    name: str    dob: dateresponse = OpenAI().chat.completions.create(    model='gpt-4o',    messages=[        {'role': 'system', 'content': 'Extract information about the user'},        {'role': 'user', 'content': 'The user with ID 123 is called Samuel, born on Jan 28th 87'}    ],    tools=[        {
  
              'function': {
  
                  'name': User.__name__,                'description': User.__doc__,                'parameters': User.model_json_schema(),            },            'type': 'function'        }    ])user = User.model_validate_json(response.choices[0].message.tool_calls[0].function.arguments)print(user)

1.3 PydanticAI​​​​​​​

from datetime import datefrom pydantic_ai import Agentfrom pydantic import BaseModelclass User(BaseModel):    """Definition of a user"""    id: int    name: str    dob: dateagent = Agent(    'openai:gpt-4o',    result_type=User,    system_prompt='Extract information about the user',)result = agent.run_sync('The user with ID 123 is called Samuel, born on Jan 28th 87')print(result.data)

二、为什么是PydanticAI

       假设您正在制作一个应用程序,用户可在其中提交他们的姓名、年龄和电子邮件。您希望确保:

名称是一个字符串;

年龄是一个数字;

电子邮件的格式有效;

从以下示例可以看出 Pydantic 是如何简化此操作:​​​​​​​

from pydantic import BaseModel, EmailStr# Define the modelclass User(BaseModel):    name: str    age: int    email: EmailStr# Example inputuser_data = {
  
      "name": "Alice",    "age": 25,    "email": "[email protected]"}# Validate the inputuser = User(**user_data)print(user.name)  # Aliceprint(user.age)   # 25print(user.email) # [email protected]

     如果用户提交了无效数据(例如,“age”:“twenty-five”),Pydantic 将自动抛出错误:​​​​​​​

user_data = {
  
      "name": "Alice",    "age": "twenty-five",  # Invalid    "email": "[email protected]"}user = User(**user_data)# Error: value is not a valid integer

三、PydanticAI特点

     Pydantic 在部署中起着关键作用,因为大多数情况下必须遵循 Pydantic:

  • 开发团队:由Pydantic背后的团队构建(比如OpenAI SDK、Anthropic SDK、LangChain、LlamaIndex、AutoGPT、Transformers、CrewAI、Instructor 等);
  • 与模型无关:支持 OpenAI、Anthropic、Gemini、Ollama、Groq 和 Mistral,并且有一个简单的界面来实现对其他模型的支持;
  • 与Pydantic Logfire无缝集成:用于实时调试、性能监控和行为跟踪 LLM 驱动的应用程序;
  • 以python为中心设计:利用 Python 熟悉的控制流和代理组合来构建 AI 驱动的项目,从而轻松应用在任何其他(非 AI)项目中使用的标准 Python 最佳实践;
  • 结构化输出:利用 Pydantic 的强大功能来验证和构建模型输出,确保响应在运行之间保持一致;
  • 流式输出:能够连续流式传输 LLM 输出,并立即进行验证,确保快速准确的结果。

四、如何使用PydanticAI

4.1 安装PydanticAI(需要python3.9+)

pip install pydantic-ai

       这将安装使用 PydanticAI 中包含的所有模型所需的 pydantic_ai 包、核心依赖项和库。如果你想使用特定的模型,你可以安装 PydanticAI 的 “slim” 版本。

4.2 PydanticAI 的 8 个重要组成部分:

  • Agents(代理)
  • Models(模型)
  • Dependencies(依赖)
  • Function Tools(函数工具)
  • Results(结果)
  • Messages and chat history(消息和聊天记录)
  • Testing and Evals(测试和评估)
  • Debugging and Monitoring(调试和监控)

4.2.1 Agents(代理)

有三种方式运行Agent:

  • agent.run() :是协程,返回一个包含已完成响应的 RunResult;
  • agent.run_sync():一个普通的同步函数,它返回一个包含已完成响应的 RunResult(在内部,只是调用 loop.run_until_complete(self.run()));
  • agent.run_stream():返回 StreamedRunResult 的协程,其中包含将响应作为异步可迭代对象流式传输的方法;

下面通过一个简单的示例来演示一下这三种方式:​​​​​​​

from pydantic_ai import Agentagent = Agent('openai:gpt-4o')result_sync = agent.run_sync('What is the capital of Italy?')print(result_sync.data)#> Romeasync def main():    result = await agent.run('What is the capital of France?')    print(result.data)    #> Paris    async with agent.run_stream('What is the capital of the UK?') as response:        print(await response.get_data())        #> London

4.2.2 Models(模型)

Pydanti

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wshzd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值