PydanticOutputParser 概述PydanticOutputParser 是 LangChain 框架中用于将语言模型输出解析为结构化数据Pydantic 模型的工具。它结合了 Pydantic 的数据验证能力和 LangChain 的输出解析功能适用于需要将非结构化文本转换为结构化数据的场景。核心功能结构化输出解析将语言模型的自然语言输出转换为 Pydantic 模型定义的格式确保数据类型和字段约束符合预期。自动错误处理若模型输出不符合 Pydantic 模型定义会抛出可捕获的异常如OutputParserException。指令生成根据 Pydantic 模型自动生成提示词模板指导语言模型输出符合要求的格式。使用方法定义 Pydantic 模型创建一个继承自pydantic.BaseModel的类定义目标数据结构frompydanticimportBaseModelclassUserInfo(BaseModel):name:strage:inthobbies:list[str]初始化解析器将 Pydantic 模型传入PydanticOutputParserfromlangchain.output_parsersimportPydanticOutputParser parserPydanticOutputParser(pydantic_objectUserInfo)生成提示词模板使用parser.get_format_instructions()获取指导模型输出的指令fromlangchain.promptsimportPromptTemplate promptPromptTemplate(template提取用户信息{query}\n{format_instructions},input_variables[query],partial_variables{format_instructions:parser.get_format_instructions()})调用模型并解析将模型输出传递给解析器的parse方法# 假设 model_output 是语言模型的原始输出try:parsed_dataparser.parse(model_output)print(parsed_data.name)# 访问解析后的字段exceptExceptionase:print(f解析失败{e})示例场景输入模型原始输出{name:Alice,age:28,hobbies:[reading,hiking]}解析后结果UserInfo(nameAlice,age28,hobbies[reading,hiking])完整示例fromlangchain_core.promptsimportPromptTemplatefromlangchain_core.output_parsersimportPydanticOutputParserfrompydantic.v1importBaseModel,Field,validatorfromlangchain_openaiimportOpenAI# 创建AI模型modelOpenAI(modelgpt-3.5-turbo-instruct,temperature0,)# 定义数据模型classJoke(BaseModel):setup:strField(description设置笑话的问题)punchline:strField(description回答笑话的答案)# 设置一个校验 保证其中setup参数的值需以结尾 否则无法通过校验validator(setup)defquestion_mark(cls,field):iffield[-1]!:raiseValueError(不符合预期的问题格式!)returnfield# 创建一个pydantic输出解析器 传入数据模型parserPydanticOutputParser(pydantic_objectJoke)# 构建提示词 - 注意观察其中的占位参数promptPromptTemplate(template回答用户的输入.\n{format_instructions}\n{query}\n,input_variables[query],partial_variables{format_instructions:parser.get_format_instructions()})# 使用管道符组装函数prompt_and_modelprompt|model# 调用大模型获得输出raw_output:strprompt_and_model.invoke({query:给我讲一个笑话})print(raw_output)# 使用输出解析器解析输出结果output:Jokeparser.parse(raw_output)print(output)输出{“setup”: “为什么猫咪总是喜欢把东西丢到地上”, “punchline”: “因为它们觉得地球是圆的所以才会有东西掉下来。”}setup‘为什么猫咪总是喜欢把东西丢到地上’ punchline‘因为它们觉得地球是圆的所以才会有东西掉下来。’高级功能自定义错误消息通过 Pydantic 模型的Field添加字段描述提升模型输出准确性frompydanticimportFieldclassUserInfo(BaseModel):name:strField(description用户全名)age:intField(gt0,description正整数年龄)部分解析使用parser.parse_partial()允许部分字段缺失返回已解析字段和未解析的原始文本。流式处理结合 LangChain 的流式响应逐步验证输出片段。注意事项确保 Pydantic 模型的字段类型和约束清晰避免歧义。若模型输出为 JSON 字符串需在提示词中明确要求 JSON 格式。复杂嵌套结构可能需要更详细的提示词指导。
PydanticOutputParser 概述
发布时间:2026/7/5 2:51:58
PydanticOutputParser 概述PydanticOutputParser 是 LangChain 框架中用于将语言模型输出解析为结构化数据Pydantic 模型的工具。它结合了 Pydantic 的数据验证能力和 LangChain 的输出解析功能适用于需要将非结构化文本转换为结构化数据的场景。核心功能结构化输出解析将语言模型的自然语言输出转换为 Pydantic 模型定义的格式确保数据类型和字段约束符合预期。自动错误处理若模型输出不符合 Pydantic 模型定义会抛出可捕获的异常如OutputParserException。指令生成根据 Pydantic 模型自动生成提示词模板指导语言模型输出符合要求的格式。使用方法定义 Pydantic 模型创建一个继承自pydantic.BaseModel的类定义目标数据结构frompydanticimportBaseModelclassUserInfo(BaseModel):name:strage:inthobbies:list[str]初始化解析器将 Pydantic 模型传入PydanticOutputParserfromlangchain.output_parsersimportPydanticOutputParser parserPydanticOutputParser(pydantic_objectUserInfo)生成提示词模板使用parser.get_format_instructions()获取指导模型输出的指令fromlangchain.promptsimportPromptTemplate promptPromptTemplate(template提取用户信息{query}\n{format_instructions},input_variables[query],partial_variables{format_instructions:parser.get_format_instructions()})调用模型并解析将模型输出传递给解析器的parse方法# 假设 model_output 是语言模型的原始输出try:parsed_dataparser.parse(model_output)print(parsed_data.name)# 访问解析后的字段exceptExceptionase:print(f解析失败{e})示例场景输入模型原始输出{name:Alice,age:28,hobbies:[reading,hiking]}解析后结果UserInfo(nameAlice,age28,hobbies[reading,hiking])完整示例fromlangchain_core.promptsimportPromptTemplatefromlangchain_core.output_parsersimportPydanticOutputParserfrompydantic.v1importBaseModel,Field,validatorfromlangchain_openaiimportOpenAI# 创建AI模型modelOpenAI(modelgpt-3.5-turbo-instruct,temperature0,)# 定义数据模型classJoke(BaseModel):setup:strField(description设置笑话的问题)punchline:strField(description回答笑话的答案)# 设置一个校验 保证其中setup参数的值需以结尾 否则无法通过校验validator(setup)defquestion_mark(cls,field):iffield[-1]!:raiseValueError(不符合预期的问题格式!)returnfield# 创建一个pydantic输出解析器 传入数据模型parserPydanticOutputParser(pydantic_objectJoke)# 构建提示词 - 注意观察其中的占位参数promptPromptTemplate(template回答用户的输入.\n{format_instructions}\n{query}\n,input_variables[query],partial_variables{format_instructions:parser.get_format_instructions()})# 使用管道符组装函数prompt_and_modelprompt|model# 调用大模型获得输出raw_output:strprompt_and_model.invoke({query:给我讲一个笑话})print(raw_output)# 使用输出解析器解析输出结果output:Jokeparser.parse(raw_output)print(output)输出{“setup”: “为什么猫咪总是喜欢把东西丢到地上”, “punchline”: “因为它们觉得地球是圆的所以才会有东西掉下来。”}setup‘为什么猫咪总是喜欢把东西丢到地上’ punchline‘因为它们觉得地球是圆的所以才会有东西掉下来。’高级功能自定义错误消息通过 Pydantic 模型的Field添加字段描述提升模型输出准确性frompydanticimportFieldclassUserInfo(BaseModel):name:strField(description用户全名)age:intField(gt0,description正整数年龄)部分解析使用parser.parse_partial()允许部分字段缺失返回已解析字段和未解析的原始文本。流式处理结合 LangChain 的流式响应逐步验证输出片段。注意事项确保 Pydantic 模型的字段类型和约束清晰避免歧义。若模型输出为 JSON 字符串需在提示词中明确要求 JSON 格式。复杂嵌套结构可能需要更详细的提示词指导。