langgraph各种函数

MessagePlaceholder

MessagesPlaceholder 是 LangChain 库中用于处理聊天消息列表的一个占位符类。它允许用户在构建提示模板时动态地插入一组消息,特别适用于处理对话历史记录。下面将详细介绍 MessagesPlaceholder 的功能、用法及其各个组成部分。

1. 什么是 MessagesPlaceholder

MessagesPlaceholder 是一个提示模板,占位符用于传递一组已经存在的消息。它假设变量已经是消息的列表,并在提示模板中插入这些消息。这个类继承自 BaseMessagePromptTemplate,使其能够与 LangChain 的其他提示模板无缝集成。

2. 基本用法

直接使用 MessagesPlaceholder

from langchain_core.prompts import MessagesPlaceholder

# 创建一个名为 "history" 的占位符
prompt = MessagesPlaceholder("history")

# 尝试格式化消息,但由于没有提供 "history",会引发 KeyError
prompt.format_messages()

上述代码会因为缺少 history 变量而抛出 KeyError。如果希望在没有提供 history 时返回一个空列表,可以将 optional 参数设置为 True

prompt = MessagesPlaceholder("history", optional=True)
print(prompt.format_messages())  # 输出: []

当提供 history 时:

formatted_messages = prompt.format_messages(
    history=[
        ("system", "You are an AI assistant."),
        ("human", "Hello!"),
    ]
)
# 输出:
# [
#     SystemMessage(content="You are an AI assistant."),
#     HumanMessage(content="Hello!"),
# ]

构建包含聊天历史的提示

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

# 创建一个包含系统消息、历史消息占位符和人类问题的提示模板
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant."),
        MessagesPlaceholder("history"),
        ("human", "{question}")
    ]
)

# 调用提示模板,传入历史消息和当前问题
formatted_prompt = prompt.invoke(
   {
       "history": [("human", "what's 5 + 2"), ("ai", "5 + 2 is 7")],
       "question": "now multiply that by 4"
   }
)
# 输出:
# ChatPromptValue(messages=[
#     SystemMessage(content="You are a helpful assistant."),
#     HumanMessage(content="what's 5 + 2"),
#     AIMessage(content="5 + 2 is 7"),
#     HumanMessage(content="now multiply that by 4"),
# ])

在这个例子中,MessagesPlaceholderhistory 中的消息插入到提示模板中,使得聊天对话能够保留之前的交流内容。

3. 限制消息数量

有时候,可能希望限制插入到提示模板中的历史消息数量,以避免过长的对话记录导致的性能问题。MessagesPlaceholder 提供了 n_messages 参数来实现这一点:

from langchain_core.prompts import MessagesPlaceholder

# 仅插入最近的一条消息
prompt = MessagesPlaceholder("history", n_messages=1)

formatted_messages = prompt.format_messages(
    history=[
        ("system", "You are an AI assistant."),
        ("human", "Hello!"),
    ]
)
# 输出:
# [
#     HumanMessage(content="Hello!"),
# ]

在这个例子中,尽管 history 包含两条消息,但由于 n_messages=1,只有最新的一条人类消息被插入。

参数解释

  • n_messages(可选):指定要包含的最大消息数量。如果设置为 None,则包含所有消息。默认为 None
    • 类型:Optional[PositiveInt]
    • 约束:exclusiveMinimum = 0

4. 关键参数详解

variable_name(必需)

  • 描述:用于作为消息列表的变量名称。
  • 类型str
  • 示例:在前面的例子中,variable_name"history"

optional(可选)

  • 描述:如果设置为 True,在调用 format_messages 时可以不传入对应的变量,此时会返回一个空列表。如果设置为 False,则必须提供对应的变量,即使其值为空列表。
  • 类型bool
  • 默认值False

5. 主要方法

format_messages(**kwargs)

  • 描述:从关键字参数中格式化消息列表。
  • 参数
    • **kwargs:用于格式化的关键字参数。
  • 返回值List[BaseMessage],即格式化后的消息列表。
  • 异常
    • 如果变量不是消息列表,则会引发 ValueError

示例

formatted_messages = prompt.format_messages(
    history=[
        ("system", "You are an AI assistant."),
        ("human", "Hello!"),
    ]
)

aformat_messages(**kwargs)

  • 描述:异步版本的 format_messages,用于异步环境中格式化消息。
  • 参数
    • **kwargs:用于格式化的关键字参数。
  • 返回值List[BaseMessage],格式化后的消息列表。

pretty_print()

  • 描述:打印一个人类可读的表示。
  • 返回值None

pretty_repr(html: bool = False)

  • 描述:生成一个人类可读的表示。
  • 参数
    • html(可选):是否以 HTML 格式返回。默认为 False
  • 返回值str,人类可读的表示。

input_variables

  • 描述:获取该提示模板的输入变量列表。
  • 返回值List[str],输入变量名称的列表。

6. 约束与错误处理

  • 约束
    • n_messages 必须大于 0。
  • 错误处理
    • 如果传入的变量不是消息列表,将引发 ValueError
    • 如果 optional=False 且未提供对应变量,将引发 KeyError

7. 综合示例

结合以上内容,下面是一个综合示例,展示如何使用 MessagesPlaceholder 构建一个包含聊天历史的提示模板,并限制消息数量:

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

# 创建一个包含系统消息、限制为最近两条的历史消息占位符和人类问题的提示模板
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant."),
        MessagesPlaceholder("history", n_messages=2),
        ("human", "{question}")
    ]
)

# 调用提示模板,传入多条历史消息和当前问题
formatted_prompt = prompt.invoke(
   {
       "history": [
           ("human", "What's the weather today?"),
           ("ai", "It's sunny and warm."),
           ("human", "Great, thank you!"),
           ("ai", "You're welcome!")
       ],
       "question": "Can you recommend a good book to read?"
   }
)
# 输出:
# ChatPromptValue(messages=[
#     SystemMessage(content="You are a helpful assistant."),
#     HumanMessage(content="Great, thank you!"),
#     AIMessage(content="You're welcome!"),
#     HumanMessage(content="Can you recommend a good book to read?"),
# ])

在这个示例中,尽管 history 中有四条消息,但由于 n_messages=2,只有最后两条消息被插入到提示模板中。

8. 总结

MessagesPlaceholder 是一个强大的工具,能够帮助开发者在构建复杂的聊天提示模板时,灵活地插入和管理消息历史。通过配置不同的参数,如 n_messagesoptional,可以满足各种不同的需求,确保提示模板既灵活又高效。结合 LangChain 的其他提示模板功能,MessagesPlaceholder 能够极大地提升构建智能对话系统的效率和效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值