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/8/4 19:06:37 阅读更多 →
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/8/4 19:06:37 阅读更多 →
联邦学习边缘端部署全链路优化(从TensorFlow Lite到TinyML):实测降低83%内存占用与41%延迟

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

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

2026/8/4 19:05:37 阅读更多 →

最新新闻

【图像识别】基于模板匹配算法实现车辆出入库计时matlab系统

【图像识别】基于模板匹配算法实现车辆出入库计时matlab系统

1 简介车辆车牌识别系统的基本工作原理为:将摄像头拍摄到的包含车辆车牌的图像输入到计算机中进行预处理,再由检索模块对车牌进行搜索、检测、定位,并分割出包含车牌字符的矩形区域,然后对车牌字符进行二值化并将其分割为单个字符…

2026/8/4 19:55:56 阅读更多 →
2026暑假老师效率助手:跳绳阅读练字打卡,作业收集批改全搞定

2026暑假老师效率助手:跳绳阅读练字打卡,作业收集批改全搞定

放暑假了,假期虽然少了教学任务,但老师们仍需发布各类打卡,比如学习打卡、阅读打卡、运动打卡、防溺水安全打卡等,督促学生们在假期保持学习状态,确保学生每日安全。 1. 一条接龙,收齐阅读、练字、跳绳所有…

2026/8/4 19:55:56 阅读更多 →
【图像识别】基于模板匹配算法实现卡牌识别matlab代码

【图像识别】基于模板匹配算法实现卡牌识别matlab代码

1 简介随着图像处理、人工智能、计算机技术的不断发展,计算机识别技术也日趋成熟,逐渐转为使用阶段,目前计算机识别方法主要有两种:1) 标记识别技术;2) 基于图像处理的识别技术。第一种方法是先…

2026/8/4 19:54:56 阅读更多 →
ExifToolGUI终极指南:免费高效的图片元数据批量管理完整解决方案

ExifToolGUI终极指南:免费高效的图片元数据批量管理完整解决方案

ExifToolGUI终极指南:免费高效的图片元数据批量管理完整解决方案 【免费下载链接】ExifToolGui A GUI for ExifTool 项目地址: https://gitcode.com/gh_mirrors/ex/ExifToolGui 你是否曾面对成百上千张照片,却不知道如何快速整理拍摄信息&#xf…

2026/8/4 19:54:56 阅读更多 →
Rekognition 实战踩坑:OCR 精度 98% 但人脸分析 API 调用费让我连夜改方案

Rekognition 实战踩坑:OCR 精度 98% 但人脸分析 API 调用费让我连夜改方案

AWS Rekognition 深度成本优化实战:从账单惊吓到混合架构设计 昨晚压测 AWS Rekognition 时,我对着账单倒吸一口凉气——处理 10 万张图片的人脸分析(FaceDetection)费用竟高达 210 美元,而同样数量的 OCR 识别只花了…

2026/8/4 19:54:56 阅读更多 →
【图像识别】基于模板匹配实现花朵分类matlab代码

【图像识别】基于模板匹配实现花朵分类matlab代码

1 简介基于直方图实现花朵分类代码​。2 部分代码%图一&#xff1a;利用直方图进行图像的匹配 %图二&#xff1a;利用形状进行图像的匹配 %交给你们啦~~~~ %-要求mo<num clear; mo 1;%-选取第&#xff1f;幅图像 num5;%图片总数量 distance_const0.8;%设定直方图距离 simil…

2026/8/4 19:54:56 阅读更多 →

日新闻

AI Agent白手起家26: 使用标准事件驱动大模型实践

AI Agent白手起家26: 使用标准事件驱动大模型实践

纲要 练习目标&#xff1a;掌握大模型标准事件的调用回顾 LangChain 中的核心标准事件 invokestreambatchastream_eventswith_structured_output 环境准备实战代码&#xff1a;多种事件调用对比 同步调用与流式输出批量处理异步事件流监听结构化输出 运行说明与预期结果总结与扩…

2026/8/4 0:00:40 阅读更多 →
dealsea是什么?跨境卖家必知的美国deal站入门指南

dealsea是什么?跨境卖家必知的美国deal站入门指南

说实话&#xff0c;第一次听说美国这个老牌折扣网站的跨境卖家&#xff0c;十个有八个会问同一个问题&#xff1a;这个平台到底是干嘛的&#xff1f;我见过一个做家居出口的朋友&#xff0c;他在亚马逊上月销二十万美金&#xff0c;却从来没用过它。我给他看了首页——一屏一屏…

