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

如何在LangGraph中自定义astream_events的LLM与Tool节点输出?

自定义LangGraph astream_events输出,过滤冗余数据

针对你遇到的astream_events返回冗余数据的问题,有两种直接可行的解决方案:

1. 遍历事件时过滤冗余内容

直接在事件循环里筛选LLM和Tool节点的关键数据,忽略不需要的事件和字段:

async for event in graph.astream_events(human_message, version="v2", stream_mode="values"):
    # 仅处理LLM和Tool节点的事件
    if event['name'] in [Node.LLM, Node.Tool]:
        # 提取核心输出,按需调整字段
        filtered_event = {
            "node_type": event['name'],
            "output": event['data']['output']
        }
        print(filtered_event)

这种方式不需要修改节点逻辑,快速实现数据过滤。

2. 从节点源头精简输出

如果希望从根本上减少事件数据量,可以封装LLM和Tool节点的逻辑,提前处理输出内容:

精简LLM节点输出

给原LLM调用链加一层处理,只保留你需要的内容(比如工具调用信息或纯文本回复):

def process_llm_result(messages: List[BaseMessage]) -> BaseMessage:
    # 执行原LLM调用流程
    raw_response = (get_history_messages | llm.bind(tools)).invoke(messages)
    # 按需保留内容,示例:只保留工具调用或纯文本
    if hasattr(raw_response, 'tool_calls') and raw_response.tool_calls:
        return AIMessage(content="", tool_calls=raw_response.tool_calls)
    else:
        return AIMessage(content=raw_response.content)

# 替换原call_llm
call_llm = process_llm_result

精简Tool节点输出

修改call_tool函数,只返回核心工具结果,而非全量数据:

def call_tool(messages: List[BaseMessage]):
    response = ...  # 原工具调用逻辑
    # 提取核心结果字段,而非返回完整response
    simplified_result = {"核心结果": response.get("你需要的键名")}
    return ToolMessage(tool_call_id=uuid4(), content=json.dumps(simplified_result))

这样节点输出本身就被精简,后续astream_events返回的事件自然不再包含冗余内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:41:06