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

参考资料

相关推荐
kimi-222几秒前
LangChain 里的 chatmodel.bind_tools 和 ReAct Agent
人工智能
zhangfeng113317 分钟前
计算机视觉vc 3D 希尔伯特曲线 基础介绍,人工智能
人工智能·计算机视觉·3d
没事别瞎琢磨21 分钟前
十一、审计与 Run Session——每一步操作都被记录
人工智能·node.js
没事别瞎琢磨22 分钟前
十六、AgentSandbox——把所有模块串起来的编排类
人工智能·node.js
George37524 分钟前
当 Loop Engineering 成为行业共识,我发现自己的开源项目已经实践了 3 个月
人工智能
没事别瞎琢磨26 分钟前
十二、网络代理与白名单规则引擎
人工智能·node.js
ZengLiangYi29 分钟前
TypeScript 项目配置:tsconfig、ESM、路径别名
javascript·typescript·aigc
马士兵教育29 分钟前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
没事别瞎琢磨30 分钟前
十四、Git Worktree 隔离执行
人工智能·node.js
安全指北针37 分钟前
大模型时代,谁在领跑中国AI安全赛道?中国AI安全产品市场分析
人工智能