LangChain 五 输出解析器

欢迎来到我的LangChain系列,如果您也和我一样,想通过学习LangChain开始AI应用开发。那就请一起来学习它的各个功能模块和demo实例。

LangChain 一 hello LLM - 掘金 (juejin.cn)

LangChain 二 模型 - 掘金 (juejin.cn)

LangChain 三 Data Connections - 掘金 (juejin.cn)

前言

LLM的输出为文本,但作为AI应用,为程序提供AI接口,我们比较需要的是JSON等更结构化的数据接口。本文一起来学习LangChain提供的输出解析器。

BaseOutputParser

BaseOutputParser是LangChain提供的解析器基类,其它的解析格式都继承自该类。子类通过重写get_format_instructions和parse方法来输出不同的结构。更高级的,BaseOutputParser还提供了parse_with_prompt重载方法,可以基于提示词上下文解析LLM的输出文本为特定结构。

LangChain的各种解析器

  • List parser
  • Datetime parser
  • Enum parser
  • Auto-fixing parser
  • Pydantic parser
  • Retry parser
  • Structured output parser

常用解析器

  • List Parser

将逗号分隔的文本解析为列表。

java 复制代码
from langchain.output_parsers import CommaSeparatedListOutputParser

output_parser = CommaSeparatedListOutputParser()
output_parser.parse("black, yellow, red, green, white, blue")

输出结果为

css 复制代码
['black', 'yellow', 'red', 'green', 'white', 'blue']
  • Structured Output Parser

如果我们想要的返回格式是JSON, 就使用Structured Output Parser。它可以生成指令帮助LLM返回结构化数据文本,同时完成文本到结构化数据的解析工作。

javascript 复制代码
from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.llms import OpenAI

首先,从langchain.output_parsers 输出器模块中引入StructuredOutputParser结构化输出解析器和ResponseSchema响应schema。 接着引入PromptTemplate类,ChatPromptTemplate类和用户聊天HumanMessagePromptTemplate,最后引入langchain模型模块里的OpenAI。

ini 复制代码
response_schemas = [
    ResponseSchema(name="answer", description="answer to the user's question"),
    ResponseSchema(name="source", description="source referred to answer the user's question, should be a website.")
]

定义了响应格式, 一个answer, 一个source。即我们希望大模型返回的内容提供的JSON格式包含两个字段,answer和source, 通过description字段,llm语义化理解,将结果交给answer字段,将结果的出处交给source

bash 复制代码
response_schemas=[ResponseSchema(name='answer', description="answer to the user's question.", type='string'), ResponseSchema(name='source', description="source referred to answer the user's question, should be a website.", type='string')]

从上面的返回,更让们感觉接近JSON的定义

ini 复制代码
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)

  生成结构化输出实例。比上图可以看出,langchain的out_put 模块就是通过一些类和流程, 简化我们生成prompt 中定制输出结果的方式。

ini 复制代码
# 获取响应格式化的指令
format_instructions = output_parser.get_format_instructions()
ini 复制代码
# partial_variables允许在代码中预填充提示此模版的部分变量。这类似于接口,抽象类之间的关系
prompt = PromptTemplate(
    template="answer the users question as best as possible.\n{format_instructions}\n{question}",
    input_variables=["question"],
    partial_variables={"format_instructions": format_instructions}
)

输出为 input_variables=['question'] output_parser=None partial_variables={'format_instructions': 'The output should be a markdown code snippet formatted in the following schema, including the leading and trailing "json" and "":\n\njson\n{\n\t"answer": string // answer to the user\'s question.\n\t"source": string // source referred to answer the user\'s question, should be a website.\n}\n'} template='answer the users question as best as possible.\n{format_instructions}\n{question}' template_format='f-string' validate_template=True   从以上代码可知,原来LangChain提供的output_parser模块,抽象了我们prompt 设计输出结果的写法。partial_variables帮助我们指定输出格式, 取名format_instructions。

ini 复制代码
model = OpenAI(temperature=0)
response = prompt.format_prompt(question="what's the capital of France?")
output = model(response.to_string())
output_parser.parse(output)

OpenAI返回模型实例,prompt.format_prompt生成模板,output_parser.parse将得到的结果返回。

rust 复制代码
{
    'answer': 'Paris',
    'source': 'https://www.worldatlas.com/articles/what-is-the-capital-of-france.html'
}

总结

之前是通过Prompt 手动设计响应格式, 这次我们通过LangChain提供的StructuredOutputParser,先使用ResponseSchema 定义格式,再通过StructuredOutputParser.from_response_schemas得到parser, 最后 output_parser.get_format_instructions()得到插入到prompt中的响应指令, partial_variables位置将其插入。

参考资料

相关推荐
式5163 分钟前
大模型学习基础(九)LoRA微调原理
人工智能·深度学习·学习
GISer_Jing3 分钟前
2026年前端开发目标(From豆包)
前端·学习·aigc
CCPC不拿奖不改名5 分钟前
python基础面试编程题汇总+个人练习(入门+结构+函数+面向对象编程)--需要自取
开发语言·人工智能·python·学习·自然语言处理·面试·职场和发展
菜鸟‍6 分钟前
【论文学习】一种用于医学图像分割单源域泛化的混合双增强约束框架 || 视觉 Transformer 在通用图像分割中的 “缺失环节”
人工智能·深度学习·计算机视觉
五度易链-区域产业数字化管理平台7 分钟前
数观丨2026年半导体集成电路产业融资分析
大数据·人工智能
应用市场7 分钟前
机器学习中的正向反馈循环:从原理到实战应用
人工智能·深度学习·机器学习
Allen正心正念202530 分钟前
GGUF/GPTQ/AWQ模型对比
人工智能
Coder_Boy_31 分钟前
基于SpringAI的在线考试系统-知识点管理模块完整优化方案
java·前端·人工智能·spring boot
Godspeed Zhao32 分钟前
从零开始学AI3——背景知识2
人工智能
康康的AI博客35 分钟前
多模态大一统:从GPT-4突破到AI领域质的飞跃之路
人工智能·ai