This commit is contained in:
@@ -7,6 +7,7 @@ import asyncio
|
||||
from typing import Any, Dict
|
||||
from langchain_core.messages import AIMessage, ToolMessage
|
||||
from langgraph.runtime import Runtime
|
||||
from langgraph.config import get_stream_writer
|
||||
|
||||
# 本地模块
|
||||
from app.state import MessagesState, GraphContext
|
||||
@@ -25,13 +26,15 @@ def create_tool_call_node(tools_by_name: Dict[str, Any]):
|
||||
异步节点函数
|
||||
"""
|
||||
|
||||
async def call_tools(state: MessagesState, runtime: Runtime[GraphContext]) -> Dict[str, Any]:
|
||||
from langchain_core.runnables.config import RunnableConfig
|
||||
|
||||
async def call_tools(state: MessagesState, config: RunnableConfig) -> Dict[str, Any]:
|
||||
"""
|
||||
工具执行节点(异步方法)
|
||||
|
||||
Args:
|
||||
state: 当前对话状态
|
||||
runtime: LangGraph 运行时上下文
|
||||
config: 运行时配置
|
||||
|
||||
Returns:
|
||||
包含 ToolMessage 的状态更新
|
||||
@@ -62,6 +65,10 @@ def create_tool_call_node(tools_by_name: Dict[str, Any]):
|
||||
results.append(ToolMessage(content=err_msg, tool_call_id=tool_id))
|
||||
continue
|
||||
|
||||
# 获取流式写入器并发送工具调用开始事件
|
||||
writer = get_stream_writer()
|
||||
writer({"type": "custom", "data": {"type": "tool_start", "tool": tool_name}})
|
||||
|
||||
try:
|
||||
# 修复闭包问题:将变量作为默认参数传入 lambda
|
||||
# 如果工具支持异步 (ainvoke),优先使用异步调用
|
||||
@@ -77,9 +84,15 @@ def create_tool_call_node(tools_by_name: Dict[str, Any]):
|
||||
result_preview = str(observation).replace("\n", " ")
|
||||
debug(f" └─ ✅ 结果: {result_preview}")
|
||||
results.append(ToolMessage(content=str(observation), tool_call_id=tool_id))
|
||||
|
||||
# 发送工具调用完成事件
|
||||
writer({"type": "custom", "data": {"type": "tool_end", "tool": tool_name, "success": True}})
|
||||
except Exception as e:
|
||||
debug(f" └─ ❌ 异常: {e}")
|
||||
results.append(ToolMessage(content=f"Error: {e}", tool_call_id=tool_id))
|
||||
|
||||
# 发送工具调用失败事件
|
||||
writer({"type": "custom", "data": {"type": "tool_end", "tool": tool_name, "success": False, "error": str(e)}})
|
||||
|
||||
info(f"🛠️ [工具调用] 执行完成,返回 {len(results)} 条 ToolMessage")
|
||||
|
||||
@@ -87,4 +100,4 @@ def create_tool_call_node(tools_by_name: Dict[str, Any]):
|
||||
log_state_change("tool_node", {**state, **result}, "离开")
|
||||
return result
|
||||
|
||||
return call_tools
|
||||
return call_tools
|
||||
Reference in New Issue
Block a user