使用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."
}