还在手动写正则解析GPT的返回内容么,试试Pydantic吧少年

在开发过程中,我们经常需要与GPT等大模型进行交互,并解析其返回的内容。传统的做法可能是手动编写正则表达式来提取所需的信息,但这种方式不仅繁琐,还容易出错。今天,我将介绍一种更优雅、更高效的方式------使用Pydantic来解析GPT的返回内容。

什么是Pydantic?

Pydantic 是一个Python库,主要用于数据验证和设置管理。它通过Python类型注解来定义数据模型,并自动验证输入数据的合法性。Pydantic的强大之处在于它能够将复杂的JSON数据直接转换为Python对象,极大地简化了数据处理流程。

为什么选择Pydantic?

  1. 类型安全:Pydantic利用Python的类型注解,确保数据的类型正确性。
  2. 自动验证:Pydantic会自动验证输入数据是否符合定义的模型,减少手动检查的工作量。
  3. 代码简洁:通过定义数据模型,代码更加清晰易读,维护起来也更加方便。
  4. 与GPT完美结合:Pydantic可以轻松解析GPT返回的JSON数据,并将其转换为Python对象。

示例代码

下面是一个使用Pydantic解析GPT返回内容的示例代码:

python 复制代码
from pydantic import BaseModel
from openai import OpenAI

# 定义数据模型
class Step(BaseModel):
    explanation: str
    output: str

class MathResponse(BaseModel):
    steps: list[Step]
    final_answer: str

# 初始化OpenAI客户端
client = OpenAI(
    base_url="http://your_base_url/v1/",
    api_key="your_api_key_here"
)

# 发送请求并解析返回内容
completion = client.beta.chat.completions.parse(
    model="gpt-4o",
    extra_headers={
        "apikey": "your_api_key_here"
    },
    messages=[
        {"role": "system", "content": "You are a helpful math tutor."},
        {"role": "user", "content": "solve 8x + 31 = 2"},
    ],
    response_format=MathResponse,
)

# 处理返回结果
message = completion.choices[0].message
print(message.parsed)

if message.parsed:
    print(message.parsed.steps)
    print("---\n")
    print(message.parsed.final_answer)
else:
    print(message.refusal)

代码解析

  1. 定义数据模型 :我们首先定义了两个Pydantic模型StepMathResponse,分别表示解题步骤和最终的数学解答。
  2. 初始化OpenAI客户端:通过OpenAI库初始化客户端,并设置API密钥和基础URL。
  3. 发送请求并解析返回内容 :使用client.beta.chat.completions.parse方法发送请求,并将返回的JSON数据解析为MathResponse对象。
  4. 处理返回结果:根据解析结果,输出解题步骤和最终答案。

运行结果

lua 复制代码
steps=[Step(explanation='Start by isolating the term with the variable. To do that, subtract 31 from both sides of the equation to maintain the equality.', output='8x + 31 - 31 = 2 - 31'), Step(explanation='Simplify both sides of the equation. On the left side, the 31 and -31 cancel out, leaving you with 8x. On the right side, 2 - 31 equals -29.', output='8x = -29'), Step(explanation='To solve for x, divide both sides of the equation by 8 to isolate x.', output='x = -\frac{29}{8}')] final_answer='x = -\frac{29}{8}'
[Step(explanation='Start by isolating the term with the variable. To do that, subtract 31 from both sides of the equation to maintain the equality.', output='8x + 31 - 31 = 2 - 31'), Step(explanation='Simplify both sides of the equation. On the left side, the 31 and -31 cancel out, leaving you with 8x. On the right side, 2 - 31 equals -29.', output='8x = -29'), Step(explanation='To solve for x, divide both sides of the equation by 8 to isolate x.', output='x = -\frac{29}{8}')]
---

x = -\frac{29}{8}

总结

通过使用Pydantic,我们可以轻松地将GPT返回的JSON数据转换为Python对象,避免了手动编写正则表达式的繁琐过程。这种方式不仅提高了代码的可读性和可维护性,还减少了出错的可能性。如果你还在手动解析GPT的返回内容,不妨试试Pydantic吧,少年!

相关推荐
程序员爱钓鱼16 分钟前
Go语言实战案例-创建模型并自动迁移
后端·google·go
javachen__22 分钟前
SpringBoot整合P6Spy实现全链路SQL监控
spring boot·后端·sql
uzong6 小时前
技术故障复盘模版
后端
GetcharZp6 小时前
基于 Dify + 通义千问的多模态大模型 搭建发票识别 Agent
后端·llm·agent
桦说编程7 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
IT毕设实战小研7 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi7 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
阿华的代码王国8 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Jimmy8 小时前
AI 代理是什么,其有助于我们实现更智能编程
前端·后端·ai编程
AntBlack9 小时前
不当韭菜V1.1 :增强能力 ,辅助构建自己的交易规则
后端·python·pyqt