跳转到内容

消息

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

纯文本数据(例如,来自 .txt.md 文档)。

FileContentBlock

不适合其他多模态块类型的文件数据。

NonStandardContentBlock

特定于提供商的内容数据。

UsageMetadata

消息的使用元数据,如令牌计数。

InputTokenDetails

输入令牌计数的细分。

OutputTokenDetails

输出令牌计数的细分。

函数 描述
trim_messages

修剪消息以使其低于令牌计数。

属性 描述
AnyMessage

表示任何已定义的 MessageMessageChunk 类型的类型。

MessageLikeRepresentation

表示消息可以表示的各种方式的类型。

ContentBlock

所有已定义的 ContentBlock 类型和别名的联合。

Annotation

所有已定义的 Annotation 类型的联合。

DataContentBlock

所有已定义的多模态数据 ContentBlock 类型的联合。

AIMessage

基类:BaseMessage

来自 AI 的消息。

AIMessage 是聊天模型对提示的响应返回的内容。

此消息代表模型的输出,由模型返回的原始输出和 LangChain 框架添加的标准化字段(例如,工具调用、使用元数据)组成。

方法 描述
__init__

初始化一个 AIMessage

pretty_repr

返回消息的美观表示形式以供显示。

属性 描述
tool_calls

如果存在,则为与消息关联的工具调用。

类型: list[ToolCall]

invalid_tool_calls

如果存在,则为与消息关联的具有解析错误的工具调用。

类型: list[InvalidToolCall]

usage_metadata

如果存在,则为消息的使用元数据,如令牌计数。

类型: UsageMetadata | None

type

消息的类型(用于反序列化)。

类型: Literal['ai']

lc_attributes

要序列化的属性。

类型: dict

content_blocks

从消息中返回标准的、带类型的 ContentBlock 字典。

类型: list[ContentBlock]

tool_calls class-attribute instance-attribute

tool_calls: list[ToolCall] = []

如果存在,则为与消息关联的工具调用。

invalid_tool_calls class-attribute instance-attribute

invalid_tool_calls: list[InvalidToolCall] = []

如果存在,则为与消息关联的具有解析错误的工具调用。

usage_metadata class-attribute instance-attribute

usage_metadata: UsageMetadata | None = None

如果存在,则为消息的使用元数据,如令牌计数。

这是一个跨模型一致的令牌使用情况的标准表示。

type class-attribute instance-attribute

type: Literal['ai'] = 'ai'

消息的类型(用于反序列化)。

__init__

__init__(
    content: str | list[str | dict] | None = None,
    content_blocks: list[ContentBlock] | None = None,
    **kwargs: Any,
) -> None

初始化一个 AIMessage

指定 content 作为位置参数,或指定 content_blocks 以进行类型化。

参数 描述
content

消息的内容。

类型: str | list[str | dict] | None 默认值: None

content_blocks

类型化的标准内容。

类型: list[ContentBlock] | None 默认值: None

**kwargs

要传递给父类的其他参数。

类型: Any 默认值: {}

lc_attributes property

lc_attributes: dict

要序列化的属性。

包括所有属性,即使它们是从其他初始化参数派生的。

content_blocks property

content_blocks: list[ContentBlock]

从消息中返回标准的、带类型的 ContentBlock 字典。

如果消息有已知的模型提供商,则首先使用特定于提供商的转换器,然后再回退到尽力而为的解析。有关详细信息,请参阅 BaseMessage 上的属性。

pretty_repr

pretty_repr(html: bool = False) -> str

返回消息的美观表示形式以供显示。

参数 描述
html

是否返回 HTML 格式的字符串。

类型: bool 默认值: False

返回 描述
str

消息的美观表示形式。

AIMessageChunk

基类:AIMessage, BaseMessageChunk

来自 AI 的消息块(在流式传输时产生)。

方法 描述
init_tool_calls

从工具调用块初始化工具调用。

init_server_tool_calls

解析 server_tool_call_chunks

__add__

消息块支持与其他消息块连接。

属性 描述
type

消息的类型(用于反序列化)。

类型: Literal['AIMessageChunk']

tool_call_chunks

如果提供,则为与消息关联的工具调用块。

类型: list[ToolCallChunk]

chunk_position

由聚合的 AIMessageChunk 表示的可选范围。

类型: Literal['last'] | None

lc_attributes

