什么是模型I/O?
对模型的使用,我们可以分成三部分,首先是对模型的format,在对模型的调用,最后再是输出,这个过程在LangChain中被称为Model I/O。
Format 提示模板
大语言模型能否运用的好,在于如何对大语言模型有很好的提示构建,我们可以使用LangChain中自带的库来创建提示模版。
如下是一个简单的LangChain提示模板,并对结果进行输出:
# 导入LangChain中的提示模板
from langchain.prompts import PromptTemplate
# 创建原始模板
template = """您是一位专业的鲜花店文案撰写员。\n
对于售价为 {price} 元的 {flower_name} ,您能提供一个吸引人的简短描述吗?
"""
# 根据原始模板创建LangChain提示模板
prompt = PromptTemplate.from_template(template)
# 打印LangChain提示模板的内容
print(prompt)
input_variables=['flower_name', 'price'] template='您是一位专业的鲜花店文案撰写员。\n\n对于售价为 {price} 元的 {flower_name} ,您能提供一个吸引人的简短描述吗?\n'
其中PromptTemplate的from_template方法就是将template转换成一个更容易操作的PromptTemplate对象。
predict 语言模型
在LangChain中支持三种大模型,在掘金小册中有讲述,在此不再重复。让我们看一个简单的案例
# 设置OpenAI API Key
import os
os.environ["OPENAI_API_KEY"] = '你的Open AI API Key'
# 导入LangChain中的OpenAI模型接口
from langchain_openai import OpenAI
# 创建模型实例
model = OpenAI(model_name='gpt-3.5-turbo-instruct')
# 输入提示
input = prompt.format(flower_name=["玫瑰"], price='50')
# 得到模型的输出
output = model.invoke(input)
# 打印输出内容
print(output)
为了得到模型的输出,我们将模板实例化,再调用模型得到模型的输出:
content='50元的玫瑰,娇艳欲滴的爱情使者。每一片花瓣都诉说着浓烈的爱意,独特的芬芳萦绕心间,是表达深情的不二之选。
parse 输出解析
最后这一过程是为了让大语言模型在输出时能输出结构化的数据,保证其效率的高效。比如我想要返回的回答包括{description:和reason:} 我们就需要LangChain的输出解析器来重构程序,生成结构化的数据
# 导入结构化输出解析器和
ResponseSchema from langchain.output_parsers import StructuredOutputParser, ResponseSchema
# 定义我们想要接收的响应模式
response_schemas = [ ResponseSchema(name="description", description="鲜花的描述文案"), ResponseSchema(name="reason", description="问什么要这样写这个文案") ]
# 创建输出解析器
output_parser = StructuredOutputParser.from_response_schemas(response_schemas) # 获取格式指示
format_instructions = output_parser.get_format_instructions() # 根据原始模板创建提示,同时在提示中加入输出解析器的说明
prompt = PromptTemplate.from_template(prompt_template, partial_variables={"format_instructions": format_instructions})
在加入partial_variables后,我们打印其prompt信息:
input_variables=['flower_name', 'price'] 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\n```json\n{\n\t"description": string // 鲜花的描述文案\n\t"reason": string // 问什么要这样写这个文案\n}\n```'} template='您是一位专业的鲜花店文案撰写员。\n对于售价为 {price} 元的 {flower_name} ,您能提供一个吸引人的简短描述吗?\n{format_instructions}'
发现其多了一段json代码,而这个代码正是我们想要的格式化数据 。
总结
在使用大语言模型时,我们能按照输入提示->模型调用->输出解析来得到我们想要的结果,在输出解析中我们呢加入了parser解析器来让获取的数据更加格式化。