一、概述
所有模型都有 有限的 上下文窗口,这意味着它们可以作为输入的 token 数量是有限的。如果你有很长的消息,或者一个 chain 或 agent 累积了很长的 历史消息,你需要管理你传递给模型的消息的长度。
trim_messages util 提供了一些基本策略,用于将消息列表修剪为特定的 token 长度。
二、获取最后的 max_tokens 令牌
为了获取消息列表中的最后一个 max_tokens,我们可以设置 strategy=“last”。请注意,对于我们的 token_counter,我们可以将其传入到一个函数 (下面将详细介绍) 或一个语言模型 (因为语言模型有一个消息令牌计数方法) 中。当调整消息以适应特定模型的上下文窗口时,将其传入到模型是有意义的:
# pip install -U langchain-openai
from langchain_core.messages import (
AIMessage,
HumanMessage,
SystemMessage,
trim_messages,
)
from langchain_openai import ChatOpenAI
messages = [
SystemMessage("you're a good assistant, you always respond with a joke."),
HumanMessage("i wonder why it's called langchain"),
AIMessage(
'Well, I guess they thought "WordRope" and "SentenceString" just didn\'t have the same ring to it!'
),
HumanMessage("and who is harrison chasing anyways"),
AIMessage(
"Hmmm let me think.\n\nWhy, he's probably chasing after the last cup of coffee in the office!"
),
HumanMessage("what do you call a speechless parrot"),
]
trim_messages(
messages,
max_tokens=45,
strategy="last",
token_counter=ChatOpenAI(model="gpt-4o"),
)
如果我们想始终保留初始系统消息,我们可以指定 include_system=True:
如果我们想允许拆分消息的内容,我们可以指定 allow_partial=True:
如果我们需要确保我们的第一条消息 (不包括 SystemMessage) 始终是特定类型的,我们可以指定 start_on:
trim_messages(
messages,
max_tokens=60,