要序列化的属性,即使它们是从其他初始化参数派生的。

类型: dict

content_blocks

从消息中返回标准的、带类型的 ContentBlock 字典。

类型: list[ContentBlock]

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

lc_attributes property

lc_attributes: dict

要序列化的属性,即使它们是从其他初始化参数派生的。

content_blocks property

content_blocks: list[ContentBlock]

从消息中返回标准的、带类型的 ContentBlock 字典。

init_tool_calls

init_tool_calls() -> Self

从工具调用块初始化工具调用。

返回 描述
Self

已初始化工具调用的值。

引发 描述
ValueError

如果工具调用块格式不正确。

init_server_tool_calls

init_server_tool_calls() -> Self

解析 server_tool_call_chunks

__add__

__add__(other: Any) -> BaseMessageChunk

消息块支持与其他消息块连接。

此功能对于将流式模型产生的消息块组合成完整的消息非常有用。

参数 描述
other

要与此消息块连接的另一个消息块。

类型: Any

返回 描述
BaseMessageChunk

一个新消息块,是此消息块

BaseMessageChunk

和另一个消息块的连接。

引发 描述
TypeError

如果另一个对象不是消息块。

例如,

AIMessageChunk(content="Hello") + AIMessageChunk(content=" World")

将得到 AIMessageChunk(content="Hello World")

HumanMessage

基类:BaseMessage

来自用户的消息。

HumanMessage 是从用户传递给模型的消息。

示例
from langchain_core.messages import HumanMessage, SystemMessage

messages = [
    SystemMessage(content="You are a helpful assistant! Your name is Bob."),
    HumanMessage(content="What is your name?"),
]

# Instantiate a chat model and invoke it with the messages
model = ...
print(model.invoke(messages))
方法 描述
__init__

指定 content 作为位置参数,或指定 content_blocks 以进行类型化。

属性 描述
type

消息的类型(用于序列化)。

类型: Literal['human']

type class-attribute instance-attribute

type: Literal['human'] = 'human'

消息的类型(用于序列化)。

__init__

__init__(
    content: str | list[str | dict] | None = None,
    content_blocks: list[ContentBlock] | None = None,
    **kwargs: Any,
) -> None

指定 content 作为位置参数,或指定 content_blocks 以进行类型化。

SystemMessage

基类:BaseMessage

用于引导 AI 行为的消息。

系统消息通常作为输入消息序列的第一个传入。

示例
from langchain_core.messages import HumanMessage, SystemMessage

messages = [
    SystemMessage(content="You are a helpful assistant! Your name is Bob."),
    HumanMessage(content="What is your name?"),
]

# Define a chat model and invoke it with the messages
print(model.invoke(messages))
方法 描述
__init__

指定 content 作为位置参数,或指定 content_blocks 以进行类型化。

属性 描述
type

消息的类型(用于序列化)。

类型: Literal['system']

type class-attribute instance-attribute

type: Literal['system'] = 'system'

消息的类型(用于序列化)。

__init__

__init__(
    content: str | list[str | dict] | None = None,
    content_blocks: list[ContentBlock] | None = None,
    **kwargs: Any,
) -> None

指定 content 作为位置参数,或指定 content_blocks 以进行类型化。

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)),
]

表示任何已定义的 MessageMessageChunk 类型的类型。

MessageLikeRepresentation module-attribute

MessageLikeRepresentation = (
    BaseMessage | list[str] | tuple[str, str] | str | dict[str, Any]
)

表示消息可以表示的各种方式的类型。

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__

初始化一个 ToolMessage

属性 描述
tool_call_id

此消息响应的工具调用。

类型: str

type

消息的类型(用于序列化)。

类型: Literal['tool']

artifact

工具执行的工件,不应发送给模型。

类型: Any

status

工具调用的状态。

类型: Literal['success', 'error']

additional_kwargs

目前继承自 BaseMessage,但未使用。

类型: dict

response_metadata

目前继承自 BaseMessage,但未使用。

类型: dict

tool_call_id instance-attribute

tool_call_id: str

此消息响应的工具调用。

type class-attribute instance-attribute

type: Literal['tool'] = 'tool'

消息的类型(用于序列化)。

artifact class-attribute instance-attribute

artifact: Any = None

工具执行的工件,不应发送给模型。

仅当它与消息内容不同时才应指定,例如,如果只将完整工具输出的一部分作为消息内容传递,但在代码的其他部分需要完整输出。

