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 小时前
基于C-MTEB/CMedQAv2-rerankingv的Qwen3-1.7b模型微调-demo
人工智能
飞哥数智坊2 小时前
AI 编程一年多,我终于明白:比技巧更重要的,是熟练度
人工智能·ai编程
新智元2 小时前
收手吧 GPT-5-Codex,外面全是 AI 编程智能体!
人工智能·openai
IT_陈寒2 小时前
Java 性能优化:5个被低估的JVM参数让你的应用吞吐量提升50%
前端·人工智能·后端
阿里云云原生3 小时前
阿里云基础设施 AI Tech Day AI 原生,智构未来——AI 原生架构与企业实践专场
人工智能
Memene摸鱼日报4 小时前
「Memene 摸鱼日报 2025.9.16」OpenAI 推出 GPT-5-Codex 编程模型,xAI 发布 Grok 4 Fast
人工智能·aigc
xiaohouzi1122334 小时前
OpenCV的cv2.VideoCapture如何加GStreamer后端
人工智能·opencv·计算机视觉
用户125205597084 小时前
解决Stable Diffusion WebUI训练嵌入式模型报错问题
人工智能
Juchecar4 小时前
一文讲清 nn.LayerNorm 层归一化
人工智能
martinzh4 小时前
RAG系统大脑调教指南:模型选择、提示设计与质量控保一本通
人工智能