-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_tool_node.py
More file actions
28 lines (26 loc) · 996 Bytes
/
basic_tool_node.py
File metadata and controls
28 lines (26 loc) · 996 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import json
from typing import Any
from langchain_core.messages import ToolMessage
# Create a function to run the tools
class BasicToolNode():
"""A node that runs the tools requested in the last AIMessage."""
def __init__(self, tools: list) -> None:
self.tools_by_name = {tool.name: tool for tool in tools}
def __call__(self, state: Any) -> dict[str, Any]:
if messages := state.get("messages", []):
message = messages[-1]
else:
raise ValueError("No messages found in state")
outputs = []
for tool_call in message.tool_calls:
tool_result = self.tools_by_name[tool_call["name"]].invoke(
tool_call["args"]
)
outputs.append(
ToolMessage(
content=json.dumps(tool_result),
name=tool_call["name"],
tool_call_id=tool_call["id"],
)
)
return {"messages": outputs}