在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
相关产品推荐
相关产品推荐

