大数跨境

彻底搞懂大模型应用的Messages类型(值得收藏)

彻底搞懂大模型应用的Messages类型(值得收藏) 慧测
2025-12-11
1
导读:LangChain Messages 详细学习文档(超实用)

免费进群技术交流(微信:huice666)

LangChain Messages 详细学习文档,完整源码及资料可以公开课获取哦

目录

1. 概述

2. 核心概念

3. 消息类型详解

4. 消息内容格式

5. 多模态支持

6. 工具调用

7. 最佳实践

概述

什么是 Messages?

Messages(消息)是 LangChain 中与模型交互的基本单位。它们代表了模型的输入和输出,携带了表示对话状态所需的内容和元数据。

消息的核心组成

每个消息对象包含三个主要部分:

1. Role(角色) - 标识消息类型(如 system、user、assistant)

2. Content(内容) - 消息的实际内容(文本、图像、音频、文档等)

3. Metadata(元数据) - 可选字段,如响应信息、消息 ID、token 使用量等

为什么使用 Messages?

 标准化:提供跨所有模型提供商的统一消息类型

 一致性:确保无论调用哪个模型都有一致的行为

 灵活性:支持文本、多模态内容、工具调用等多种场景

 可追溯性:包含元数据用于调试和监控

核心概念

1. 基本使用方式

LangChain 支持三种方式传递消息给模型:

方式一:文本提示(Text Prompts)

response = model.invoke("介绍一下但问智能的大模型应用课程")
   
   
   

适用场景:

 单次独立请求

 不需要保留对话历史

 希望代码简洁

方式二:消息对象列表(Message Prompts)

from langchain.messages import SystemMessage, HumanMessage, AIMessage

messages =[
    SystemMessage("You are a poetry expert"),
    HumanMessage("Write a haiku about spring"),
    AIMessage("Cherry blossoms bloom...")
]
response = model.invoke(messages)

适用场景:

 管理多轮对话

 处理多模态内容(图像、音频、文件)

 包含系统指令

方式三:字典格式(Dictionary Format)

messages =[
{"role":"system","content":"You are a poetry expert"},
{"role":"user","content":"Write a haiku about spring"},
{"role":"assistant","content":"Cherry blossoms bloom..."}
]
response = model.invoke(messages)

适用场景:

 与 OpenAI API 格式兼容

 简化数据序列化

消息类型详解

1. SystemMessage(系统消息)

作用: 设置模型的行为方式和上下文

基本用法:

from langchain.messages import SystemMessage
   
   
   
 
system_msg = SystemMessage("You are a helpful coding assistant.")

高级用法 - 详细角色设定:

system_msg = SystemMessage("""
   
   
   
You are a senior Python developer with expertise in web frameworks.
Always provide code examples and explain your reasoning.
Be concise but thorough in your explanations.
""")

关键点:

 通常放在消息列表的第一位

 用于设定模型的角色、语气和行为准则

 不同提供商对系统消息的处理可能有差异

2. HumanMessage(用户消息)

作用: 代表用户输入和交互

文本内容

from langchain.messages import HumanMessage
   
   
   
 
human_msg = HumanMessage("What is machine learning?")

带元数据

human_msg = HumanMessage(
   
   
   
    content="Hello!",
    name="alice",      # 可选:标识不同用户
    id="msg_123",      # 可选:用于追踪的唯一标识符
)

元数据字段说明:

 name: 用户标识符(某些提供商会使用,某些会忽略)

 id: 消息的唯一标识符,用于追踪和调试

3. AIMessage(AI 消息)

作用: 代表模型的输出

基本响应

response = model.invoke("Explain AI")
   
   
   
print(type(response))  # <class 'langchain.messages.AIMessage'>

手动创建 AIMessage

from langchain.messages import AIMessage

# 手动创建 AI 消息(例如用于对话历史)
ai_msg = AIMessage("I'd be happy to help you with that question!")

# 添加到对话历史
messages =[
    SystemMessage("You are a helpful assistant"),
    HumanMessage("Can you help me?"),
    ai_msg,# 插入,就像它来自模型一样
    HumanMessage("Great! What's 2+2?")
]

AIMessage 的重要属性

属性

类型

说明

text

string

消息的文本内容

content

string | dict[]

消息的原始内容

content_blocks

ContentBlock[]

标准化的内容块

tool_calls

dict[] | None

模型进行的工具调用

id

string

消息的唯一标识符

usage_metadata

dict | None

使用元数据(token 计数等)

response_metadata

ResponseMetadata | None

响应元数据

Token 使用统计

response = model.invoke("Hello!")
   
   
   
print(response.usage_metadata)
# 输出示例:
# {
#     'input_tokens': 8,
#     'output_tokens': 304,
#     'total_tokens': 312,
#     'input_token_details': {'audio': 0, 'cache_read': 0},
#     'output_token_details': {'audio': 0, 'reasoning': 256}
# }

流式响应和分块

chunks = []
   
   
   
full_message = None
for chunk in model.stream("Hi"):
    chunks.append(chunk)
    print(chunk.text)
    full_message = chunk if full_message is None else full_message + chunk

4. ToolMessage(工具消息)

作用: 将工具执行结果传回模型

from langchain.messages import AIMessage, ToolMessage

# 模型进行工具调用后
ai_message = AIMessage(
    content=[],
    tool_calls=[{
"name":"get_weather",
"args":{"location":"San Francisco"},
"id":"call_123"
}]
)

# 执行工具并创建结果消息
weather_result ="Sunny, 72°F"
tool_message = ToolMessage(
    content=weather_result,
    tool_call_id="call_123",# 必须匹配调用 ID
    name="get_weather"
)

