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/10/21 23:41:12 阅读更多 →
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/27 15:35:32 阅读更多 →
联邦学习边缘端部署全链路优化(从TensorFlow Lite到TinyML):实测降低83%内存占用与41%延迟

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

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

2026/11/3 14:23:47 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/5 12:28:00 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/5 1:08:50 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/5 12:28:01 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/5 12:28:02 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/5 0:54:28 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/4 19:19:54 阅读更多 →

日新闻

周新闻

月新闻