2026/8/4 0:01:40 阅读更多 →
清华大学重磅EST:植物自导电闪蒸焦耳热600°C/2600°C两步法!稀土超积累植物秒级转化为CeO₂-石墨烯电催化剂!

清华大学重磅EST:植物自导电闪蒸焦耳热600°C/2600°C两步法!稀土超积累植物秒级转化为CeO₂-石墨烯电催化剂!

通讯作者&#xff1a;邓兵、刘建国通讯单位&#xff1a;清华大学DOI&#xff1a;https://doi.org/10.1021/acs.est.6c00603研究背景稀土元素&#xff08;REEs&#xff09;是清洁能源技术与电子器件不可或缺的核心原料&#xff0c;然而传统提取方式依赖能耗高、排放大的采矿与强…

2026/8/4 0:01:40 阅读更多 →

周新闻

最大流算法详解:从水管网络到Ford-Fulkerson与Dinic实战

最大流算法详解:从水管网络到Ford-Fulkerson与Dinic实战

1. 从水管网络到最大流&#xff1a;一个核心问题的诞生想象一下&#xff0c;你是一个城市供水系统的总工程师。你的城市有多个水源&#xff08;水库&#xff09;&#xff0c;需要通过一个复杂的地下管道网络&#xff0c;将水输送到各个居民区。每条管道都有其最大通水能力&…

2026/8/4 13:24:41 阅读更多 →
基于Springboot的企业门户网站(源码+LW+调试文档+讲解)

基于Springboot的企业门户网站(源码+LW+调试文档+讲解)

温馨提示&#xff1a;本人主页置顶文章(点我)开头有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;本人主页置顶文章(点我)开头有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;本人主页置顶文章(点我)开头有 CSDN 平台…

2026/8/4 11:41:39 阅读更多 →
MATLAB xcorr函数详解:从互相关原理到四大实战应用

MATLAB xcorr函数详解:从互相关原理到四大实战应用

1. 从一次信号“找茬”说起&#xff1a;为什么我们需要互相关几年前&#xff0c;我在处理一组声学传感器数据时遇到了一个棘手的问题。我有两个麦克风记录了一段相同的音频信号&#xff0c;理论上它们接收到的声音波形应该非常相似&#xff0c;只是由于麦克风位置不同&#xff…

2026/8/4 5:26:40 阅读更多 →

月新闻

免费解锁百度网盘SVIP加速:macOS用户必备的下载提速终极指南

免费解锁百度网盘SVIP加速:macOS用户必备的下载提速终极指南

免费解锁百度网盘SVIP加速&#xff1a;macOS用户必备的下载提速终极指南 【免费下载链接】BaiduNetdiskPlugin-macOS For macOS.百度网盘 破解SVIP、下载速度限制~ 项目地址: https://gitcode.com/gh_mirrors/ba/BaiduNetdiskPlugin-macOS 还在为百度网盘macOS版的龟速下…

2026/8/4 13:38:24 阅读更多 →
终极ncmdump指南:3分钟实现网易云NCM音乐解密与格式转换

终极ncmdump指南:3分钟实现网易云NCM音乐解密与格式转换

终极ncmdump指南&#xff1a;3分钟实现网易云NCM音乐解密与格式转换 【免费下载链接】ncmdump 项目地址: https://gitcode.com/gh_mirrors/ncmd/ncmdump 还在为网易云音乐下载的NCM格式文件无法在其他播放器播放而烦恼吗&#xff1f;ncmdump解密工具帮你轻松解决这个困…

2026/8/4 11:09:16 阅读更多 →
HarmonyOS 应用开发《掌上英语》第81篇: 智能体卡片:为英语学习 App 打造桌面级学习助手

HarmonyOS 应用开发《掌上英语》第81篇: 智能体卡片:为英语学习 App 打造桌面级学习助手

AgentCard 智能体卡片&#xff1a;为英语学习 App 打造桌面级学习助手适用平台&#xff1a;HarmonyOS 7.0 (API 26 Beta)一、引言 HarmonyOS 7.0&#xff08;API 26 Beta&#xff09;新增了 AgentCard 智能体卡片能力&#xff0c;这是继 HMAF&#xff08;鸿蒙智能体框架&#x…

2026/8/4 13:38:40 阅读更多 →