LLM及LangChain開發筆記(13)_輸出解析器(Output Parser)

 

原始輸入(customer_review)內容:

customer_review = """
這個吹風機非常棒。它有四個檔位:輕柔模式、輕微微風、大風城市和龍捲風。
它在兩天內送到,正好趕上我妻子的周年紀念禮物。我覺得我妻子非常喜歡它,
她感到無言以對。到目前為止,我是唯一在使用它,
我每隔一天上班前用它來為妻子吹頭髮。它的價格略高於其他吹風機,
但我認為為了額外的功能,這是值得的。
"""



預期的輸出 JSON:

{
  "禮物": true,
  "送貨天數": "2",
  "價格": [
    "它的價格略高於其他吹風機,",
    "但我認為為了額外的功能,這是值得的。"
  ]
}


"禮物"
由 我妻子的周年紀念禮物 判斷為 true

"送貨天數"
由 它在兩天內送到 中的「兩天」提取為 "2"

"價格"
將描述價格與價值的兩句話提取為一組列表

Step1.定義 JSON 輸出格式的 Schema(結構化回應欄位)
目的是讓大語言模型(如 GPT)依照明確規範輸出 JSON 格式的資訊。
常用於資訊擷取(Information Extraction)任務。

匯入必要模組:
  • ResponseSchema:定義每個欄位的名稱與描述。
  • StructuredOutputParser:根據這些 Schema 解析模型輸出。
  • ChatPromptTemplate:製作提示詞。

步驟1程式

from langchain.output_parsers import ResponseSchema
from langchain.output_parsers import StructuredOutputParser
from langchain.prompts.chat import ChatPromptTemplate

gift_schema = ResponseSchema(
    name="禮物",
    description="該物品是否作為禮物購買?\
如果是,請回答True;\
如果不是或者不知道,請回答False。"
)

delivery_days_schema = ResponseSchema(
    name="送貨天數",
    description="產品到達需要多少天?\
如果找不到這個信息,請輸出-1。"
)

price_value_schema = ResponseSchema(
    name="價格",
    description="提取任何關於價值或價格的句子,\
並將它們作為逗號分隔的 Python 列表輸出。"
)


Step2.創建解析器實例,獲取格式指令
讓 LLM 明確知道你希望它產出什麼格式的 JSON 結構。
並在 print(format_instructions) 時顯示這段提示文字,可直接嵌入 prompt。
用 StructuredOutputParser.from_response_schemas([...]) 建立解析器。

步驟2程式

# 將格式規範放到一個列表裡
response_schemas = [gift_schema,
                    delivery_days_schema,
                    price_value_schema]

# 構建一個StructuredOutputParser實例
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)

# 獲取將發送給LLM的格式指令
format_instructions = output_parser.get_format_instructions()

print(format_instructions)


Step3.創建提示模板物件實體,將文本和格式指令作為參數輸入,呼叫LLM Chat模組去打印結果

步驟3-1程式

customer_review = """
這個吹風機非常棒。它有四個檔位:輕柔模式、輕微微風、大風城市和龍捲風。
它在兩天內送到,正好趕上我妻子的周年紀念禮物。我覺得我妻子非常喜歡它,
她感到無言以對。到目前為止,我是唯一在使用它,
我每隔一天上班前用它來為妻子吹頭髮。它的價格略高於其他吹風機,
但我認為為了額外的功能,這是值得的。
"""

review_template_2 = """ 
對於以下文本,提取以下信息:

禮物:該物品是否作為禮物購買?
如果是,請回答true;如果不是或者不知道,請回答false。
布林值請使用 `true` 或 `false`(小寫)
送貨天數:產品到達需要多少天?
如果找不到這個信息,請輸出 -1。
送貨天數請使用阿拉伯數字,如 "2"
價格:提取任何關於價值或價格的句子, 
並將它們作為逗號分隔的Python列表輸出。
價格欄位請用 JSON 陣列輸出(["句子1", "句子2"])

不要使用 Python 格式(如 True/False),也不要加多餘自然語言描述
文本:{text}
{format_instructions}
"""

# 創建一個ChatPromptTemplate實例,用於模板的重用
prompt = ChatPromptTemplate.from_template(template=review_template_2)

# 將文本和格式指令作為輸入變量傳入
messages = prompt.format_messages(text=customer_review,
                                   format_instructions=format_instructions)
print(messages)


步驟3-2程式

#呼叫LLM解析文本並打印內容
import openai
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())  # read local .env file

openai.api_key = os.getenv('OPENAI_API_KEY')
from langchain.chat_models import ChatOpenAI
chat = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.0)
response = chat(messages)
print(response.content)


Step4.將結果解析為字典型態,並提取與送貨天數相關的值


步驟4程式

output_dict = output_parser.parse(response.content)
print(output_dict.get("送貨天數"))



留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題

Crystal Report報表開發(二)_基礎操作排版對齊_基本組成部分介紹