05 langchain-Core_Components-Messages
https://docs.langchain.com/oss/python/langchain/messagesmessage是与大模型交互信息的载体包括角色system\user、内容、大数据(id\token usage)等基础应用创建message实体然后在大模型invoke时传递进去from langchain.chat_models import init_chat_model from langchain.messages import HumanMessage, AIMessage, SystemMessage model init_chat_model(gpt-5-nano) system_msg SystemMessage(You are a helpful assistant.) human_msg HumanMessage(Hello, how are you?) # Use with chat models messages [system_msg, human_msg] response model.invoke(messages) # Returns AIMessage文本prompt直接用一串字符串来发送单一的请求response model.invoke(“Write a haiku about spring”)message prompt可以用message列表来作为提示词用于管理多轮对话、多模态数据和system信息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)字典类型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)参考quick-startrole是OPENAI对话系统的角色常见的有user、system、assistant其中system是用于定义对话的框架设定对话背景或者模型行为user指代用户或者提问的一方assistant指代回答问题的AI系统message 类型systemMessage:告诉model如何行动并为交互提供上下文信息humanMessage:用户输入AIMessage:模型反馈响应包含文本内容、工具调用和大数据ToolMessage:工具调用的反馈system messagesystem_msg SystemMessage(You are a helpful coding assistant.) messages [ system_msg, HumanMessage(How do I create a REST API?) ] response model.invoke(messages)from langchain.messages import SystemMessage, HumanMessage 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. ) messages [ system_msg, HumanMessage(How do I create a REST API?) ] response model.invoke(messages)human messagetext contentresponse model.invoke([ HumanMessage(What is machine learning?) ])[!NOTE] invoke输入参数类型字符串或者message的列表注意是列表而不是单独的messageLanguageModelInputPromptValue | str | Sequence[MessageLikeRepresentation]MessageLikeRepresentation ( BaseMessage | list[str] | tuple[str, str] | str | dict[str, Any])# Using a string is a shortcut for a single HumanMessage response model.invoke(What is machine learning?)message metadatahuman message中包含多个参数支持信息传入from langchain_core.runnables import RunnableLambda, RunnablePassthrough,ConfigurableField from langchain.tools import tool from langchain.chat_models import init_chat_model from langchain_deepseek import ChatDeepSeek import os from langchain.messages import HumanMessage from langchain_core.tracers.schemas import Run import time def fn_start(run_obj: Run): print(run_obj) print(start_time:, run_obj.start_time) def fn_end(run_obj: Run): print(end_time:, run_obj.end_time) model init_chat_model( modeldeepseek-chat, api_keysk-xxxx, ).with_listeners( on_startfn_start, on_endfn_end ) human_msg HumanMessage( contentHello!, namealice, # Optional: identify different users idmsg_123, # Optional: unique identifier for tracing ) response model.invoke([human_msg]) print(response)参数content: str | list[str | dict]message内容additional_kwargs: dictmessage附加的信息from langchain_core.runnables import RunnableLambda, RunnablePassthrough,ConfigurableField from langchain.tools import tool from langchain.chat_models import init_chat_model from langchain_deepseek import ChatDeepSeek import os from langchain.messages import HumanMessage from langchain_core.tracers.schemas import Run import time def fn_start(run_obj: Run): print(run_obj) print(start_time:, run_obj.start_time) def fn_end(run_obj: Run): print(end_time:, run_obj.end_time) model init_chat_model( modeldeepseek-chat, api_keysk-xxxx, ).with_listeners( on_startfn_start, on_endfn_end ) from langchain.messages import AIMessage, SystemMessage, HumanMessage # Add to conversation history messages [ HumanMessage(Great! Whats it?,additional_kwargs{aaaaa:bbbbb}) ] response model.invoke(messages) print(response)response_metadata: dict响应头、对数概率、token数量、模型名称name:str|Nonemessage的名称id:str|Nonemessage的idcontent_blocks:list[types.ContentBlock]多模态的内容输入除了text文本信息之外还包含多种其他类型输入等应用多模态的时候再考虑text:TextAccessor获取message的文本内容from langchain.messages import AIMessage, SystemMessage, HumanMessage # Create an AI message manually (e.g., for conversation history) # Add to conversation history humHumanMessage(Great! Whats it?) print(hum.text)AI message调用大模型后的响应可以构造一条message后注入到history中from langchain.messages import AIMessage, SystemMessage, HumanMessage # Create an AI message manually (e.g., for conversation history) ai_msg AIMessage(Id be happy to help you with that question!) # Add to conversation history messages [ SystemMessage(You are a helpful assistant), HumanMessage(Can you help me?), ai_msg, # Insert as if it came from the model HumanMessage(Great! Whats 22?) ] response model.invoke(messages)参数包含text、content、content_blocks、tool_calls、id、usage_metadata、response_metadatastreaming and chunk流式输出AIMessageChunkfrom langchain.chat_models import init_chat_model from langchain_core.tracers.schemas import Run chunks[] model init_chat_model( modeldeepseek-chat, api_keysk-xxxx, ) full_messageNone for chunk in model.stream(Hello!): chunks.append(chunk) # print(chunk) full_message chunk if full_message is None else full_message chunk print(full_message)Tool messagetool工具响应toolcall的反馈也可以构造相关message注意tool_call id需要保持一致from langchain.chat_models import init_chat_model model init_chat_model( modeldeepseek-chat, api_keysk-xxxx, ) from langchain.messages import AIMessage,HumanMessage from langchain.messages import ToolMessage # After a model makes a tool call # (Here, we demonstrate manually creating the messages for brevity) ai_message AIMessage( content[], tool_calls[{ name: get_weather, args: {location: San Francisco}, id: call_123 }] ) # Execute tool and create result message weather_result Sunny, 72°F tool_message ToolMessage( contentweather_result, tool_call_idcall_123 # Must match the call ID ) # Continue conversation messages [ HumanMessage(Whats the weather in San Francisco?), ai_message, # Models tool call tool_message, # Tool execution result ] response model.invoke(messages) # Model processes the result print(response)如果id不匹配就会出现异常artifacttool message中附加数据但不会被传输到model中可以在其他程序中应用from langchain.messages import ToolMessage # Sent to model message_content It was the best of times, it was the worst of times. # Artifact available downstream artifact {document_id: doc_123, page: 0} tool_message ToolMessage( contentmessage_content, tool_call_idcall_123, namesearch_books, artifactartifact, )message contentmessage中包含content信息类型可以是str,也可以是content block列表from langchain.messages import HumanMessage # String content human_message HumanMessage(Hello, how are you?) # Provider-native format (e.g., OpenAI) human_message HumanMessage(content[ {type: text, text: Hello, how are you?}, {type: image_url, image_url: {url: https://example.com/image.jpg}} ]) # List of standard content blocks human_message HumanMessage(content_blocks[ {type: text, text: Hello, how are you?}, {type: image, url: https://example.com/image.jpg}, ])standard content blocks可用于跨模型厂商之间的信息交互并可以保证接口类型的正确性TextContentBlock{“type”: “text”,“text”: “Hello world”,“annotations”: []:List of annotations for the text}ReasoningContentBlock{“type”: “reasoning”,“reasoning”: “The user is asking about…”,“extras”: {“signature”: “abc123”},}ImageContentBlock等多模态相关信息待需要再行研究toolCall{“type”: “tool_call”,“name”: “search”,“args”: {“query”: “weather”},“id”: “call_123”}多模态此处仅贴例子待有相关条件后再行尝试# From URL message { role: user, content: [ {type: text, text: Describe the content of this image.}, {type: image, url: https://example.com/path/to/image.jpg}, ] } # From base64 data message { role: user, content: [ {type: text, text: Describe the content of this image.}, { type: image, base64: AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2..., mime_type: image/jpeg, }, ] } # From provider-managed File ID message { role: user, content: [ {type: text, text: Describe the content of this image.}, {type: image, file_id: file-abc123}, ] }Use with chat model由于大模型调用没有状态记录因此需要一个不断append的message list来记录对话过程

