01. LangGraph 两种流式模式

在 LangGraph 中,编译后的 图程序 也是一个 Runnable可运行组件,并支持多种流式模式输出,和 LLM 使用流式模式输出一个一个词不一样,在 LangGraph 中,流式响应每次输出的都是一个节点的 数据状态,在 LangGraph 中流式模式有两种:

  • values:此流式模式返回图的值,这是每个节点调用后图的 完整状态(总量);
  • updates:此流式模式返回图的更新,这是每个节点调用后图的 状态的更新(增量);

要想使用流式模式非常简单,在调用 stream() 函数时,传递 stream_mode 参数即可配置不同的流式响应模式,以 ReACT 智能体为例,使用流式模式输出 values 模式的数据,代码如下

inputs = {"messages": [("human", "2024年北京半程马拉松的前3名成绩是多少?")]}

for chunk in agent.stream(

        inputs,

        stream_mode="values",

):

print(chunk["messages"][-1].pretty_print())

在上述的代码中,由于使用 values 模式,所以每个节点流式输出的内容都是完整的 数据状态,每次都取出消息中的最后一条并进行格式化输出,输出内容如下

================================ Human Message =================================

2024年北京半程马拉松的前3名成绩是多少?

None

================================== Ai Message ==================================

Tool Calls:

  google_serper (call_5bBUF3wgFFAA5Uo6UrcCsPjh)

 Call ID: call_5bBUF3wgFFAA5Uo6UrcCsPjh

  Args:

    query: 2024年北京半程马拉松前3名成绩

None

================================= Tool Message =================================

Name: google_serper

经过激烈角逐,男子组方面,中国选手何杰以1小时03分44秒的成绩夺得冠军,埃塞俄比亚选手DEJENE HAILU BIKILA以及来自肯尼亚的Robert Keter和WILLY MNANGAT三人以1小时03分45秒的成绩并列获得亚军,中国选手李春晖则以1小时06分58秒的成绩获得季军。

None

================================== Ai Message ==================================

2024年北京半程马拉松的前3名成绩如下:

1. **冠军**:何杰(中国),成绩:1小时03分44秒

2. **亚军**:埃塞俄比亚选手 DEJENE HAILU BIKILA、肯尼亚选手 Robert Keter 和 WILLY MNANGAT,成绩:1小时03分45秒(并列)

3. **季军**:李春晖(中国),成绩:1小时06分58秒

None

在上述代码中,可以很清晰看到在 LangGraph 中,流式输出是以 节点 作为单位生成内容的,将 stream_mode 切换成 updates,这样每次流式响应返回的内容是节点对应 状态的更新,调整的代码如下

inputs = {"messages": [("human", "2024年北京半程马拉松的前3名成绩是多少?")]}

for chunk in agent.stream(

        inputs,

        stream_mode="updates",

):

    print(chunk)

输出内容如下:

