This runs tools in the graph It takes in an agent action and calls that tool and returns the result.
(state: State)
| 173 | |
| 174 | @action(reads=["messages"], writes=["messages"]) |
| 175 | def tool_node(state: State) -> tuple[dict, State]: |
| 176 | """This runs tools in the graph |
| 177 | |
| 178 | It takes in an agent action and calls that tool and returns the result.""" |
| 179 | messages = state["messages"] |
| 180 | # Based on the continue condition |
| 181 | # we know the last message involves a function call |
| 182 | last_message = messages[-1] |
| 183 | # We construct an ToolInvocation from the function_call |
| 184 | tool_input = json.loads(last_message.additional_kwargs["function_call"]["arguments"]) |
| 185 | # We can pass single-arg inputs by value |
| 186 | if len(tool_input) == 1 and "__arg1" in tool_input: |
| 187 | tool_input = next(iter(tool_input.values())) |
| 188 | tool_name = last_message.additional_kwargs["function_call"]["name"] |
| 189 | action = ToolInvocation( |
| 190 | tool=tool_name, |
| 191 | tool_input=tool_input, |
| 192 | ) |
| 193 | # We call the tool_executor and get back a response |
| 194 | response = tool_executor.invoke(action) |
| 195 | # We use the response to create a FunctionMessage |
| 196 | function_message = FunctionMessage( |
| 197 | content=f"{tool_name} response: {str(response)}", name=action.tool |
| 198 | ) |
| 199 | # We return a list, because this will get added to the existing list |
| 200 | return {"messages": [function_message]}, state.append(messages=function_message) |
| 201 | |
| 202 | |
| 203 | @action(reads=[], writes=[]) |