status class-attribute instance-attribute

status: Literal['success', 'error'] = 'success'

工具调用的状态。

additional_kwargs class-attribute instance-attribute

additional_kwargs: dict = Field(default_factory=dict, repr=False)

目前继承自 BaseMessage,但未使用。

response_metadata class-attribute instance-attribute

response_metadata: dict = Field(default_factory=dict, repr=False)

目前继承自 BaseMessage,但未使用。

coerce_args classmethod

coerce_args(values: dict) -> dict

将模型参数强制转换为正确的类型。

参数 描述
values

模型参数。

类型: dict

__init__

__init__(
    content: str | list[str | dict] | None = None,
    content_blocks: list[ContentBlock] | None = None,
    **kwargs: Any,
) -> None

初始化一个 ToolMessage

指定 content 作为位置参数,或指定 content_blocks 以进行类型化。

参数 描述
content

消息的内容。

类型: str | list[str | dict] | None 默认值: None

content_blocks

类型化的标准内容。

类型: list[ContentBlock] | None 默认值: None

**kwargs

附加字段。

类型: Any 默认值: {}

ToolCall

基类:TypedDict

表示 AI 调用工具的请求。

示例
{"name": "foo", "args": {"a": 1}, "id": "123"}

这表示一个调用名为 'foo' 的工具的请求,其参数为 {"a": 1},标识符为 '123'

属性 描述
name

要调用的工具的名称。

类型: str

args

工具调用的参数。

类型: dict[str, Any]

id

与工具调用关联的标识符。

类型: str | None

name instance-attribute

name: str

要调用的工具的名称。

args instance-attribute

args: dict[str, Any]

工具调用的参数。

id instance-attribute

id: str | None

与工具调用关联的标识符。

在进行多个并发工具调用时,需要一个标识符来将工具调用请求与工具调用结果关联起来。

InvalidToolCall

基类:TypedDict

允许 LLM 产生的错误。

在这里,我们添加一个 error 键来显示生成过程中出现的错误(例如,无效的 JSON 参数)。

属性 描述
type

用于区分。

类型: Literal['invalid_tool_call']

id

与工具调用关联的标识符。

类型: str | None

name

要调用的工具的名称。

类型: str | None

args

工具调用的参数。

类型: str | None

error

与工具调用关联的错误消息。

类型: str | None

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

extras

特定于提供商的元数据。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['invalid_tool_call']

用于区分。

id instance-attribute

id: str | None

与工具调用关联的标识符。

在进行多个并发工具调用时,需要一个标识符来将工具调用请求与工具调用结果关联起来。

name instance-attribute

name: str | None

要调用的工具的名称。

args instance-attribute

args: str | None

工具调用的参数。

error instance-attribute

error: str | None

与工具调用关联的错误消息。

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

特定于提供商的元数据。

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

要调用的工具的名称。

类型: str | None

args

工具调用的参数。

类型: str | None

id

与工具调用关联的标识符。

类型: str | None

index

工具调用在序列中的索引。

类型: int | None

name instance-attribute

name: str | None

要调用的工具的名称。

args instance-attribute

args: str | None

工具调用的参数。

id instance-attribute

id: str | None

与工具调用关联的标识符。

index instance-attribute

index: int | None

工具调用在序列中的索引。

ServerToolCall

基类:TypedDict

在服务器端执行的工具调用。

例如:代码执行、网页搜索等。

属性 描述
type

用于区分。

类型: Literal['server_tool_call']

id

与工具调用关联的标识符。

类型: str

name

要调用的工具的名称。

类型: str

args

工具调用的参数。

类型: dict[str, Any]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

extras

特定于提供商的元数据。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['server_tool_call']

用于区分。

id instance-attribute

id: str

与工具调用关联的标识符。

name instance-attribute

name: str

要调用的工具的名称。

args instance-attribute

args: dict[str, Any]

工具调用的参数。

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

特定于提供商的元数据。

ServerToolCallChunk

基类:TypedDict

服务器端工具调用的一个块(在流式传输时产生)。

属性 描述
type

用于区分。

类型: Literal['server_tool_call_chunk']

name

要调用的工具的名称。

类型: NotRequired[str]

args

工具调用参数的 JSON 子字符串。

类型: NotRequired[str]

id

与工具调用关联的标识符。

类型: NotRequired[str]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

