使用Langchain的输出解析器从CHATGPT提示响应中提取信息
这本jupyter笔记本演示了如何使用langchain的StructuredOutputParser从chatgpt提示响应中提取结构化信息。
导入诸如OpenAI , LangChain类的必要库,并定义了ChatOpenAI实例。
定义示例输出结构,该字段诸如"gift" , "delivery_days" , "price_value"之类的字段。
显示要解析的示例客户评论文本。
为每个输出字段构建ResponseSchema对象。
使用响应模式创建一个StructuredOutputParser PARSER。
定义一个提示模板,该模板包含解析器的格式说明。
提示ChatGpt以结构化格式分析评论文本和输出。
解析JSON的响应,将礼物,交货日和价格价值提取到字典中。
总而言之,笔记本电脑显示了如何使用Langchain的输出解析器从自由形式的CHATGPT响应中获取结构化数据,从而使及时的工程能够进行信息提取。
jupyter笔记本链接:langchain_output_parser_prompt_engineering.ipynb(实验是在Google Colab中进行的)
要将OpenAI的GPT-3.5-Turbo模型与Langchain一起使用,需要使用API键。可以从此处获得API键。
为了控制LLM生成的文本的随机性和创造力,我们在初始化ChatOpenAI实例时使用了温度= 0.0。温度是设置为0到1之间的数值值。温度为0表示该模型始终选择最可能生成的单词,而1温度为1表示模型更可能选择较少的单词,从而导致更具创造力和意外的输出。通常,最佳温度设置取决于手头的特定任务。对于需要准确性和事实的任务,例如回答问题或总结文本,通常首选较低的温度。对于需要创造力和独创性的任务,例如写诗或产生故事思想,更高的温度可能更合适。由于我们的任务是从chatgpt提示响应中提取结构化信息,因此我们将温度设置为0.0。
输出解析器:语言模型输出文本。但是很多时候,您想获得更多结构化信息,而不仅仅是文本。这是输出解析器帮助构建语言模型响应的地方。输出解析器必须实现两种主要方法:
对于我们的及时工程,我们分析客户评论以提取3个信息:
我们想解析的评论中输出的示例结构:
{
"gift" : true ,
"delivery_days" : 3 ,
"price_value" : " pretty affordable! "
}提示模板:
For the following text, extract the following information:
gift: Was the item purchased as a gift for someone else?
Answer True if yes, False if not or unknown.
delivery_days: How many days did it take for the product
to arrive? If this information is not found, output -1.
price_value: Extract any sentences about the value or price,
and output them as a comma separated Python list.
text: {text}
{format_instructions}
在这里,文本引用了客户审核和格式_ Instructions是一个字符串,其中包含有关如何格式化语言模型的说明。
然后可以轻松地将LLM响应送入输出解析器中,以在我们所需的JSON/词典格式中获取结构化数据。
例如,我们使用以下评论:
This leaf blower is pretty amazing. It has four settings:
candle blower, gentle breeze, windy city, and tornado.
It arrived in two days, just in time for my wife's
anniversary present.
I think my wife liked it so much she was speechless.
So far I've been the only one using it, and I've been
using it every other morning to clear the leaves on our lawn.
It's slightly more expensive than the other leaf blowers
out there, but I think it's worth it for the extra features.
输出解析器具有输出:
{
'gift': False,
'delivery_days': '2',
'price_value': "It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features."
}