Replies: 1 comment
-
LangChain provides a BaseCallbackHandler interface, which you can extend to capture tool-related events, such as tool selection. from langchain.callbacks.base import BaseCallbackHandler class ToolSelectionCallback(BaseCallbackHandler):
Instantiate the callbacktool_selection_callback = ToolSelectionCallback()
Pass your custom callback handler to the AgentExecutor when creating the agent. from langchain.agents import AgentExecutor agent_executor = AgentExecutor(
The selected_tool attribute in your callback handler will contain the name of the most recently selected tool. response = agent_executor.invoke({"input": "I wanna book a hotel room"}) Access the tool name from the callbackprint(f"Tool identified immediately: {tool_selection_callback.selected_tool}")
If you need deeper control, you can override the agent’s _plan or _take_next_step methods. For example: from langchain.agents import Agent class CustomAgent(Agent): Key Notes This setup gives you access to the selected tool’s name as soon as the agent identifies it, before execution or argument collection. |
Beta Was this translation helpful? Give feedback.
-
Checked other resources
Commit to Help
Example Code
Description
I’ve implemented a tool-calling agent (see attached code) that processes multiple tools, each defined with a name, description, and arguments. Based on the input, the agent identifies the most suitable tool and prompts for the required arguments. Once all arguments are collected, the agent executes the tool. At that point, I can retrieve the tool’s name via intermediate_steps or the tool function.
However, I want to access the matched tool’s name immediately after it is identified, either before or during the argument collection process. From the attached code, it seems intermediate_steps only populates after the tool is invoked. Still, the agent clearly identifies the tool early on, as the argument-gathering prompts are specific to it. I’ve also explored using callbacks, but they haven’t provided the desired functionality.
Is there a way to retrieve the tool’s name as soon as it is identified, but before it is executed?
System Info
python:3.12
Beta Was this translation helpful? Give feedback.
All reactions