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

参考资料

相关推荐
冬奇Lab7 小时前
Workflow 系列(06):安全——跨步骤注入传播与四层防御
人工智能·工作流引擎
冬奇Lab7 小时前
每日一个开源项目(第149篇):RAG-Anything - 把图片、表格、公式当成一等公民的多模态 RAG 框架
人工智能·开源
米小虾7 小时前
AI Agent 安全实战指南:当智能体开始"不听话",开发者该如何应对?
人工智能·安全·agent
米小虾8 小时前
联合国发布首份全球AI评估报告:我们正站在AI治理的十字路口
aigc·ai编程
IT_陈寒9 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
阿里云大数据AI技术11 小时前
构建高转化海外电商搜索:阿里云OpenSearch行业算法版的全链路智能优化策略实战
人工智能·搜索引擎
Awu122711 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
字节跳动视频云技术团队11 小时前
让 Agent 成为音视频工作台:AI MediaKit CLI + Skill 发布
人工智能·音视频开发
魏祖潇11 小时前
framework 整合实战——DDD/TDD/SDD 三件套在 framework 仓的真实落地
人工智能·后端