开始使用免费开始使用

聊天提示模板

鉴于聊天模型在许多 LLM 应用中的重要性,LangChain 提供了创建提示模板的功能,用于按不同聊天"角色"来组织消息。

ChatPromptTemplate 类已经为您导入,且一个 LLM 已经定义好。

本练习是课程的一部分

使用 LangChain 开发 LLM 应用

查看课程

练习说明

  • 使用 ChatPromptTemplate.from_messages() 将角色-消息对转换为聊天提示模板。
  • 为给定的消息分配合适的角色,构建对话模式。
  • 创建一个 LCEL 链,并使用提供的输入进行调用。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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)
编辑并运行代码