# 继续对话
messages =[
    HumanMessage("What's the weather in San Francisco?"),
    ai_message,# 模型的工具调用
    tool_message,# 工具执行结果
]
response = model.invoke(messages)

ToolMessage 属性

属性

类型

必需

说明

content

string

工具调用的字符串化输出

tool_call_id

string

对应的工具调用 ID

name

string

被调用的工具名称

artifact

dict

额外数据,不发送给模型但可编程访问

artifact 字段的使用

artifact 字段存储补充数据,这些数据不会发送给模型,但可以在程序中访问:

# 检索工具示例
   
   
   
message_content = "It was the best of times, it was the worst of times."
artifact = {"document_id": "doc_123", "page": 0}

tool_message = ToolMessage(
    content=message_content,      # 发送给模型
    tool_call_id="call_123",
    name="search_books",
    artifact=artifact,            # 仅供应用程序使用
)

消息内容格式

Content 属性

消息的 content 属性是发送给模型的数据负载,支持:

1. 字符串

2. 提供商原生格式的对象列表

3. LangChain 标准内容块列表

多模态输入示例

from langchain.messages import HumanMessage

# 字符串内容
human_message = HumanMessage("Hello, how are you?")

# 提供商原生格式(如 OpenAI)
human_message = HumanMessage(content=[
{"type":"text","text":"Hello, how are you?"},
{"type":"image_url","image_url":{"url":"https://example.com/image.jpg"}}
])

# 标准内容块
human_message = HumanMessage(content_blocks=[
{"type":"text","text":"Hello, how are you?"},
{"type":"image","url":"https://example.com/image.jpg"},
])

多模态支持

LangChain 支持多种数据形式:文本、音频、图像、视频。

1. 图像输入

# 从 URL
   
   
   
message = {
    "role": "user",
    "content": [
        {"type": "text", "text": "Describe the content of this image."},
        {"type": "image", "url": "https://example.com/path/to/image.jpg"},
    ]
}

# 从 base64 数据
message = {
    "role": "user",
    "content": [
        {"type": "text", "text": "Describe the content of this image."},
        {
            "type": "image",
            "base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
            "mime_type": "image/jpeg",
        },
    ]
}

# 从提供商管理的文件 ID
message = {
    "role": "user",
    "content": [
        {"type": "text", "text": "Describe the content of this image."},
        {"type": "image", "file_id": "file-abc123"},
    ]
}

2. PDF 文档输入

message = {
   
   
   
    "role": "user",
    "content": [
        {"type": "text", "text": "Summarize this document."},
        {
            "type": "file",
            "url": "https://example.com/document.pdf",
            "mime_type": "application/pdf",
        },
    ]
}

3. 音频输入

message = {
   
   
   
    "role": "user",
    "content": [
        {"type": "text", "text": "Transcribe this audio."},
        {
            "type": "audio",
            "base64": "UklGRiQAAABXQVZFZm10...",
            "mime_type": "audio/wav",
        },
    ]
}

4. 视频输入

message = {
   
   
   
    "role": "user",
    "content": [
        {"type": "text", "text": "What happens in this video?"},
        {
            "type": "video",
            "url": "https://example.com/video.mp4",
            "mime_type": "video/mp4",
        },
    ]
}

工具调用

工具调用流程

from langchain.chat_models import init_chat_model
   
   
   

model = init_chat_model("gpt-5-nano")

def get_weather(location: str) -> str:
    """Get the weather at a location."""
    ...

model_with_tools = model.bind_tools([get_weather])
response = model_with_tools.invoke("What's the weather in Paris?")

# 检查工具调用
for tool_call in response.tool_calls:
    print(f"Tool: {tool_call['name']}")
    print(f"Args: {tool_call['args']}")
    print(f"ID: {tool_call['id']}")

最佳实践

1. 选择合适的消息格式

 简单任务:使用文本提示

 对话系统:使用消息对象列表

 多模态应用:使用内容块

2. 管理对话历史

# 保持对话上下文
   
   
   
conversation_history = [
    SystemMessage("You are a helpful assistant"),
]

# 添加用户消息
conversation_history.append(HumanMessage("Hello"))

# 获取响应
response = model.invoke(conversation_history)

# 添加 AI 响应到历史
conversation_history.append(response)

3. 监控 Token 使用

response = model.invoke(messages)
   
   
   
if response.usage_metadata:
    print(f"Input tokens: {response.usage_metadata['input_tokens']}")
    print(f"Output tokens: {response.usage_metadata['output_tokens']}")
    print(f"Total tokens: {response.usage_metadata['total_tokens']}")

4. 错误处理

try:
   
   
   
    response = model.invoke(messages)
ifhasattr(response,'invalid_tool_calls'):
for invalid_call in response.invalid_tool_calls:
print(f"Invalid tool call: {invalid_call['name']}")
print(f"Error: {invalid_call['error']}")
except Exception as e:
print(f"Error invoking model: {e}")

总结

LangChain Messages 提供了一个强大而灵活的框架来处理与 LLM 的交互:

 统一接口:跨不同模型提供商的一致 API

 丰富功能:支持文本、多模态、工具调用等

 可扩展性:易于集成到复杂的应用程序中

 可观测性:内置元数据和使用统计

通过理解和正确使用这些消息类型,你可以构建更强大、更可靠的 AI 应用程序。

 免费进群技术交流(huice666)


【声明】内容源于网络
0
0
慧测
专注人工智能前沿技术落地企业实战应用
内容 404
粉丝 0
慧测 专注人工智能前沿技术落地企业实战应用
总阅读104
粉丝0
内容404