系列文章地址
【可能是全网最丝滑的LangChain教程】一、LangChain介绍-优快云博客
【可能是全网最丝滑的LangChain教程】二、LangChain安装-优快云博客
【可能是全网最丝滑的LangChain教程】三、快速入门LLM Chain-优快云博客
【可能是全网最丝滑的LangChain教程】四、快速入门Retrieval Chain-优快云博客
【可能是全网最丝滑的LangChain教程】五、快速入门Conversation Retrieval Chain-优快云博客
【可能是全网最丝滑的LangChain教程】六、快速入门Agent-优快云博客
【可能是全网最丝滑的LangChain教程】七、LCEL表达式语言-优快云博客
【可能是全网最丝滑的LangChain教程】八、LangChain进阶之LLM
【可能是全网最丝滑的LangChain教程】九、LangChain进阶之Chat Model
【可能是全网最丝滑的LangChain教程】十、LangChain进阶之Prompts
01 Output Parsers 介绍
输出解析器是LangChain的一个关键组件,它们的作用是将模型生成的文本输出转换成结构化的数据,以便更容易地使用和分析。
简单来说就是:模型输出------>结构化数据。
如果你正在从事或者你正打算从事大模型应用相关研发,我想你都能明白结构化数据输出的重要性。
02 原理解析
技术还是要学到本质,掌握本质就能以不变应万变。这里以_CSV Parser_为例。
from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain_core.prompts import PromptTemplate
"""
1. 这是csv数据解析器
2. CSV数据默认以逗号分割
"""
output_parser = CommaSeparatedListOutputParser()
"""
1. 调用方法生成一段字符串
2. 字符串内容是:Your response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`
"""
format_instructions = output_parser.get_format_instructions()
"""
1. 构造输入提示
2. subject内容是用户的输入,format_instructions上面已经备注
3. partial_variables作用是一次输入,多次使用。(目的是不用没次都设置)
"""
prompt = PromptTemplate(
template="列举5条与{subject}有关的经典语录。\n{format_instructions}",
input_variables=["subject"],
partial_variables={
"format_instructions": format_instructions},
)
"""
1. 链式调用执行(LCEL表达式)
2. 提示---模型---输出解析器
"""
chain = prompt | model | output_parser
"""
1. 最终给到模型的输入是:
列举5条与江湖有关的经典语录。\nYour response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`
2. 模型的输出是一段字符串:刀光剑影,快意恩仇, 一诺千金, 路见不平,拔刀相助, 人在江湖,身不由己, 血雨腥风,笑傲江湖。
3. 输出解析器解析成list:['刀光剑影,快意恩仇', '一诺千金', '路见不平,拔刀相助', '人在江湖,身不由己', '血雨腥风,笑傲江湖。']
"""
chain.invoke({
"subject": "江湖"})
"""
输出:
['刀光剑影,快意恩仇', '一诺千金', '路见不平,拔刀相助', '人在江湖,身不由己', '血雨腥风,笑傲江湖。']
"""
CSV Parser是怎么解析的?答案很简单,源码里就一个方法,方法内部就一行代码
def parse(self, text: str) -> List\[str\]:
"""Parse the output of an LLM call."""
return \[part.strip() for part in text.split(",")\]
所以,你在阅读我这篇文章的时候能想到其他的输出解析器的实现原理吗?给我留言,让我看看~
03 基本使用
这里我将介绍LangChain中目前的常用输出解析器的使用。
CSV parser
CSV输出解析器,用于将模型的输出,按照逗号分割,解析成列表。使用上面已经介绍,这里不再重复说明。
Datetime parser
顾名思义,解析输出中的时间信息。
from langchain.output_parsers import DatetimeOutputParser
output_parser = DatetimeOutputParser()
template = """Answer the users question:
{question}
{format_instructions}"""
prompt = PromptTemplate.from_template(
template,
partial_variables={
"format_instructions": output_parser.get_format_instructions()},
)
chain = prompt | model | output_parser
output = chain.invoke({
"question": "中国人民共和国哪一年成立?"})
print(output)
本质是这句话:Answer the users question:\n\nxxxxxx哪一年成立?\n\nWrite a datetime string that matches the following pattern: ‘%Y-%m-%dT%H:%M:%S.%fZ’.\n\nExamples: 0018-02-08T10:24:18.419248Z, 0638-03-23T17:42:46.562176Z, 0093-01-29T12:37:35.194184Z\n\nReturn ONLY this string, no other words!
解析方法是
format = "%Y-%m-%dT%H:%M:%S.%fZ"
"""The string value that used as the datetime format."""
def parse(self, response: str) -> datetime:
try:
return datetime.strptime(response.strip(), self.format)
except ValueError as e:
raise OutputParserException(
f"Could not parse datetime string: {
response}"
) from e
Enum parser
顾名思义,将模型输出解析成枚举类型。
from langchain.output_parsers.enum import EnumOutputParser
from enum import Enum
class Colors(Enum):
RED = "红色"
GREEN = "绿色"
BLUE = "蓝色"
parser = EnumOutputParser(enum=Colors)
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate.from_template(
"""请回答这个国家的人喜欢什么颜色。
> Country: {country}
Instructions: {in