extras

特定于提供商的元数据。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['server_tool_call_chunk']

用于区分。

name instance-attribute

要调用的工具的名称。

args instance-attribute

工具调用参数的 JSON 子字符串。

id instance-attribute

与工具调用关联的标识符。

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

特定于提供商的元数据。

ServerToolResult

基类:TypedDict

服务器端工具调用的结果。

属性 描述
type

用于区分。

类型: Literal['server_tool_result']

id

与服务器工具结果关联的标识符。

类型: NotRequired[str]

tool_call_id

相应服务器工具调用的 ID。

类型: str

status

服务器端工具的执行状态。

类型: Literal['success', 'error']

output

已执行工具的输出。

类型: NotRequired[Any]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

extras

特定于提供商的元数据。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['server_tool_result']

用于区分。

id instance-attribute

与服务器工具结果关联的标识符。

tool_call_id instance-attribute

tool_call_id: str

相应服务器工具调用的 ID。

status instance-attribute

status: Literal['success', 'error']

服务器端工具的执行状态。

output instance-attribute

output: NotRequired[Any]

已执行工具的输出。

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

特定于提供商的元数据。

ContentBlock module-attribute

所有已定义的 ContentBlock 类型和别名的联合。

TextContentBlock

基类:TypedDict

来自 LLM 的文本输出。

这通常表示消息的主要文本内容,例如语言模型的响应或用户消息的文本。

工厂函数

create_text_block 也可用作创建 TextContentBlock 的工厂函数。优点包括:

  • 自动生成 ID(如果未提供)
  • 在创建时严格验证必需的参数
属性 描述
type

内容块的类型。用于区分。

类型: Literal['text']

id

内容块标识符。

类型: NotRequired[str]

text

块文本。

类型: str

annotations

Citation 和其他注释。

类型: NotRequired[list[Annotation]]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

extras

特定于提供商的元数据。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['text']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

text instance-attribute

text: str

块文本。

annotations instance-attribute

annotations: NotRequired[list[Annotation]]

Citation 和其他注释。

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

特定于提供商的元数据。

Annotation module-attribute

所有已定义的 Annotation 类型的联合。

Citation

基类:TypedDict

用于引用文档中数据的注释。

注意

start/end 索引指的是响应文本,而不是源文本。这意味着索引是相对于模型的响应,而不是原始文档(如 url 中指定的)。

工厂函数

create_citation 也可用作创建 Citation 的工厂函数。优点包括:

  • 自动生成 ID(如果未提供)
  • 在创建时严格验证必需的参数
属性 描述
type

内容块的类型。用于区分。

类型: Literal['citation']

id

内容块标识符。

类型: NotRequired[str]

url

文档来源的 URL。

类型: NotRequired[str]

title

源文档标题。

类型: NotRequired[str]

start_index

响应文本 (TextContentBlock.text) 的起始索引。

类型: NotRequired[int]

end_index

响应文本 (TextContentBlock.text) 的结束索引

类型: NotRequired[int]

cited_text

被引用的源文本摘要。

类型: NotRequired[str]

extras

特定于提供商的元数据。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['citation']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

url instance-attribute

文档来源的 URL。

title instance-attribute

title: NotRequired[str]

源文档标题。

例如,网页的页面标题或论文的标题。

start_index instance-attribute

start_index: NotRequired[int]

响应文本 (TextContentBlock.text) 的起始索引。

end_index instance-attribute

end_index: NotRequired[int]

响应文本 (TextContentBlock.text) 的结束索引

cited_text instance-attribute

cited_text: NotRequired[str]

被引用的源文本摘要。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

特定于提供商的元数据。

NonStandardAnnotation

基类:TypedDict

特定于提供商的注释格式。

属性 描述
type

内容块的类型。用于区分。

类型: Literal['non_standard_annotation']

id

内容块标识符。

类型: NotRequired[str]

value

特定于提供商的注释数据。

类型: dict[str, Any]

type instance-attribute

type: Literal['non_standard_annotation']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

value instance-attribute

value: dict[str, Any]

特定于提供商的注释数据。

ReasoningContentBlock

基类:TypedDict

来自 LLM 的推理输出。

工厂函数

create_reasoning_block 也可用作创建 ReasoningContentBlock 的工厂函数。优点包括:

  • 自动生成 ID(如果未提供)
  • 在创建时严格验证必需的参数