相关新闻

EdgeRemover:Windows系统彻底卸载Microsoft Edge的完整解决方案

EdgeRemover:Windows系统彻底卸载Microsoft Edge的完整解决方案

EdgeRemover:Windows系统彻底卸载Microsoft Edge的完整解决方案 【免费下载链接】EdgeRemover A PowerShell script that correctly uninstalls or reinstalls Microsoft Edge on Windows 10 & 11. 项目地址: https://gitcode.com/gh_mirrors/ed/EdgeRemover …

2026/9/24 1:18:10 阅读更多 →
5分钟掌握Windows与Office智能激活:KMS_VL_ALL_AIO全面解析

5分钟掌握Windows与Office智能激活:KMS_VL_ALL_AIO全面解析

5分钟掌握Windows与Office智能激活:KMS_VL_ALL_AIO全面解析 【免费下载链接】KMS_VL_ALL_AIO Smart Activation Script 项目地址: https://gitcode.com/gh_mirrors/km/KMS_VL_ALL_AIO 还在为系统激活烦恼吗?KMS_VL_ALL_AIO智能激活脚本为您提供了…

2026/10/2 4:43:38 阅读更多 →
联邦学习边缘端部署全链路优化(从TensorFlow Lite到TinyML):实测降低83%内存占用与41%延迟

联邦学习边缘端部署全链路优化(从TensorFlow Lite到TinyML):实测降低83%内存占用与41%延迟

更多请点击: https://codechina.net 第一章:联邦学习边缘端部署全链路优化的范式演进 联邦学习在边缘场景落地面临通信开销大、设备异构性强、资源受限及隐私-效用-延迟三元权衡等核心挑战。早期单层聚合范式(如FedAvg)直接迁移至…

2026/9/29 0:32:11 阅读更多 →

