欧米茄手表价格及图片官方网站,江阴高新区建设促进服务中心网站,wordpress 页面标题,中国最厉害的室内设计师【大语言模型LangChain】 ModelsIO OutputParsers详解 一、简介二、OutputParsers 的优势三、解析器类型四、实战示例1、String 解析器2、Json 解析器3、Pydantic 解析器4、结构化输出解析器5、OpenAI 函数输出解析器5.1、JsonOutputFunctionsParser5.2、JsonKeyOutputFunction… 【大语言模型LangChain】 ModelsIO OutputParsers详解 一、简介二、OutputParsers 的优势三、解析器类型四、实战示例1、String 解析器2、Json 解析器3、Pydantic 解析器4、结构化输出解析器5、OpenAI 函数输出解析器5.1、JsonOutputFunctionsParser5.2、JsonKeyOutputFunctionsParser5.3、PydanticOutputFunctionsParser5.4、PydanticAttrOutputFunctionsParser 一、简介
基于前边的章节LangChain 已经可以轻松实现帮用户拿到大语言模型的输出然而不难发现前文介绍的模型调用显示返回的内容通常是一个类(class)的实例其中包含了 content 以及其他一些额外的参数。
对于模型调用者来说他们可能只关心 content 的内容也就是模型对输入内容的回答或者希望得到一个可操作的数据结构比如 JSON 格式的数据。
二、OutputParsers 的优势
LangChain 设计的初衷之一旨在让用户更便捷地使用大模型所以为了解决输出内容格式化的问题。
通过使用 LangChain 提供的解析器用户可以更轻松地获取模型的输出并直接处理或操作所需的内容而无需进行额外的转换或处理。
三、解析器类型
根据业务需求开发者通常需要大模型返回一个结构化的数据方便后续的逻辑可以根据这个数据进行进一步的处理。
然而不同的输入结果可能需要相对应的解析器来做处理LangChain 同样提供了几种常见的解析器类型
String 解析器Json 解析器Pydantic 解析器结构化输出解析器OpenAI 函数输出解析器
四、实战示例
1、String 解析器
LangChain 提供了 StrOutputParser这是一个专门用来处理模型输出内容的解析器。当模型输出的内容是字符串格式的时候StrOutputParser 能够直接返回模型输出的 content 字符串内容。
这使得用户无需进行复杂的数据解析操作可以直接获取模型输出的内容字符串从而更方便地进行后续处理或使用代码示例如下所示
# 定义模型
import osfrom langchain_core.messages import SystemMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain_openai import ChatOpenAIos.environ[OPENAI_API_KEY] xxxxxxxxxxxxxxxxx # 将个人token替换到这个位置
os.environ[OPENAI_API_BASE] xxxxxxxxxxxxxxxxxmodel ChatOpenAI()
# 提示词模板
messages ChatPromptTemplate.from_messages([SystemMessage(content你是一个翻译各种语言的助手),HumanMessagePromptTemplate.from_template(把 {poetry} 的原文诗翻译为英文)
])
# 输出解析器
parser StrOutputParser()
# 调用链
chain_with_parser messages | model | parser # 使用输出解析器
res_with_parser chain_with_parser.invoke({poetry: 静夜思})
print(res_with_parser)
print(type(res_with_parser))print(---------------------不使用parser---------------------------------)chain_with_parser messages | model
res_with_parser chain_with_parser.invoke({poetry: 静夜思})
print(res_with_parser)
print(type(res_with_parser))结果对比
2、Json 解析器
当模型输出的内容是一个 JSON 格式时LangChain 也提供了相应的解析器 JsonOutputParser。该解析器能够根据 JSON 结构的内容将其转换为 Python 对应的字典格式的数据使得用户能够更方便地处理和操作模型输出的结果。代码示例如下所示
import osfrom langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAIos.environ[OPENAI_API_KEY] xxxxxxxxxxxxxxx # 将个人token替换到这个位置
os.environ[OPENAI_API_BASE] xxxxxxxxxxxxxxx# 定义模型
model ChatOpenAI()
# Json输出解析器
parser JsonOutputParser()
# 模板提示输出 json 格式的回答
prompt PromptTemplate(template根据用户的输入给出一段中文宣传语 \n{format_instructions}\n{ads}\n,input_variables[ads],partial_variables{format_instructions: parser.get_format_instructions()},
)
# 调用链 包含json输出解析器
chain_with_parser prompt | model | parser
res_with_parser chain_with_parser.invoke({ads: 音乐节})
print(res_with_parser)
print(type(res_with_parser))print(------------------------不加json解析器------------------------)# 调用链 包含json输出解析器
chain_with_parser prompt | model
res_with_parser chain_with_parser.invoke({ads: 音乐节})
print(res_with_parser)
print(type(res_with_parser)) 3、Pydantic 解析器
除了支持解析 JSON 格式外LangChain 还提供了对 Pydantic 模型的解析器 PydanticOutputParser。
LangChain 的 Pydantic 解析器可以将模型输出的内容解析为 Pydantic 模型所定义的数据结构。这使得用户可以更加方便地使用 Pydantic 的功能例如数据验证、序列化和反序列化等代码示例如下
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
import osos.environ[OPENAI_API_KEY] xxxxxxxxxxxxx # 将个人token替换到这个位置
os.environ[OPENAI_API_BASE] xxxxxxxxxxxxxclass Translation(BaseModel):origin_str: str Field(description原始输入的值)trans_str: str Field(description翻译后的值)# 定义一个模型
model ChatOpenAI(temperature0)
# 使用 pydantic 输出解析器解析 Translation 类
parser PydanticOutputParser(pydantic_objectTranslation)
# 提示模板
prompt PromptTemplate(template翻译用户输入的内容为英文\n{format_instructions}\n{query}\n,input_variables[query],partial_variables{format_instructions: parser.get_format_instructions()},
)
# 包含解析器的调用链
chain_with_parser prompt | model | parser
res_parser chain_with_parser.invoke({query: 赏花})
# 输出返回的内容及类型
print(res_parser)
print(type(res_parser)) 4、结构化输出解析器
LangChain 提供了一种自定义解析方案即使用 schema 结构。用户可以根据需要定义自己的 schema并使用 LangChain 的 StructuredOutputParser类来解析符合该 schema 的数据。
这种方式让用户能够更灵活地处理各种类型的模型输出数据而无需依赖特定的数据验证库或框架。StructuredOutputParser 为用户提供了一种通用的解析方式使他们能够简单地将模型输出的数据转换为符合自定义 schema 的数据对象。 代码示例如下
from langchain.output_parsers import ResponseSchema, StructuredOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAIimport osos.environ[OPENAI_API_KEY] xxxxxxxxxxxxxxx # 将个人token替换到这个位置
os.environ[OPENAI_API_BASE] xxxxxxxxxxxxxxxresponse_schemas [ResponseSchema(nameslogan, description宣传语内容),ResponseSchema(namereq, description宣传语限制在10个字符内),
]
output_parser StructuredOutputParser.from_response_schemas(response_schemas)
prompt PromptTemplate(template根据用户输入的商品给出宣传语\n{format_instructions}\n{goods},input_variables[goods],partial_variables{format_instructions: output_parser.get_format_instructions()},
)model ChatOpenAI(temperature0)
chain_with_parser prompt | model | output_parser
res_with_parser chain_with_parser.invoke({goods: 音乐节})
print(res_with_parser)
print(type(res_with_parser))print(-----------------不加解析器-----------------------)model ChatOpenAI(temperature0)
chain_with_parser prompt | model
res_with_parser chain_with_parser.invoke({goods: 音乐节})
print(res_with_parser)
print(type(res_with_parser)) 5、OpenAI 函数输出解析器
LangChain 支持解析 OpenAI 提供的函数调用并提供了以下四种形式来处理输出结果
JsonOutputFunctionsParser生成 JSON 格式的结果。JsonKeyOutputFunctionsParser指定 JSON 中某个 key 对应的 value。PydanticOutputFunctionsParser解析 Pydantic 模型的结构。PydanticAttrOutputFunctionsParser直接输出模型中某个参数的值。
5.1、JsonOutputFunctionsParser
# 调用大模型
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers.openai_functions import JsonOutputFunctionsParserimport osos.environ[OPENAI_API_KEY] xxxxxxxxxxxxx # 将个人token替换到这个位置
os.environ[OPENAI_API_BASE] xxxxxxxxxxxxxmodel ChatOpenAI()
# 提示词模板
prompt ChatPromptTemplate.from_template(出给一个关于 {goods} 的广告宣传语)
# 自定义函数
functions [{name: advertisement,description: 一段广告词,parameters: {type: object,properties: {goods: {type: string, description: 要进行广告的产品},ads: {type: string, description: 广告词},},required: [goods, ads],},}
]# todo JsonOutputFunctionsParser# 创建调用链 包含输出解析器
chain_json_with_parser prompt | model.bind(function_call{name: advertisement},functionsfunctions) | JsonOutputFunctionsParser()
res_json_with_parser chain_json_with_parser.invoke({goods: 冰淇淋})
print(res_json_with_parser)
print(type(res_json_with_parser))print(---------------------------不加JsonOutputFunctionsParser---------------------------)chain_json_with_parser prompt | model.bind(function_call{name: advertisement},functionsfunctions)
res_json_with_parser chain_json_with_parser.invoke({goods: 冰淇淋})
print(res_json_with_parser)
print(type(res_json_with_parser))5.2、JsonKeyOutputFunctionsParser
# 调用大模型
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers.openai_functions import JsonKeyOutputFunctionsParser
import osos.environ[OPENAI_API_KEY] xxxxxxxxxxxxx # 将个人token替换到这个位置
os.environ[OPENAI_API_BASE] xxxxxxxxxxxxxmodel ChatOpenAI()
# 提示词模板
prompt ChatPromptTemplate.from_template(出给一个关于 {goods} 的广告宣传语)
# 自定义函数
functions [{name: advertisement,description: 一段广告词,parameters: {type: object,properties: {goods: {type: string, description: 要进行广告的产品},ads: {type: string, description: 广告词},},required: [goods, ads],},}
]# todo JsonOutputFunctionsParser# 创建调用链 包含输出解析器
chain_key_parser prompt | model.bind(function_call{name: advertisement},functionsfunctions) | JsonKeyOutputFunctionsParser(key_nameads)
res_key_parser chain_key_parser.invoke({goods: 摩托车})
print(res_key_parser)
print(type(res_key_parser))print(---------------------------不加JsonKeyOutputFunctionsParser---------------------------)chain_key_parser prompt | model.bind(function_call{name: advertisement},functionsfunctions)
res_key_parser chain_key_parser.invoke({goods: 摩托车})
print(res_key_parser)
print(type(res_key_parser))5.3、PydanticOutputFunctionsParser
# 调用大模型
from langchain_core.output_parsers.openai_functions import PydanticOutputFunctionsParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.utils.function_calling import convert_to_openai_function
from langchain_openai import ChatOpenAI
import osfrom pydantic import BaseModel,Fieldos.environ[OPENAI_API_KEY] xxxxxxxxxxxxx # 将个人token替换到这个位置
os.environ[OPENAI_API_BASE] xxxxxxxxxxxxxclass Advertisement(BaseModel):origin_str: str Field(description原始输入的值)trans_str: str Field(description翻译后的值)# 自定义函数
functions [{name: advertisement,description: 一段广告词,parameters: {type: object,properties: {goods: {type: string, description: 要进行广告的产品},ads: {type: string, description: 广告词},},required: [goods, ads],},}
]model ChatOpenAI()
# 提示词模板
prompt ChatPromptTemplate.from_template(出给一个关于 {goods} 的广告宣传语)
# 定义解析器
parser PydanticOutputFunctionsParser(pydantic_schemaAdvertisement)
# 调用函数
openai_functions [convert_to_openai_function(Advertisement)]
# 创建调用链
chain_pydantic_parser prompt | model.bind(functionsopenai_functions) | parser
# 输出大模型执行结果
res_pydantic_parser chain_pydantic_parser.invoke({goods: 饮料})
print(res_pydantic_parser)
print(type(res_pydantic_parser))5.4、PydanticAttrOutputFunctionsParser
# 调用大模型
from langchain_core.output_parsers.openai_functions import PydanticOutputFunctionsParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.utils.function_calling import convert_to_openai_function
from langchain_openai import ChatOpenAI
import osfrom pydantic import BaseModel,Fieldos.environ[OPENAI_API_KEY] xxxxxxxxxxxxx # 将个人token替换到这个位置
os.environ[OPENAI_API_BASE] xxxxxxxxxxxxxclass Advertisement(BaseModel):origin_str: str Field(description原始输入的值)trans_str: str Field(description翻译后的值)# 自定义函数
functions [{name: advertisement,description: 一段广告词,parameters: {type: object,properties: {goods: {type: string, description: 要进行广告的产品},ads: {type: string, description: 广告词},},required: [goods, ads],},}
]model ChatOpenAI()
# 提示词模板
prompt ChatPromptTemplate.from_template(出给一个关于 {goods} 的广告宣传语)print(---------------------------------PydanticAttrOutputFunctionsParser--------------------------------)from langchain_core.output_parsers.openai_functions import PydanticAttrOutputFunctionsParser# 定义 pydantic 参数输出解析器传入 Pydantic 模型和需要输出的属性名
parser PydanticAttrOutputFunctionsParser(pydantic_schemaAdvertisement, attr_nametrans_str)
# 调用函数
openai_functions [convert_to_openai_function(Advertisement)]
# 创建调用链 包含输出解析器
chain_pydantic_parser prompt | model.bind(functionsopenai_functions) | parser
# 传入参数执行
res_pydantic_parser chain_pydantic_parser.invoke({goods: 饮料})
print(res_pydantic_parser)
print(type(res_pydantic_parser))