属性 描述
type

内容块的类型。用于区分。

类型: Literal['reasoning']

id

内容块标识符。

类型: NotRequired[str]

reasoning

推理文本。

类型: NotRequired[str]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

extras

特定于提供商的元数据。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['reasoning']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

reasoning instance-attribute

reasoning: NotRequired[str]

推理文本。

可以是思考总结或原始推理文本本身。这通常是从模型的响应中的 <think> 标签解析出来的。

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

特定于提供商的元数据。

DataContentBlock module-attribute

所有已定义的多模态数据 ContentBlock 类型的联合。

ImageContentBlock

基类:TypedDict

图像数据。

工厂函数

create_image_block 也可用作创建 ImageContentBlock 的工厂函数。优点包括:

  • 自动生成 ID(如果未提供)
  • 在创建时严格验证必需的参数
属性 描述
type

内容块的类型。用于区分。

类型: Literal['image']

id

内容块标识符。

类型: NotRequired[str]

file_id

图片文件的 ID,例如,来自文件存储系统的 ID。

类型: NotRequired[str]

mime_type

图片的 MIME 类型。对于 base64 是必需的。

类型: NotRequired[str]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

url

图片的 URL。

类型: NotRequired[str]

base64

作为 base64 字符串的数据。

类型: NotRequired[str]

extras

提供商特定的元数据。这不应用于图片数据本身。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['image']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

file_id instance-attribute

file_id: NotRequired[str]

图片文件的 ID,例如,来自文件存储系统的 ID。

mime_type instance-attribute

mime_type: NotRequired[str]

图片的 MIME 类型。对于 base64 是必需的。

来自 IANA 的示例

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

url instance-attribute

图片的 URL。

base64 instance-attribute

base64: NotRequired[str]

作为 base64 字符串的数据。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

提供商特定的元数据。这不应用于图片数据本身。

VideoContentBlock

基类:TypedDict

视频数据。

工厂函数

create_video_block 也可以用作工厂来创建 VideoContentBlock。好处包括

  • 自动生成 ID(如果未提供)
  • 在创建时严格验证必需的参数
属性 描述
type

内容块的类型。用于区分。

类型: Literal['video']

id

内容块标识符。

类型: NotRequired[str]

file_id

视频文件的 ID,例如,来自文件存储系统的 ID。

类型: NotRequired[str]

mime_type

视频的 MIME 类型。对于 base64 是必需的。

类型: NotRequired[str]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

url

视频的 URL。

类型: NotRequired[str]

base64

作为 base64 字符串的数据。

类型: NotRequired[str]

extras

提供商特定的元数据。这不应用于视频数据本身。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['video']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

file_id instance-attribute

file_id: NotRequired[str]

视频文件的 ID,例如,来自文件存储系统的 ID。

mime_type instance-attribute

mime_type: NotRequired[str]

视频的 MIME 类型。对于 base64 是必需的。

来自 IANA 的示例

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

url instance-attribute

视频的 URL。

base64 instance-attribute

base64: NotRequired[str]

作为 base64 字符串的数据。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

提供商特定的元数据。这不应用于视频数据本身。

AudioContentBlock

基类:TypedDict

音频数据。

工厂函数

create_audio_block 也可以用作工厂来创建 AudioContentBlock。好处包括: * 自动生成 ID(如果未提供) * 在创建时严格验证必需的参数

属性 描述
type

内容块的类型。用于区分。

类型: Literal['audio']

id

内容块标识符。

类型: NotRequired[str]

file_id

音频文件的 ID,例如,来自文件存储系统的 ID。

类型: NotRequired[str]

mime_type

音频的 MIME 类型。对于 base64 是必需的。

类型: NotRequired[str]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

url

音频的 URL。

类型: NotRequired[str]

base64

作为 base64 字符串的数据。

类型: NotRequired[str]

extras

提供商特定的元数据。这不应用于音频数据本身。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['audio']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

file_id instance-attribute

file_id: NotRequired[str]

音频文件的 ID,例如,来自文件存储系统的 ID。

mime_type instance-attribute

mime_type: NotRequired[str]

音频的 MIME 类型。对于 base64 是必需的。

来自 IANA 的示例

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

url instance-attribute

音频的 URL。

base64 instance-attribute

base64: NotRequired[str]

作为 base64 字符串的数据。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

提供商特定的元数据。这不应用于音频数据本身。

