PydanticToolsParser 工具(tool call)把 LLM 生成的文本转成结构化的数据(Pydantic 模型)过程中遇到的坑

发布于:2025-02-27 ⋅ 阅读:(14) ⋅ 点赞:(0)

PydanticToolsParser 的作用
PydanticToolsParser 是一个工具,主要作用是 把 LLM 生成的文本转成结构化的数据(Pydantic 模型),让代码更容易使用这些数据进行自动化处理。

换句话说,AI 生成的文本通常是自然语言,代码不好直接解析,比如 “请帮我订明天上午 10 点到上海的机票”。
如果用 PydanticToolsParser,就可以把这句话解析成一个 Python 对象,比如:

FlightBookingRequest(
    destination="上海",
    time="2025-02-27 10:00:00"
)

这样,代码就可以直接使用这个对象去调用订票 API,自动执行任务。

但是我们在调用工具的过程中会遇到类似以下问题:
在这里插入图片描述

可以从以下几个方面去思考排查

  1. 模型不支持或工具调用能力有限

    • 有用户建议更换模型,例如使用“llama-3.3-70b-versatile”或者“llama-3.1-8b-instant”(参见citeturn0search0中的讨论),这些模型在工具调用的兼容性和稳定性上表现更佳。
  2. 提示(prompt)设计问题

    • 如果提示不够明确,模型可能会生成不完整或格式错误的工具调用请求。例如,提示中没有充分说明需要返回完整的 JSON 格式,导致生成的参数中缺失了某些字段。

如何调试与解决

方案一:调整提示格式
确保在提示中明确说明所需的 JSON 格式。例如,在提示中增加类似下面的说明:

query = """
请使用 MathCalculationRequest 工具计算 34 * 5,并按照如下 JSON 格式返回:
{
  "expression": "34 * 5",
  "result": 170.0
}
"""

这样模型能获得更多上下文,从而更准确地生成符合要求的输出。

方案二:更换模型
如前面搜索讨论中建议,尝试使用其他推荐的模型,例如“llama-3.3-70b-versatile”。更换模型的方法如下:

llm = init_chat_model("llama-3.3-70b-versatile", model_provider="groq")

这有助于绕过当前模型在工具调用方面存在的问题。

我遇到的问题主要出在 LLM模型不够强,更换参数更大的模型。


原始有问题的代码如下:

import getpass
import os
from datetime import datetime, timedelta
from typing import Union
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers.openai_tools import PydanticToolsParser


# 1. 获取 API Key
if not os.environ.get("GROQ_API_KEY"):
    os.environ["GROQ_API_KEY"] = getpass.getpass("Enter API key for Groq: ")

# 2. 初始化 LLM
llm = init_chat_model("llama3-8b-8192", model_provider="groq")

# 3. 定义结构化数据模型
class FlightBookingRequest(BaseModel):
    destination: str
    time: str

class ReminderRequest(BaseModel):
    event: str
    time: str

class MathCalculationRequest(BaseModel):
    expression: str
    result: float

# 4. 绑定工具
tools = [FlightBookingRequest, ReminderRequest, MathCalculationRequest]
llm_with_tools = llm.bind_tools(tools)

# 5. 解析 LLM 输出
parser = PydanticToolsParser(tools=tools)
chain = llm_with_tools | parser

def handle_request(request: Union[FlightBookingRequest, ReminderRequest, MathCalculationRequest]):
    print(request)
    if isinstance(request, FlightBookingRequest):
        print(f"正在预订 {request.time} 飞往 {request.destination} 的机票...")
    elif isinstance(request, ReminderRequest):
        print(f"已设置提醒:{request.time} - {request.event}")
    elif isinstance(request, MathCalculationRequest):
        print(f"计算结果:{request.expression} = {request.result}")

    
query =  "用MathCalculationRequest工具解析这个表达式: 34 * 5 "

structured_data = chain.invoke(query)  # AI 解析文本
print(structured_data)
handle_request(structured_data)  # 执行相应任务

修改后的代码请点击查看教程

总结

  • 错误信息表明:模型生成的工具调用请求格式不正确,无法成功解析为 Pydantic 对象。
  • 最有可能的原因是当前使用的 Groq 模型(“llama3-8b-8192”)在工具调用功能上存在局限性或提示设计不足。
  • 推荐尝试调整提示(prompt)、更新依赖库或更换为其他推荐的模型以解决问题。