我最近花了數小時除錯一個使用 LangGraph 和 MCP 建立的客服機器人,結果發現問題不在代理的推理本身,而在於我們如何將這些推理呈現給使用者。機器人常常只顯示載入中的 spinner,讓使用者懷疑它是否當機,或仍在處理查詢。問題在於我們的前端只有在代理完成整個思考流程後才更新,而複雜查詢可能需要數秒甚至數分鐘。
這段經驗促使我探討如何即時將代理的推理串流到前端,提供更互動且吸引人的使用者體驗。如此一來,我們就能讓使用者更清楚代理在做什麼以及為什麼這麼做,這對強調透明度與信任的應用程式來說格外重要。
為了達成這個目標,我們可以利用 LangGraph 的 StateGraph 與 add_node 功能,建構一個代表代理推理流程的圖形。接著使用 MCP 的 tools 與 resources 建立更新串流,在代理思考過程中即時傳送到前端。
以下是使用 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 函式會在每一步產生更新,包含目前的思考過程與下一步可能的選項。
實作此方法時需注意,代理的推理流程可能高度分支,導致可能的下一步數量呈指數成長。為了解決這個問題,我們可以使用 beam search 或 pruning 等技術,限制可能的下一步數量,避免圖形過大。
隨著我們持續探索代理式 AI 的可能性,我們將深入探討代理推理的複雜性,以及如何利用 LangGraph 和 MCP 建立更透明且互動的系統。明天,我們將探討如何整合多個代理與模型,以建立更強大且靈活的 AI 應用程式。
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.