PlainTextContentBlock

基类:TypedDict

纯文本数据(例如,来自 .txt.md 文档)。

注意

langchain-core<1.0.0 中存在一个 PlainTextContentBlock。虽然名称被保留了下来,但结构发生了显著变化。新旧版本之间共享的唯一键是 typetext,尽管 type 的值已从 'text' 更改为 'text-plain'

注意

标题和上下文是可选字段,可以传递给模型。请参阅 Anthropic 示例

工厂函数

create_plaintext_block 也可以用作工厂来创建 PlainTextContentBlock。好处包括

  • 自动生成 ID(如果未提供)
  • 在创建时严格验证必需的参数
属性 描述
type

内容块的类型。用于区分。

类型: Literal['text-plain']

id

内容块标识符。

类型: NotRequired[str]

file_id

纯文本文件的 ID,例如,来自文件存储系统的 ID。

类型: NotRequired[str]

mime_type

文件的 MIME 类型。对于 base64 是必需的。

类型: Literal['text/plain']

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

url

纯文本的 URL。

类型: NotRequired[str]

base64

作为 base64 字符串的数据。

类型: NotRequired[str]

text

纯文本内容。如果数据以 base64 形式提供,则此项为可选。

类型: NotRequired[str]

title

文本数据的标题,例如,文档的标题。

类型: NotRequired[str]

context

文本的上下文,例如,对文本内容的描述或摘要。

类型: NotRequired[str]

extras

提供商特定的元数据。这不应用于数据本身。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['text-plain']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

file_id instance-attribute

file_id: NotRequired[str]

纯文本文件的 ID,例如,来自文件存储系统的 ID。

mime_type instance-attribute

mime_type: Literal['text/plain']

文件的 MIME 类型。对于 base64 是必需的。

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

url instance-attribute

纯文本的 URL。

base64 instance-attribute

base64: NotRequired[str]

作为 base64 字符串的数据。

text instance-attribute

纯文本内容。如果数据以 base64 形式提供,则此项为可选。

title instance-attribute

title: NotRequired[str]

文本数据的标题,例如,文档的标题。

context instance-attribute

context: NotRequired[str]

文本的上下文,例如,对文本内容的描述或摘要。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

提供商特定的元数据。这不应用于数据本身。

FileContentBlock

基类:TypedDict

不适合其他多模态块类型的文件数据。

此块旨在用于非图片、音频或纯文本的文件。例如,它可用于 PDF、Word 文档等。

如果文件是图片、音频或纯文本,您应该使用相应的内容块类型(例如,ImageContentBlockAudioContentBlockPlainTextContentBlock)。

工厂函数

create_file_block 也可以用作工厂来创建 FileContentBlock。好处包括

  • 自动生成 ID(如果未提供)
  • 在创建时严格验证必需的参数
属性 描述
type

内容块的类型。用于区分。

类型: Literal['file']

id

内容块标识符。

类型: NotRequired[str]

file_id

文件的 ID,例如,来自文件存储系统的 ID。

类型: NotRequired[str]

mime_type

文件的 MIME 类型。对于 base64 是必需的。

类型: NotRequired[str]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

url

文件的 URL。

类型: NotRequired[str]

base64

作为 base64 字符串的数据。

类型: NotRequired[str]

extras

提供商特定的元数据。这不应用于文件数据本身。

类型: NotRequired[dict[str, Any]]

type instance-attribute

type: Literal['file']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

file_id instance-attribute

file_id: NotRequired[str]

文件的 ID,例如,来自文件存储系统的 ID。

mime_type instance-attribute

mime_type: NotRequired[str]

文件的 MIME 类型。对于 base64 是必需的。

来自 IANA 的示例

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

url instance-attribute

文件的 URL。

base64 instance-attribute

base64: NotRequired[str]

作为 base64 字符串的数据。

extras instance-attribute

extras: NotRequired[dict[str, Any]]

提供商特定的元数据。这不应用于文件数据本身。

NonStandardContentBlock

基类:TypedDict

特定于提供商的内容数据。

此块包含尚无标准类型的数据。

此块的目的应该是简单地持有提供商特定的有效负载。如果提供商的非标准输出包括推理和工具调用,则适配器的工作应该是解析该有效负载并发出相应的标准 ReasoningContentBlockToolCalls

没有 extras 字段,因为提供商特定的数据应包含在 value 字段中。

