開始使用免費開始

聊天提示模板

由於聊天模型在許多 LLM 應用中相當關鍵,LangChain 提供了建立提示模板的功能,用來將不同聊天「角色」的訊息結構化。

ChatPromptTemplate 類別已為你匯入,LLM 也已經定義好了。

本練習屬於課程

使用 LangChain 開發 LLM 應用

檢視課程

練習說明

  • 使用 ChatPromptTemplate.from_messages() 將角色與訊息的配對轉換為聊天提示模板。
  • 為提供的訊息指派合適的角色,建立一個對話樣式。
  • 建立一個 LCEL chain,並用提供的輸入加以呼叫。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

llm = ChatOpenAI(model="gpt-4o-mini", api_key='')

# Create a chat prompt template
prompt_template = ChatPromptTemplate.____(
    [
        ("____", "You are a geography expert that returns the colors present in a country's flag."),
        ("____", "France"),
        ("____", "blue, white, red"),
        ("____", "{country}")
    ]
)

# Chain the prompt template and model, and invoke the chain
llm_chain = ____ | llm

country = "Japan"
response = llm_chain.invoke({"country": country})
print(response.content)
編輯並執行程式碼