Kasi Yaswanth

我最近花了几个小时调试一个基于 LangGraph 和 MCP 构建的支持机器人,结果发现问题并不在于代理的推理本身,而在于我们向用户呈现推理的方式。机器人经常看起来像卡在加载动画上,让用户怀疑它是冻结了还是仍在处理他们的查询。问题在于我们的前端只有在代理完成整个思考过程后才会更新,而对于复杂查询,这个过程可能需要几秒钟甚至几分钟。

这次经历促使我探索如何将代理的推理过程实时流式传输到前端,从而为用户提供更具交互性和吸引力的体验。通过这种方式,我们可以让用户更好地理解代理正在做什么以及原因,这对于透明度和信任至关重要的应用尤为重要。

为了实现这一目标,我们可以利用 LangGraph 的 StateGraphadd_node 功能来构建一个表示代理推理过程的图。然后,我们可以使用 MCP 的 toolsresources 创建一个更新流,在代理完成思考过程时发送到前端。

以下是使用 Python 实现此功能的示例:

import langgraph as lg
from mcp import tools, resources

# Create a new StateGraph to represent the agent's reasoning process
graph = lg.StateGraph()

# Define a node that represents the agent's current thought process
def thought_process_node(graph, thought_process):
    node = graph.add_node(thought_process)
    # Add conditional edges to represent the possible next steps in the thought process
 graph.add_conditional_edges(node, [
        (thought_process + " -> considering option A", 0.7),
        (thought_process + " -> considering option B", 0.3)
    ])
    return node

# Create a stream of updates that can be sent to the frontend
def stream_reasoning(graph, initial_thought_process):
    current_node = thought_process_node(graph, initial_thought_process)
    while True:
        # Get the next node in the graph based on the current node and the agent's reasoning
        next_node = graph.get_next_node(current_node)
        # Send an update to the frontend with the current thought process and the next possible steps
        yield {
            "thought_process": next_node.value,
            "next_steps": [edge.value for edge in graph.get_outgoing_edges(next_node)]
        }
        # Update the current node
        current_node = next_node

# Create a checkpoint to save the agent's reasoning process
checkpoint = resources.Checkpoint("agent_reasoning")

# Start the agent's reasoning process and stream the updates to the frontend
initial_thought_process = "considering user query"
for update in stream_reasoning(graph, initial_thought_process):
    # Send the update to the frontend
    print(update)
    # Save the current state of the agent's reasoning process
    checkpoint.save(graph)

Enter fullscreen mode Exit fullscreen mode

这段代码创建了一个 StateGraph 来表示代理的推理过程,并定义了一个表示当前思考过程的节点。然后,它创建了一个更新流,在代理完成思考过程时发送到前端。stream_reasoning 函数在每一步生成一个更新,其中包括当前思考过程和下一个可能的步骤。

在实现此方法时需要注意的一个实际问题是,代理的推理过程可能具有高度分支性,导致可能的下一步数量呈指数级增长。为了缓解这个问题,我们可以使用束搜索或剪枝等技术来限制可能的下一步数量,并防止图变得过大。

随着我们继续探索代理式 AI 的可能性,我们将更深入地研究代理推理的复杂性,以及如何使用 LangGraph 和 MCP 构建更透明和交互式的系统。明天,我们将探讨如何集成多个代理和模型,以创建更强大和灵活的 AI 应用。