消息
langchain.messages ¶
消息和消息内容类型。
包括不同角色的消息类型(例如,人类、AI、系统),以及消息内容块的类型(例如,文本、图像、音频)和工具调用。
参考文档
此页面包含消息的参考文档。有关使用消息的概念指南、教程和示例,请参阅文档。
| 类 | 描述 |
|---|---|
AIMessage |
来自 AI 的消息。 |
AIMessageChunk |
来自 AI 的消息块(在流式传输时产生)。 |
HumanMessage |
来自用户的消息。 |
SystemMessage |
用于引导 AI 行为的消息。 |
ToolMessage |
用于将执行工具的结果传回给模型的消息。 |
ToolCall |
表示 AI 调用工具的请求。 |
InvalidToolCall |
允许 LLM 产生的错误。 |
ToolCallChunk |
工具调用的一个块(在流式传输时产生)。 |
ServerToolCall |
在服务器端执行的工具调用。 |
ServerToolCallChunk |
服务器端工具调用的一个块(在流式传输时产生)。 |
ServerToolResult |
服务器端工具调用的结果。 |
TextContentBlock |
来自 LLM 的文本输出。 |
Citation |
用于引用文档中数据的注释。 |
NonStandardAnnotation |
特定于提供商的注释格式。 |
ReasoningContentBlock |
来自 LLM 的推理输出。 |
ImageContentBlock |
图像数据。 |
VideoContentBlock |
视频数据。 |
AudioContentBlock |
音频数据。 |
PlainTextContentBlock |
纯文本数据(例如,来自 |
FileContentBlock |
不适合其他多模态块类型的文件数据。 |
NonStandardContentBlock |
特定于提供商的内容数据。 |
UsageMetadata |
消息的使用元数据,如令牌计数。 |
InputTokenDetails |
输入令牌计数的细分。 |
OutputTokenDetails |
输出令牌计数的细分。 |
| 函数 | 描述 |
|---|---|
trim_messages |
修剪消息以使其低于令牌计数。 |
| 属性 | 描述 |
|---|---|
AnyMessage |
表示任何已定义的
|
MessageLikeRepresentation |
表示消息可以表示的各种方式的类型。
|
ContentBlock |
所有已定义的
|
Annotation |
所有已定义的
|
DataContentBlock |
所有已定义的多模态数据
|
AIMessage ¶
基类:BaseMessage
来自 AI 的消息。
AIMessage 是聊天模型对提示的响应返回的内容。
此消息代表模型的输出,由模型返回的原始输出和 LangChain 框架添加的标准化字段(例如,工具调用、使用元数据)组成。
| 方法 | 描述 |
|---|---|
__init__ |
初始化一个 |
pretty_repr |
返回消息的美观表示形式以供显示。 |
| 属性 | 描述 |
|---|---|
tool_calls |
如果存在,则为与消息关联的工具调用。 |
invalid_tool_calls |
如果存在,则为与消息关联的具有解析错误的工具调用。
类型: |
usage_metadata |
如果存在,则为消息的使用元数据,如令牌计数。
类型: |
type |
消息的类型(用于反序列化)。
类型: |
lc_attributes |
要序列化的属性。
类型: |
content_blocks |
从消息中返回标准的、带类型的
类型: |
invalid_tool_calls class-attribute instance-attribute ¶
invalid_tool_calls: list[InvalidToolCall] = []
如果存在,则为与消息关联的具有解析错误的工具调用。
usage_metadata class-attribute instance-attribute ¶
usage_metadata: UsageMetadata | None = None
如果存在,则为消息的使用元数据,如令牌计数。
这是一个跨模型一致的令牌使用情况的标准表示。
__init__ ¶
content_blocks property ¶
content_blocks: list[ContentBlock]
从消息中返回标准的、带类型的 ContentBlock 字典。
如果消息有已知的模型提供商,则首先使用特定于提供商的转换器,然后再回退到尽力而为的解析。有关详细信息,请参阅 BaseMessage 上的属性。
AIMessageChunk ¶
基类:AIMessage, BaseMessageChunk
来自 AI 的消息块(在流式传输时产生)。
| 方法 | 描述 |
|---|---|
init_tool_calls |
从工具调用块初始化工具调用。 |
init_server_tool_calls |
解析 |
__add__ |
消息块支持与其他消息块连接。 |
| 属性 | 描述 |
|---|---|
type |
消息的类型(用于反序列化)。
类型: |
tool_call_chunks |
如果提供,则为与消息关联的工具调用块。
类型: |
chunk_position |
由聚合的
类型: |
lc_attributes |
要序列化的属性,即使它们是从其他初始化参数派生的。
类型: |
content_blocks |
从消息中返回标准的、带类型的
类型: |
type class-attribute instance-attribute ¶
type: Literal['AIMessageChunk'] = 'AIMessageChunk'
消息的类型(用于反序列化)。
tool_call_chunks class-attribute instance-attribute ¶
tool_call_chunks: list[ToolCallChunk] = []
如果提供,则为与消息关联的工具调用块。
chunk_position class-attribute instance-attribute ¶
chunk_position: Literal['last'] | None = None
由聚合的 AIMessageChunk 表示的可选范围。
如果将具有 chunk_position="last" 的块聚合到流中,则消息内容中的 tool_call_chunks 将被解析为 tool_calls。
__add__ ¶
__add__(other: Any) -> BaseMessageChunk
消息块支持与其他消息块连接。
此功能对于将流式模型产生的消息块组合成完整的消息非常有用。
| 参数 | 描述 |
|---|---|
other
|
要与此消息块连接的另一个消息块。
类型: |
| 返回 | 描述 |
|---|---|
BaseMessageChunk
|
一个新消息块,是此消息块 |
BaseMessageChunk
|
和另一个消息块的连接。 |
| 引发 | 描述 |
|---|---|
TypeError
|
如果另一个对象不是消息块。 |
例如,
AIMessageChunk(content="Hello") + AIMessageChunk(content=" World")
将得到 AIMessageChunk(content="Hello World")
HumanMessage ¶
基类:BaseMessage
来自用户的消息。
HumanMessage 是从用户传递给模型的消息。
示例
| 方法 | 描述 |
|---|---|
__init__ |
指定 |
| 属性 | 描述 |
|---|---|
type |
消息的类型(用于序列化)。
类型: |
SystemMessage ¶
基类:BaseMessage
用于引导 AI 行为的消息。
系统消息通常作为输入消息序列的第一个传入。
示例
| 方法 | 描述 |
|---|---|
__init__ |
指定 |
| 属性 | 描述 |
|---|---|
type |
消息的类型(用于序列化)。
类型: |
AnyMessage module-attribute ¶
AnyMessage = Annotated[
Annotated[AIMessage, Tag(tag="ai")]
| Annotated[HumanMessage, Tag(tag="human")]
| Annotated[ChatMessage, Tag(tag="chat")]
| Annotated[SystemMessage, Tag(tag="system")]
| Annotated[FunctionMessage, Tag(tag="function")]
| Annotated[ToolMessage, Tag(tag="tool")]
| Annotated[AIMessageChunk, Tag(tag="AIMessageChunk")]
| Annotated[HumanMessageChunk, Tag(tag="HumanMessageChunk")]
| Annotated[ChatMessageChunk, Tag(tag="ChatMessageChunk")]
| Annotated[SystemMessageChunk, Tag(tag="SystemMessageChunk")]
| Annotated[FunctionMessageChunk, Tag(tag="FunctionMessageChunk")]
| Annotated[ToolMessageChunk, Tag(tag="ToolMessageChunk")],
Field(discriminator=Discriminator(_get_type)),
]
表示任何已定义的 Message 或 MessageChunk 类型的类型。
MessageLikeRepresentation module-attribute ¶
表示消息可以表示的各种方式的类型。
ToolMessage ¶
基类:BaseMessage, ToolOutputMixin
用于将执行工具的结果传回给模型的消息。
ToolMessage 对象包含工具调用的结果。通常,结果编码在 content 字段中。
示例:一个 ToolMessage,表示从 ID 为 `tool_call_id` 的工具调用中得到的结果 `42`。
from langchain_core.messages import ToolMessage
ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL")
示例:一个 ToolMessage,其中只有部分工具输出被发送到模型,而完整的输出则传递给工件。
from langchain_core.messages import ToolMessage
tool_output = {
"stdout": "From the graph we can see that the correlation between "
"x and y is ...",
"stderr": None,
"artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."},
}
ToolMessage(
content=tool_output["stdout"],
artifact=tool_output,
tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL",
)
tool_call_id 字段用于将工具调用请求与工具调用响应关联起来。这在聊天模型能够并行请求多个工具调用的情况下非常有用。
| 方法 | 描述 |
|---|---|
coerce_args |
将模型参数强制转换为正确的类型。 |
__init__ |
初始化一个 |
| 属性 | 描述 |
|---|---|
tool_call_id |
此消息响应的工具调用。
类型: |
type |
消息的类型(用于序列化)。
类型: |
artifact |
工具执行的工件,不应发送给模型。
类型: |
status |
工具调用的状态。
类型: |
additional_kwargs |
目前继承自
类型: |
response_metadata |
目前继承自
类型: |
artifact class-attribute instance-attribute ¶
artifact: Any = None
工具执行的工件,不应发送给模型。
仅当它与消息内容不同时才应指定,例如,如果只将完整工具输出的一部分作为消息内容传递,但在代码的其他部分需要完整输出。
status class-attribute instance-attribute ¶
status: Literal['success', 'error'] = 'success'
工具调用的状态。
additional_kwargs class-attribute instance-attribute ¶
目前继承自 BaseMessage,但未使用。
response_metadata class-attribute instance-attribute ¶
目前继承自 BaseMessage,但未使用。
ToolCall ¶
InvalidToolCall ¶
基类:TypedDict
允许 LLM 产生的错误。
在这里,我们添加一个 error 键来显示生成过程中出现的错误(例如,无效的 JSON 参数)。
| 属性 | 描述 |
|---|---|
type |
用于区分。
类型: |
id |
与工具调用关联的标识符。
类型: |
name |
要调用的工具的名称。
类型: |
args |
工具调用的参数。
类型: |
error |
与工具调用关联的错误消息。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
extras |
特定于提供商的元数据。
类型: |
ToolCallChunk ¶
基类:TypedDict
工具调用的一个块(在流式传输时产生)。
当合并 ToolCallChunk(例如,通过 AIMessageChunk.__add__)时,所有字符串属性都会被连接。只有当 index 的值相等且不为 None 时,块才会被合并。
示例
left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
right_chunks = [ToolCallChunk(name=None, args="1}", index=0)]
(
AIMessageChunk(content="", tool_call_chunks=left_chunks)
+ AIMessageChunk(content="", tool_call_chunks=right_chunks)
).tool_call_chunks == [ToolCallChunk(name="foo", args='{"a":1}', index=0)]
| 属性 | 描述 |
|---|---|
name |
要调用的工具的名称。
类型: |
args |
工具调用的参数。
类型: |
id |
与工具调用关联的标识符。
类型: |
index |
工具调用在序列中的索引。
类型: |
ServerToolCall ¶
ServerToolCallChunk ¶
基类:TypedDict
服务器端工具调用的一个块(在流式传输时产生)。
| 属性 | 描述 |
|---|---|
type |
用于区分。
类型: |
name |
要调用的工具的名称。
类型: |
args |
工具调用参数的 JSON 子字符串。
类型: |
id |
与工具调用关联的标识符。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
extras |
特定于提供商的元数据。
类型: |
ServerToolResult ¶
基类:TypedDict
服务器端工具调用的结果。
| 属性 | 描述 |
|---|---|
type |
用于区分。
类型: |
id |
与服务器工具结果关联的标识符。
类型: |
tool_call_id |
相应服务器工具调用的 ID。
类型: |
status |
服务器端工具的执行状态。
类型: |
output |
已执行工具的输出。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
extras |
特定于提供商的元数据。
类型: |
ContentBlock module-attribute ¶
ContentBlock = (
TextContentBlock
| InvalidToolCall
| ReasoningContentBlock
| NonStandardContentBlock
| DataContentBlock
| ToolContentBlock
)
所有已定义的 ContentBlock 类型和别名的联合。
TextContentBlock ¶
基类:TypedDict
来自 LLM 的文本输出。
这通常表示消息的主要文本内容,例如语言模型的响应或用户消息的文本。
工厂函数
create_text_block 也可用作创建 TextContentBlock 的工厂函数。优点包括:
- 自动生成 ID(如果未提供)
- 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
text |
块文本。
类型: |
annotations |
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
extras |
特定于提供商的元数据。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
Annotation module-attribute ¶
Annotation = Citation | NonStandardAnnotation
所有已定义的 Annotation 类型的联合。
Citation ¶
基类:TypedDict
用于引用文档中数据的注释。
注意
start/end 索引指的是响应文本,而不是源文本。这意味着索引是相对于模型的响应,而不是原始文档(如 url 中指定的)。
工厂函数
create_citation 也可用作创建 Citation 的工厂函数。优点包括:
- 自动生成 ID(如果未提供)
- 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
url |
文档来源的 URL。
类型: |
title |
源文档标题。
类型: |
start_index |
响应文本 (
类型: |
end_index |
响应文本 (
类型: |
cited_text |
被引用的源文本摘要。
类型: |
extras |
特定于提供商的元数据。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
NonStandardAnnotation ¶
ReasoningContentBlock ¶
基类:TypedDict
来自 LLM 的推理输出。
工厂函数
create_reasoning_block 也可用作创建 ReasoningContentBlock 的工厂函数。优点包括:
- 自动生成 ID(如果未提供)
- 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
reasoning |
推理文本。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
extras |
特定于提供商的元数据。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
reasoning instance-attribute ¶
reasoning: NotRequired[str]
推理文本。
可以是思考总结或原始推理文本本身。这通常是从模型的响应中的 <think> 标签解析出来的。
DataContentBlock module-attribute ¶
DataContentBlock = (
ImageContentBlock
| VideoContentBlock
| AudioContentBlock
| PlainTextContentBlock
| FileContentBlock
)
所有已定义的多模态数据 ContentBlock 类型的联合。
ImageContentBlock ¶
基类:TypedDict
图像数据。
工厂函数
create_image_block 也可用作创建 ImageContentBlock 的工厂函数。优点包括:
- 自动生成 ID(如果未提供)
- 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
file_id |
图片文件的 ID,例如,来自文件存储系统的 ID。
类型: |
mime_type |
图片的 MIME 类型。对于 base64 是必需的。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
url |
图片的 URL。
类型: |
base64 |
作为 base64 字符串的数据。
类型: |
extras |
提供商特定的元数据。这不应用于图片数据本身。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
VideoContentBlock ¶
基类:TypedDict
视频数据。
工厂函数
create_video_block 也可以用作工厂来创建 VideoContentBlock。好处包括
- 自动生成 ID(如果未提供)
- 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
file_id |
视频文件的 ID,例如,来自文件存储系统的 ID。
类型: |
mime_type |
视频的 MIME 类型。对于 base64 是必需的。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
url |
视频的 URL。
类型: |
base64 |
作为 base64 字符串的数据。
类型: |
extras |
提供商特定的元数据。这不应用于视频数据本身。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
AudioContentBlock ¶
基类:TypedDict
音频数据。
工厂函数
create_audio_block 也可以用作工厂来创建 AudioContentBlock。好处包括: * 自动生成 ID(如果未提供) * 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
file_id |
音频文件的 ID,例如,来自文件存储系统的 ID。
类型: |
mime_type |
音频的 MIME 类型。对于 base64 是必需的。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
url |
音频的 URL。
类型: |
base64 |
作为 base64 字符串的数据。
类型: |
extras |
提供商特定的元数据。这不应用于音频数据本身。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
PlainTextContentBlock ¶
基类:TypedDict
纯文本数据(例如,来自 .txt 或 .md 文档)。
注意
在 langchain-core<1.0.0 中存在一个 PlainTextContentBlock。虽然名称被保留了下来,但结构发生了显著变化。新旧版本之间共享的唯一键是 type 和 text,尽管 type 的值已从 'text' 更改为 'text-plain'。
注意
标题和上下文是可选字段,可以传递给模型。请参阅 Anthropic 示例。
工厂函数
create_plaintext_block 也可以用作工厂来创建 PlainTextContentBlock。好处包括
- 自动生成 ID(如果未提供)
- 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
file_id |
纯文本文件的 ID,例如,来自文件存储系统的 ID。
类型: |
mime_type |
文件的 MIME 类型。对于 base64 是必需的。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
url |
纯文本的 URL。
类型: |
base64 |
作为 base64 字符串的数据。
类型: |
text |
纯文本内容。如果数据以 base64 形式提供,则此项为可选。
类型: |
title |
文本数据的标题,例如,文档的标题。
类型: |
context |
文本的上下文,例如,对文本内容的描述或摘要。
类型: |
extras |
提供商特定的元数据。这不应用于数据本身。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
FileContentBlock ¶
基类:TypedDict
不适合其他多模态块类型的文件数据。
此块旨在用于非图片、音频或纯文本的文件。例如,它可用于 PDF、Word 文档等。
如果文件是图片、音频或纯文本,您应该使用相应的内容块类型(例如,ImageContentBlock、AudioContentBlock、PlainTextContentBlock)。
工厂函数
create_file_block 也可以用作工厂来创建 FileContentBlock。好处包括
- 自动生成 ID(如果未提供)
- 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
file_id |
文件的 ID,例如,来自文件存储系统的 ID。
类型: |
mime_type |
文件的 MIME 类型。对于 base64 是必需的。
类型: |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
url |
文件的 URL。
类型: |
base64 |
作为 base64 字符串的数据。
类型: |
extras |
提供商特定的元数据。这不应用于文件数据本身。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
NonStandardContentBlock ¶
基类:TypedDict
特定于提供商的内容数据。
此块包含尚无标准类型的数据。
此块的目的应该是简单地持有提供商特定的有效负载。如果提供商的非标准输出包括推理和工具调用,则适配器的工作应该是解析该有效负载并发出相应的标准 ReasoningContentBlock 和 ToolCalls。
没有 extras 字段,因为提供商特定的数据应包含在 value 字段中。
工厂函数
create_non_standard_block 也可以用作工厂来创建 NonStandardContentBlock。好处包括
- 自动生成 ID(如果未提供)
- 在创建时严格验证必需的参数
| 属性 | 描述 |
|---|---|
type |
内容块的类型。用于区分。
类型: |
id |
内容块标识符。
类型: |
value |
特定于提供商的内容数据。 |
index |
聚合响应中块的索引。在流式传输期间使用。
类型: |
id instance-attribute ¶
id: NotRequired[str]
内容块标识符。
可以是
- 由提供商生成(例如,OpenAI 的文件 ID)
- 由 LangChain 在创建时生成(以
'lc_'为前缀的UUID4))
trim_messages ¶
trim_messages(
messages: Iterable[MessageLikeRepresentation] | PromptValue,
*,
max_tokens: int,
token_counter: Callable[[list[BaseMessage]], int]
| Callable[[BaseMessage], int]
| BaseLanguageModel,
strategy: Literal["first", "last"] = "last",
allow_partial: bool = False,
end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
start_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
include_system: bool = False,
text_splitter: Callable[[str], list[str]] | TextSplitter | None = None,
) -> list[BaseMessage]
修剪消息以使其低于令牌计数。
trim_messages 可用于将聊天记录的大小减少到指定的令牌或消息数量。
在任何一种情况下,如果将修剪后的聊天记录直接传回给聊天模型,生成的聊天记录通常应满足以下属性
- 生成的聊天记录应该是有效的。大多数聊天模型期望聊天记录以 (1) 一个
HumanMessage或 (2) 一个SystemMessage后跟一个HumanMessage开始。为实现这一点,请设置start_on='human'。此外,通常ToolMessage只能出现在涉及工具调用的AIMessage之后。 - 它包含最近的消息并丢弃聊天记录中的旧消息。为实现这一点,请设置
strategy='last'。 - 通常,新的聊天记录应包含
SystemMessage(如果它存在于原始聊天记录中),因为SystemMessage包含给聊天模型的特殊指令。如果存在,SystemMessage几乎总是历史记录中的第一条消息。为实现这一点,请设置include_system=True。
注意
下面的示例展示了如何配置 trim_messages 以实现与上述属性一致的行为。
| 参数 | 描述 |
|---|---|
messages
|
要修剪的类消息对象序列。
类型: |
max_tokens
|
修剪后消息的最大令牌数。
类型: |
token_counter
|
用于计算 注意 使用
类型: |
strategy
|
修剪策略。 -
类型: |
allow_partial
|
如果只能包含消息的一部分,是否拆分消息。如果
类型: |
end_on
|
结束的消息类型。如果指定,则该类型最后一次出现之后的所有消息都将被忽略。如果
类型: |
start_on
|
开始的消息类型。仅当
类型: |
include_system
|
如果索引
类型: |
text_splitter
|
用于拆分消息字符串内容的函数或
类型: |
| 返回 | 描述 |
|---|---|
list[BaseMessage]
|
修剪后的 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果指定了两个不兼容的参数或指定了无法识别的 |
示例
根据令牌计数修剪聊天记录,如果存在 SystemMessage 则保留它,并确保聊天记录以 HumanMessage(或一个 SystemMessage 后跟一个 HumanMessage)开始。
from langchain_core.messages import (
AIMessage,
HumanMessage,
BaseMessage,
SystemMessage,
trim_messages,
)
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"),
# Most chat models expect that chat history starts with either:
# (1) a HumanMessage or
# (2) a SystemMessage followed by a HumanMessage
start_on="human",
# Usually, we want to keep the SystemMessage
# if it's present in the original history.
# The SystemMessage has special instructions for the model.
include_system=True,
allow_partial=False,
)
[
SystemMessage(
content="you're a good assistant, you always respond with a joke."
),
HumanMessage(content="what do you call a speechless parrot"),
]
根据消息计数修剪聊天记录,如果存在 SystemMessage 则保留它,并确保聊天记录以 HumanMessage(或一个 SystemMessage 后跟一个 HumanMessage)开始。
trim_messages(
messages,
# When `len` is passed in as the token counter function,
# max_tokens will count the number of messages in the chat history.
max_tokens=4,
strategy="last",
# Passing in `len` as a token counter function will
# count the number of messages in the chat history.
token_counter=len,
# Most chat models expect that chat history starts with either:
# (1) a HumanMessage or
# (2) a SystemMessage followed by a HumanMessage
start_on="human",
# Usually, we want to keep the SystemMessage
# if it's present in the original history.
# The SystemMessage has special instructions for the model.
include_system=True,
allow_partial=False,
)
[
SystemMessage(
content="you're a good assistant, you always respond with a joke."
),
HumanMessage(content="and who is harrison chasing anyways"),
AIMessage(
content="Hmmm let me think.\n\nWhy, he's probably chasing after "
"the last cup of coffee in the office!"
),
HumanMessage(content="what do you call a speechless parrot"),
]
messages = [
SystemMessage("This is a 4 token text. The full message is 10 tokens."),
HumanMessage(
"This is a 4 token text. The full message is 10 tokens.", id="first"
),
AIMessage(
[
{"type": "text", "text": "This is the FIRST 4 token block."},
{"type": "text", "text": "This is the SECOND 4 token block."},
],
id="second",
),
HumanMessage(
"This is a 4 token text. The full message is 10 tokens.", id="third"
),
AIMessage(
"This is a 4 token text. The full message is 10 tokens.",
id="fourth",
),
]
def dummy_token_counter(messages: list[BaseMessage]) -> int:
# treat each message like it adds 3 default tokens at the beginning
# of the message and at the end of the message. 3 + 4 + 3 = 10 tokens
# per message.
default_content_len = 4
default_msg_prefix_len = 3
default_msg_suffix_len = 3
count = 0
for msg in messages:
if isinstance(msg.content, str):
count += (
default_msg_prefix_len
+ default_content_len
+ default_msg_suffix_len
)
if isinstance(msg.content, list):
count += (
default_msg_prefix_len
+ len(msg.content) * default_content_len
+ default_msg_suffix_len
)
return count
前 30 个令牌,允许部分消息
UsageMetadata ¶
基类:TypedDict
消息的使用元数据,如令牌计数。
这是一个跨模型一致的令牌使用情况的标准表示。
示例
行为在 0.3.9 版本中发生变化
添加了 input_token_details 和 output_token_details。
LangSmith SDK
LangSmith SDK 也有一个 UsageMetadata 类。虽然两者共享字段,但 LangSmith 的 UsageMetadata 具有额外的字段来捕获 LangSmith 平台使用的成本信息。
| 属性 | 描述 |
|---|---|
input_tokens |
输入(或提示)令牌的数量。所有输入令牌类型的总和。
类型: |
output_tokens |
输出(或完成)令牌的数量。所有输出令牌类型的总和。
类型: |
total_tokens |
总令牌数。
类型: |
input_token_details |
输入令牌计数的细分。 |
output_token_details |
输出令牌计数的细分。 |
input_token_details instance-attribute ¶
input_token_details: NotRequired[InputTokenDetails]
输入令牌计数的细分。
不需要与总输入令牌数相加。不需要包含所有键。
output_token_details instance-attribute ¶
output_token_details: NotRequired[OutputTokenDetails]
输出令牌计数的细分。
不需要与总输出令牌数相加。不需要包含所有键。
InputTokenDetails ¶
基类:TypedDict
输入令牌计数的细分。
不需要与总输入令牌数相加。不需要包含所有键。
也可能包含提供商特定的额外键。
于 0.3.9 版本中添加
| 属性 | 描述 |
|---|---|
audio |
音频输入令牌。
类型: |
cache_creation |
被缓存且缓存未命中的输入令牌。
类型: |
cache_read |
被缓存且缓存命中的输入令牌。
类型: |