2026/6/20 8:27:51
网站建设
项目流程
金昌网站建设,html国外网站源码,网站设计常用软件,长沙做网站的费用1. 消息核心概念
消息#xff08;Messages#xff09; 是LangChain中模型交互的基本上下文单元#xff0c;代表着模型输入和输出的结构化数据载体。每个消息对象包含三个核心组成部分#xff1a;
角色#xff08;Role#xff09;#xff1a;标识消息类型#xff08;如s…1. 消息核心概念消息Messages是LangChain中模型交互的基本上下文单元代表着模型输入和输出的结构化数据载体。每个消息对象包含三个核心组成部分角色Role标识消息类型如system、user、assistant内容Content消息的实际内容支持文本、图像、音频、文档等元数据Metadata可选字段如响应信息、消息ID和令牌使用情况在LangChain架构中消息既是对话状态的表现形式也是模型调用的标准接口为LLM交互提供了统一的抽象层。2. 消息类型详解2.1 系统消息SystemMessage系统消息用于引导模型行为和设置交互上下文是对话的初始化指令fromlangchain.messagesimportSystemMessage# 基础指令system_msgSystemMessage(You are a helpful coding assistant.)# 详细角色定义detailed_system_msgSystemMessage( 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.2 人类消息HumanMessage人类消息代表用户输入支持多模态内容fromlangchain.messagesimportHumanMessage# 文本内容human_msgHumanMessage(What is machine learning?)# 带元数据的人类消息human_msg_with_metadataHumanMessage(contentHello!,namealice,# 可选标识不同用户idmsg_123,# 可选用于追踪的唯一标识符)2.3 AI消息AIMessageAI消息表示模型输出包含响应内容、工具调用和元数据fromlangchain.messagesimportAIMessage# 从模型获取的响应responsemodel.invoke(Explain AI)print(type(response))# class langchain.messages.AIMessage# 手动创建AI消息用于对话历史manual_ai_msgAIMessage(Id be happy to help you with that question!)2.4 工具消息ToolMessage工具消息用于传递工具执行结果给模型fromlangchain.messagesimportToolMessage# 创建工具消息tool_messageToolMessage(contentSunny, 72°F,# 工具执行结果tool_call_idcall_123,# 必须与AI消息中的工具调用ID匹配nameget_weather,# 被调用工具的名称artifact{document_id:doc_123,page:0}# 不发送给模型的附加数据)3. 基本使用方式3.1 三种调用格式文本提示适用于单次独立请求responsemodel.invoke(Write a haiku about spring)消息对象列表适用于多轮对话fromlangchain.messagesimportSystemMessage,HumanMessage,AIMessage messages[SystemMessage(You are a poetry expert),HumanMessage(Write a haiku about spring),AIMessage(Cherry blossoms bloom...)]responsemodel.invoke(messages)字典格式OpenAI兼容格式messages[{role:system,content:You are a poetry expert},{role:user,content:Write a haiku about spring},{role:assistant,content:Cherry blossoms bloom...}]responsemodel.invoke(messages)3.2 完整工作流程示例fromlangchain.chat_modelsimportinit_chat_modelfromlangchain.messagesimportHumanMessage,AIMessage,SystemMessage# 初始化模型modelinit_chat_model(gpt-5-nano)# 创建消息序列system_msgSystemMessage(You are a helpful assistant.)human_msgHumanMessage(Hello, how are you?)# 调用模型messages[system_msg,human_msg]responsemodel.invoke(messages)# 返回AIMessage4. 高级功能特性4.1 工具调用当模型绑定工具时AI消息中会包含工具调用信息fromlangchain.chat_modelsimportinit_chat_model modelinit_chat_model(gpt-5-nano)# 定义工具函数defget_weather(location:str)-str:Get the weather at a location....# 绑定工具并调用model_with_toolsmodel.bind_tools([get_weather])responsemodel_with_tools.invoke(Whats the weather in Paris?)# 处理工具调用fortool_callinresponse.tool_calls:print(fTool:{tool_call[name]})print(fArgs:{tool_call[args]})print(fID:{tool_call[id]})4.2 令牌使用统计AI消息包含详细的令牌使用元数据responsemodel.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}# }4.3 流式响应处理处理流式响应时接收的是AIMessageChunk对象chunks[]full_messageNoneforchunkinmodel.stream(Hi):chunks.append(chunk)print(chunk.text)full_messagechunkiffull_messageisNoneelsefull_messagechunk5. 内容格式详解5.1 内容表示方式消息内容支持三种表示形式fromlangchain.messagesimportHumanMessage# 1. 字符串形式human_messageHumanMessage(Hello, how are you?)# 2. 提供者原生格式human_messageHumanMessage(content[{type:text,text:Hello, how are you?},{type:image_url,image_url:{url:https://example.com/image.jpg}}])# 3. 标准内容块类型安全接口human_messageHumanMessage(content_blocks[{type:text,text:Hello, how are you?},{type:image,url:https://example.com/image.jpg},])5.2 多模态内容支持LangChain支持多种多模态输入格式# 从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,},]}# 使用提供者管理的文件IDmessage{role:user,content:[{type:text,text:Describe the content of this image.},{type:image,file_id:file-abc123},]}6. 最佳实践指南6.1 消息组织原则明确角色分配正确使用系统、用户和助手角色合理使用元数据为消息添加ID和名称以支持追踪和调试保持对话状态将完整对话历史作为消息序列传递6.2 性能优化建议使用内容块标准表示跨提供者的一致接口合理设置环境变量使用LC_OUTPUT_VERSIONv1以获得标准内容块表示监控令牌使用通过usage_metadata分析成本和使用模式6.3 错误处理策略验证工具调用ID匹配确保ToolMessage的tool_call_id与AI消息中的调用ID一致检查模型支持能力确认目标模型支持所需的多模态格式和文件类型处理提供者差异注意不同提供者对消息字段如name的支持差异总结LangChain的Messages模块提供了强大而灵活的消息抽象层支持从简单的文本对话到复杂的多模态交互和工具调用。通过掌握消息的核心概念、类型系统和使用模式开发者可以构建出高效、可靠且可维护的LLM应用。消息作为LangChain中模型交互的统一接口其设计平衡了灵活性与类型安全同时保持了与主流提供者API的兼容性。在实际应用中建议根据具体需求选择适当的消息格式和调用方式并结合最佳实践进行优化。