You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在LangGraph中如何快速获取用户第一条HumanMessage的内容?

获取LangGraph状态中第一条HumanMessage内容的最优方式

实现思路

直接基于消息类型判断,遍历状态里的messages序列,找到第一个HumanMessage实例后直接读取其content属性,全程无需解析消息内容。

代码示例

from langchain_core.messages import HumanMessage

def get_first_human_content(state: AgentState) -> str | None:
    for msg in state["messages"]:
        if isinstance(msg, HumanMessage):
            return msg.content
    return None  # 无HumanMessage时返回None

说明

  • 借助Python内置的isinstance做类型校验,再直接访问content属性,这是效率最高的方式,完全避开了解析操作。
  • 因为messages是通过add_messages配置为追加模式,所以遍历到的第一个HumanMessage就是用户插入的第一条人类消息。

内容的提问来源于stack exchange,提问作者Simone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:39:51