工厂函数

create_non_standard_block 也可以用作工厂来创建 NonStandardContentBlock。好处包括

  • 自动生成 ID(如果未提供)
  • 在创建时严格验证必需的参数
属性 描述
type

内容块的类型。用于区分。

类型: Literal['non_standard']

id

内容块标识符。

类型: NotRequired[str]

value

特定于提供商的内容数据。

类型: dict[str, Any]

index

聚合响应中块的索引。在流式传输期间使用。

类型: NotRequired[int | str]

type instance-attribute

type: Literal['non_standard']

内容块的类型。用于区分。

id instance-attribute

内容块标识符。

可以是

  • 由提供商生成(例如,OpenAI 的文件 ID)
  • 由 LangChain 在创建时生成(以 'lc_' 为前缀的 UUID4))

value instance-attribute

value: dict[str, Any]

特定于提供商的内容数据。

index instance-attribute

index: NotRequired[int | str]

聚合响应中块的索引。在流式传输期间使用。

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. 生成的聊天记录应该是有效的。大多数聊天模型期望聊天记录以 (1) 一个 HumanMessage 或 (2) 一个 SystemMessage 后跟一个 HumanMessage 开始。为实现这一点,请设置 start_on='human'。此外,通常 ToolMessage 只能出现在涉及工具调用的 AIMessage 之后。
  2. 它包含最近的消息并丢弃聊天记录中的旧消息。为实现这一点,请设置 strategy='last'
  3. 通常,新的聊天记录应包含 SystemMessage(如果它存在于原始聊天记录中),因为 SystemMessage 包含给聊天模型的特殊指令。如果存在,SystemMessage 几乎总是历史记录中的第一条消息。为实现这一点,请设置 include_system=True

注意

下面的示例展示了如何配置 trim_messages 以实现与上述属性一致的行为。

参数 描述
messages

要修剪的类消息对象序列。

类型: Iterable[MessageLikeRepresentation] | PromptValue

max_tokens

修剪后消息的最大令牌数。

类型: int

token_counter

用于计算 BaseMessageBaseMessage 列表中令牌数的函数或 llm。如果传入一个 BaseLanguageModel,则将使用 BaseLanguageModel.get_num_tokens_from_messages()。设置为 len 以计算聊天记录中的消息数量。

注意

使用 count_tokens_approximately 获取快速、近似的令牌计数。建议在热路径上使用 trim_messages,此时不需要精确的令牌计数。

类型: Callable[[list[BaseMessage]], int] | Callable[[BaseMessage], int] | BaseLanguageModel

strategy

修剪策略。 - 'first': 保留消息的前 <= n_count 个令牌。 - 'last': 保留消息的后 <= n_count 个令牌。

类型: Literal['first', 'last'] 默认值: 'last'

allow_partial

如果只能包含消息的一部分,是否拆分消息。如果 strategy='last',则包含消息的最后部分内容。如果 strategy='first',则包含消息的第一部分内容。

类型: bool 默认值: False

end_on

结束的消息类型。如果指定,则该类型最后一次出现之后的所有消息都将被忽略。如果 strategy='last',则在尝试获取最后 max_tokens 个令牌之前完成此操作。如果 strategy='first',则在获取前 max_tokens 个令牌之后完成此操作。可以指定为字符串名称(例如 'system''human''ai' 等)或 BaseMessage 类(例如 SystemMessageHumanMessageAIMessage 等)。可以是一种类型或类型列表。

类型: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None 默认值: None

start_on

开始的消息类型。仅当 strategy='last' 时才应指定。如果指定,则该类型第一次出现之前的所有消息都将被忽略。这是在我们将初始消息修剪到最后 max_tokens 个令牌之后完成的。如果 include_system=True,则不适用于索引 0 处的 SystemMessage。可以指定为字符串名称(例如 'system''human''ai' 等)或 BaseMessage 类(例如 SystemMessageHumanMessageAIMessage 等)。可以是一种类型或类型列表。

类型: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None 默认值: None

include_system

如果索引 0 处有 SystemMessage,是否保留它。仅当 strategy="last" 时才应指定。

类型: bool 默认值: False

text_splitter