{'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Uue3f3nABE1Hytcg2UmVyeD1', 'function': {'arguments': '{"query":"2024 Beijing Half Marathon results top 3 finishers"}', 'name': 'google_serper'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 25, 'prompt_tokens': 169, 'total_tokens': 194}, 'model_name': 'gpt-4o-mini', 'system_fingerprint': 'fp_80a1bad4c7', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-b19b4cca-fc24-456c-ba26-c9a023620e72-0', tool_calls=[{'name': 'google_serper', 'args': {'query': '2024 Beijing Half Marathon results top 3 finishers'}, 'id': 'call_Uue3f3nABE1Hytcg2UmVyeD1', 'type': 'tool_call'}], usage_metadata={'input_tokens': 169, 'output_tokens': 25, 'total_tokens': 194})]}}

{'tools': {'messages': [ToolMessage(content="Chinese runner He Jie, Ethiopian Dejene Hailu Bikila and Kenyans Robert Keter and Willy Mnangat at the finish line of the Beijing Half Marathon ... A controversial result finish at the Beijing Half Marathon is being investigated by event ... Duration: 0:42. Posted: Apr 15, 2024. Organizers are investigating a half marathon race in Beijing after three African runners appeared to let China's top long-distance runner ... The top three finishers of the Beijing half marathon are stripped of their medals after an investigation into the controversial result. Organisers have revoked He Jie's first place in the Beijing half marathon last weekend after an investigation confirmed that three other ... Missing: 3 | Show results with:3. China's marathon runner He Jie won the 2024 Beijing Half Marathon on Sunday with a time of 1:03:44. He was just one second ahead of Ethiopian ... The top finishers in the Beijing Half Marathon have been disqualified after three runners from Africa appeared to step aside to let a ... Missing: results | Show results with:results. The race's bizarre finish saw He Jie cross the line first after two runners from Kenya and one from Ethiopia seemed to deliberately allow him to ... Missing: finishers | Show results with:finishers. Beijing half marathon's bizarre finish saw He Jie cross the line first after the Kenyans Robert Keter and Willy Mnangat, and Dejene Hailu from ... Missing: finishers | Show results with:finishers. Video evidence from the final moments of the race showed He trailing behind Kenya's Robert Keter and Willy Mnangat and Ethiopia's Dejene Hailu. Missing: finishers | Show results with:finishers.", name='google_serper', tool_call_id='call_Uue3f3nABE1Hytcg2UmVyeD1')]}}

{'agent': {'messages': [AIMessage(content='在2024年北京半程马拉松中,最终的排名出现了争议。根据报道,中国选手何杰在比赛中以1小时03分44秒的成绩跨线第一,但由于调查发现其他选手似乎故意让他领先,三名非洲选手的名次和成绩也受到影响。\n\n尽管初步结果显示何杰获得第一,但由于争议,赛事组织方正在调查这起事件。实际上,赛后可能会撤销这些选手的名次和奖牌。\n\n因此,目前无法确认最终的前三名的官方结果。如果您需要更详细的信息,请关注相关赛事的官方公告。', response_metadata={'token_usage': {'completion_tokens': 140, 'prompt_tokens': 548, 'total_tokens': 688}, 'model_name': 'gpt-4o-mini', 'system_fingerprint': 'fp_80a1bad4c7', 'finish_reason': 'stop', 'logprobs': None}, id='run-be8123c2-5c57-4a4c-a071-ef7c22665bcd-0', usage_metadata={'input_tokens': 548, 'output_tokens': 140, 'total_tokens': 688})]}}

可以看到返回的数据并不是完整的数据,而是对应节点更新的增量数据,并且格式为字典,键为 节点名称,值为 状态的更新。

02. 扩展与思考

在上述的两种流式模式中,虽然可以正确获取每个节点的数据,但是等待的时间仍然过长,特别是和大语言模型相关的节点,其根本原因在于 节点 也应该进行 流式输出,例如 大语言模型节点,在 图 的流式输出下,也应该保持流式输出,而不是完整输出。

这也是常见的 Agent 的输出方式,例如 Coze、Dify、智谱、GPTs 等,如下

在上述的动图演示中,可以看到 Agent 执行了几个步骤:知识库检索、工具调用、LLM生成内容,当每个步骤完成之后都会流式返回内容给前端,并且在一些相对耗时的步骤,例如 LLM生成内容 也在该步骤内进行了流式输出,这样可以避免用户亦或者 API 接口长时间没有响应导致连接中断,也能提升用户体验。

两种对比方式如下

在 LangGraph 中,可以通过 LangGraph 原生的支持来实现 外层节点流式输出 + 节点内部流式事件 方案,不过该方案使用到了 异步流式事件 的功能;除此之外,也可以通过为节点添加 队列 + 异步 的方式来实现,两种实现方式各有差异+优缺点,不过在这一章中我们暂时不会讲解该功能,等到第 8 周讲解《响应模块开发与流式响应升级》时,我们会来更深入讲解,并在 LLMOps 项目中来实现上述演示图的效果。

感兴趣的同学可以提前阅读 LangGraph 的相关参考资料:Redirecting...

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