5分钟明白LangChain 的输出解析器和链

本文介绍 LangChain 的输出解析器OutputParser的使用,和基于LangChain的LCEL构建

1. 输出解析器OutputParser

1.1、为什么需要OutputParser

常规的使用LangChain构建LLM应用的流程是:Prompt 输入、调用LLM 、LLM输出。有时候我们期望LLM给到的数据是格式化的数据,方便做后续的处理。

这时就需要在Prompt里设置好要求,然后LLM会在输出内容后,再将内容传给输出解析器,输出解析器会解析成我们预期的格式。

1.2、代码实践

调用系统自带的输出解析器

示例1:将调用 LLM 的结果,解析为逗号分隔的列表。比如询问某个城市有N个景点。

from langchain_openai import ChatOpenAI
from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", "{parser_instructions}"),
    ("human", "列出{cityName}的{viewPointNum}个著名景点。")
])

output_parser = CommaSeparatedListOutputParser()
parser_instructions = output_parser.get_format_instructions()
# 查看解析器的指令内容
print(parser_instructions)

final_prompt = prompt.invoke({"cityName": "南京", "viewPointNum": 3, "parser_instructions": parser_instructions})

model = ChatOpenAI(model="gpt-3.5-turbo",
                   openai_api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                   openai_api_base="https://api.aigc369.com/v1")
response = model.invoke(final_prompt)
print(response.content)

ret = output_parser.invoke(response)
print(ret)

自定义格式的输出解析器

除了使用自带的一些输出格式,还可以使用自定义的输出格式。使用步骤如下:

  • 定义数据结构类,继承pydanticBaseModel

  • 使用输出解析器PydanticOutputParser

  • 后续是常规操作:生成prompt、调用LLM执行、将输出按照Parser解析

示例2:比如给LLM一段书籍的介绍,让他按照指定的格式总结输出。

from typing import List

from langchain.output_parsers import PydanticOutputParser
from langchain.prompts import ChatPromptTemplate
from langchain.schema import HumanMessage
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI


class BookInfo(BaseModel):
    book_name: str = Field(description="书籍的名字")
    author_name: str = Field(description="书籍的作者")
    genres: List[str] = Field(description="书籍的体裁")


output_parser = PydanticOutputParser(pydantic_object=BookInfo)
# 查看输出解析器的内容,会被输出成json格式
print(output_parser.get_format_instructions())

prompt = ChatPromptTemplate.from_messages([
    ("system", "{parser_instructions} 你输出的结果请使用中文。"),
    ("human", "请你帮我从书籍的概述中,提取书名、作者,以及书籍的体裁。书籍概述会被三个#符号包围。\n###{book_introduction}###")
])

book_introduction = """
《朝花夕拾》原名《旧事重提》,是现代文学家鲁迅的散文集,收录鲁迅于1926年创作的10篇回忆性散文, [1]1928年由北京未名社出版,现编入《鲁迅全集》第2卷。
此文集作为“回忆的记事”,多侧面地反映了作者鲁迅青少年时期的生活,形象地反映了他的性格和志趣的形成经过。前七篇反映他童年时代在绍兴的家庭和私塾中的生活情景,后三篇叙述他从家乡到南京,又到日本留学,然后回国教书的经历;揭露了半殖民地半封建社会种种丑恶的不合理现象,同时反映了有抱负的青年知识分子在旧中国茫茫黑夜中,不畏艰险,寻找光明的困难历程,以及抒发了作者对往日亲友、师长的怀念之情 [2]。
文集以记事为主,饱含着浓烈的抒情气息,往往又夹以议论,做到了抒情、叙事和议论融为一体,优美和谐,朴实感人。作品富有诗情画意,又不时穿插着幽默和讽喻;形象生动,格调明朗,有强烈的感染力。
"""

model = ChatOpenAI(model="gpt-3.5-turbo",
                   openai_api_key="sk-BuQK7SGbqCZP2i2z7fF267AeD0004eF095AbC78d2f79E019",
                   openai_api_base="https://api.aigc369.com/v1")
final_prompt = prompt.invoke({"book_introduction": book_introduction,
                              "parser_instructions": output_parser.get_format_instructions()})
response = model.invoke(final_prompt)
print(response.content)
result = output_parser.invoke(response)
print(result)

2. 利用LCEL构建链

2.1、LCEL是啥

LCEL是LangChain 表达式语言(LangChain Expression Language)的简称。使用LCEL可以快速将各种组合到一起,那又是啥呢?

在LangChain里只要实现了Runnable接口,并且有invoke方法,都可以成为。实现了Runnable接口的类,可以拿上一个链的输出作为自己的输入。

比如以上代码的ChatPromptTemplate 、ChatOpenAI 、PydanticOutputParser等,都实现了Runnable接口,且都有invoke方法。

LCEL提供了多种方式将链组合起来,比如使用管道符 |,这种方式既方便书写,表达力也很强劲。

2.2、使用区别

不使用LCEL

不使用LCEL时,代码写起来是,各种invoke满天飞。比如这样:

final_prompt = prompt.invoke({"book_introduction": book_introduction,
                              "parser_instructions": output_parser.get_format_instructions()})
response = model.invoke(final_prompt)
result = output_parser.invoke(response)

使用LCEL

使用LCEL时,代码简洁,并且表达力强许多,比如这样:

chain = prompt | model | output_parser
ret = chain.invoke({"book_introduction": book_introduction,
                    "parser_instructions": output_parser.get_format_instructions()})

3、总结

本文主要聊了LangChain的输出解析器 和 使用LCEL构建链,希望对你有帮助!

文章转载自:程序员半支烟

原文链接:https://www.cnblogs.com/mangod/p/18214717

体验地址:引迈 - JNPF快速开发平台_低代码开发平台_零代码开发平台_流程设计器_表单引擎_工作流引擎_软件架构

  • 20
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值