用于拆分消息字符串内容的函数或 langchain_text_splitters.TextSplitter。仅在 allow_partial=True 时使用。如果 strategy='last',则将包含部分消息的最后拆分的令牌。如果 strategy='first',则将包含部分消息的第一批拆分的令牌。令牌拆分器假定保留了分隔符,以便可以直接连接拆分的内容以重新创建原始文本。默认为按换行符拆分。

类型: Callable[[str], list[str]] | TextSplitter | None 默认值: None

返回 描述
list[BaseMessage]

修剪后的 BaseMessage 列表。

引发 描述
ValueError

如果指定了两个不兼容的参数或指定了无法识别的 strategy

示例

根据令牌计数修剪聊天记录,如果存在 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 个令牌,允许部分消息

trim_messages(
    messages,
    max_tokens=30,
    token_counter=dummy_token_counter,
    strategy="first",
    allow_partial=True,
)

[
    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."}],
        id="second",
    ),
]

UsageMetadata

基类:TypedDict

消息的使用元数据,如令牌计数。

这是一个跨模型一致的令牌使用情况的标准表示。

示例
{
    "input_tokens": 350,
    "output_tokens": 240,
    "total_tokens": 590,
    "input_token_details": {
        "audio": 10,
        "cache_creation": 200,
        "cache_read": 100,
    },
    "output_token_details": {
        "audio": 10,
        "reasoning": 200,
    },
}

行为在 0.3.9 版本中发生变化

添加了 input_token_detailsoutput_token_details

LangSmith SDK

LangSmith SDK 也有一个 UsageMetadata 类。虽然两者共享字段,但 LangSmith 的 UsageMetadata 具有额外的字段来捕获 LangSmith 平台使用的成本信息。

属性 描述
input_tokens

输入(或提示)令牌的数量。所有输入令牌类型的总和。

类型: int

output_tokens

输出(或完成)令牌的数量。所有输出令牌类型的总和。

类型: int

total_tokens

总令牌数。input_tokens + output_tokens 的总和。

类型: int

input_token_details

输入令牌计数的细分。

类型: NotRequired[InputTokenDetails]

output_token_details

输出令牌计数的细分。

类型: NotRequired[OutputTokenDetails]

input_tokens instance-attribute

input_tokens: int

输入(或提示)令牌的数量。所有输入令牌类型的总和。

output_tokens instance-attribute

output_tokens: int

输出(或完成)令牌的数量。所有输出令牌类型的总和。

total_tokens instance-attribute

total_tokens: int

总令牌数。input_tokens + output_tokens 的总和。

input_token_details instance-attribute

input_token_details: NotRequired[InputTokenDetails]

输入令牌计数的细分。

需要与总输入令牌数相加。需要包含所有键。

output_token_details instance-attribute

output_token_details: NotRequired[OutputTokenDetails]

输出令牌计数的细分。

需要与总输出令牌数相加。需要包含所有键。

InputTokenDetails

基类:TypedDict

输入令牌计数的细分。

需要与总输入令牌数相加。需要包含所有键。

示例
{
    "audio": 10,
    "cache_creation": 200,
    "cache_read": 100,
}

也可能包含提供商特定的额外键。

于 0.3.9 版本中添加

属性 描述
audio

音频输入令牌。

类型: int

cache_creation

被缓存且缓存未命中的输入令牌。

类型: int

cache_read

被缓存且缓存命中的输入令牌。

类型: int

audio instance-attribute

audio: int

音频输入令牌。

cache_creation instance-attribute

cache_creation: int

被缓存且缓存未命中的输入令牌。

由于缓存未命中,缓存是根据这些令牌创建的。

cache_read instance-attribute

cache_read: int

被缓存且缓存命中的输入令牌。

由于缓存命中,令牌是从缓存中读取的。更准确地说,是根据这些令牌的模型状态从缓存中读取的。

OutputTokenDetails

基类:TypedDict

输出令牌计数的细分。

需要与总输出令牌数相加。需要包含所有键。

示例
{
    "audio": 10,
    "reasoning": 200,
}

也可能包含提供商特定的额外键。

于 0.3.9 版本中添加

属性 描述
audio

音频输出令牌。

类型: int

reasoning

推理输出令牌。

类型: int

audio instance-attribute

audio: int

音频输出令牌。

reasoning instance-attribute

reasoning: int

推理输出令牌。

模型在思维链过程中生成(即由 OpenAI 的 o1 模型生成)但未作为模型输出返回的令牌。

© . This site is unofficial and not affiliated with LangChain, Inc.