最新新闻

为什么2026年你该试试Orkas:local-first多智能体AI桌面应用,一位Commander指挥9位专家Agent

为什么2026年你该试试Orkas:local-first多智能体AI桌面应用,一位Commander指挥9位专家Agent

为什么2026年你该试试Orkas:local-first多智能体AI桌面应用,一位Commander指挥9位专家Agent 【免费下载链接】Orkas Orkas is an open-source, local-first AI desktop app: a commander LLM directs specialist sub-agents, and runs your installed co…

2026/10/7 8:37:20 阅读更多 →
# AI 时代开发者如何保持竞争力:你需要强化的三项核心技能

# AI 时代开发者如何保持竞争力:你需要强化的三项核心技能

AI 时代开发者如何保持竞争力:你需要强化的三项核心技能 AI 正在改变开发者的工作方式。手写代码依然必要,但你现在更需要懂得如何指挥 AI、评估质量、权衡技术方案并做出决策。这其实不难,你可以从以下三个方向开始练手。 变成调度者&#x…

2026/10/7 8:37:20 阅读更多 →
libwebsockets lws-acme-client 插件实战:在 lwsws 中自动签发与续期 Let‘s Encrypt TLS 证书

libwebsockets lws-acme-client 插件实战:在 lwsws 中自动签发与续期 Let‘s Encrypt TLS 证书

人工智能AI Agent多模态语音AI 应用 【免费下载链接】ten-framework Open-source framework for conversational voice AI agents 项目地址: https://gitcode.com/TEN-framework/ten-framework 点击查看 免费下载 本篇文章以 third_party/libwebsockets 仓库中的 l…

2026/10/7 8:37:20 阅读更多 →
基于 MCP 协议的 GEO 检测 Agent 化实践:控制面/执行面分离架构

基于 MCP 协议的 GEO 检测 Agent 化实践:控制面/执行面分离架构

摘要:本文记录将 GEO(生成式引擎优化)品牌可见度检测流程 Agent 化的完整工程实践:网站作为控制面负责任务状态机与数据归属,AI 工作台(腾讯 WorkBuddy)作为执行面通过自定义 MCP 连接器领取并执…

2026/10/7 8:37:20 阅读更多 →
木工机械出口中东:220V/240V/400V/415V转380V变压器选型 卓尔凡技术分享

木工机械出口中东:220V/240V/400V/415V转380V变压器选型 卓尔凡技术分享

随着中国木工机械不断出口到中东市场,数控开料机、封边机、雕刻机、裁板锯、砂光机、四面刨等设备在沙特、阿联酋、伊朗、伊拉克、科威特、卡塔尔、阿曼、约旦、埃及等国家越来越常见。但很多设备厂家和外贸商都会遇到一个实际问题:国内木工机械大多按三…

2026/10/7 8:37:20 阅读更多 →
humanizer如何让改写不失真?SFT+DPO+GRPO训练流水线完整拆解(全程不用AI检测器)

humanizer如何让改写不失真?SFT+DPO+GRPO训练流水线完整拆解(全程不用AI检测器)

humanizer如何让改写不失真?SFTDPOGRPO训练流水线完整拆解(全程不用AI检测器) 【免费下载链接】humanizer 项目地址: https://ai.gitcode.com/hf_mirrors/jialinyyzz/humanizer humanizer 是一个 12B 参数的本地 AI 文本改写模型&…

2026/10/7 8:36:19 阅读更多 →

日新闻

ROS2机械臂仿真与运动控制:从URDF建模到Gazebo实战全解析

ROS2机械臂仿真与运动控制:从URDF建模到Gazebo实战全解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/7 1:01:58 阅读更多 →
用浏览器直接改ESP32的WiFi密码:NVS键值配置工具设计与实现

用浏览器直接改ESP32的WiFi密码:NVS键值配置工具设计与实现

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/7 1:02:00 阅读更多 →
芯片封装缺陷检测:扫描声学显微镜(SAT)原理与实操指南

芯片封装缺陷检测:扫描声学显微镜(SAT)原理与实操指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/7 1:02:00 阅读更多 →

周新闻

KT148A语音芯片外挂8002D功放的工程实践指南

KT148A语音芯片外挂8002D功放的工程实践指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/6 7:15:40 阅读更多 →
LLC谐振变换器增益公式推导:从FHA等效到完整归一化表达式

LLC谐振变换器增益公式推导:从FHA等效到完整归一化表达式

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/6 5:29:09 阅读更多 →
ARM架构深度解析:从RISC设计理念到交叉编译实战

ARM架构深度解析:从RISC设计理念到交叉编译实战

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/6 6:26:51 阅读更多 →

月新闻

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/6 8:21:32 阅读更多 →
Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/6 4:21:51 阅读更多 →
黑夜航拍船只数据集训练YOLOV5模型全流程解析

黑夜航拍船只数据集训练YOLOV5模型全流程解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/6 1:18:13 阅读更多 →