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位置将其插入。

参考资料

相关推荐
胡耀超1 分钟前
隐私计算技术全景:从联邦学习到可信执行环境的实战指南—数据安全——隐私计算 联邦学习 多方安全计算 可信执行环境 差分隐私
人工智能·安全·数据安全·tee·联邦学习·差分隐私·隐私计算
停停的茶2 小时前
深度学习(目标检测)
人工智能·深度学习·目标检测
Y200309162 小时前
基于 CIFAR10 数据集的卷积神经网络(CNN)模型训练与集成学习
人工智能·cnn·集成学习
老兵发新帖2 小时前
主流神经网络快速应用指南
人工智能·深度学习·神经网络
AI量化投资实验室3 小时前
15年122倍,年化43.58%,回撤才20%,Optuna机器学习多目标调参backtrader,附python代码
人工智能·python·机器学习
java_logo3 小时前
vllm-openai Docker 部署手册
运维·人工智能·docker·ai·容器
倔强青铜三3 小时前
苦练Python第67天:光速读取任意行,linecache模块解锁文件处理新姿势
人工智能·python·面试
算家计算3 小时前
重磅突破!全球首个真实物理环境机器人基准测试正式发布,具身智能迎来 “ImageNet 时刻”
人工智能·资讯
新智元3 小时前
苹果 M5「夜袭」高通英特尔!AI 算力狂飙 400%,Pro 三剑客火速上新
人工智能·openai
GoppViper3 小时前
什么是GEO生成式引擎优化?GEO科普:定义、原理与应用指南
人工智能·搜索引擎