Why does agent invoke the tool multiple times? #24228
Replies: 4 comments 2 replies
-
The agent invokes the tool multiple times because agents are designed to decide how many times to use tools based on the input. This flexibility allows the agent to handle complex tasks that may require multiple tool invocations. To ensure the tool is invoked only once, you should use a chain instead of an agent. Chains are suitable when you know the specific sequence of tool usage needed for any user input. Here is an example of how to create a chain that ensures the tool is invoked only once: from operator import itemgetter
chain = llm_with_tools | (lambda x: x.tool_calls[0]["args"]) | multiply
chain.invoke("What's three times 12") This setup ensures that the tool is invoked exactly once by extracting the arguments of the first tool call and passing them to the tool. Additionally, if you are using the LangChain framework, you can create an agent that uses self-ask with search prompting, which expects exactly one tool. Here is an example of how to create such an agent: from langchain import hub
from langchain_community.chat_models import ChatAnthropic
from langchain.agents import (
AgentExecutor, create_self_ask_with_search_agent
)
prompt = hub.pull("hwchase17/self-ask-with-search")
model = ChatAnthropic(model="claude-3-haiku-20240307")
tools = [...] # Should just be one tool with name `Intermediate Answer`
agent = create_self_ask_with_search_agent(model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
agent_executor.invoke({"input": "hi"}) This setup ensures that the agent uses exactly one tool named |
Beta Was this translation helpful? Give feedback.
-
related #25546 |
Beta Was this translation helpful? Give feedback.
-
Hi @dosu |
Beta Was this translation helpful? Give feedback.
-
I highly recommend that you write your tool schema and append it into the prompt that you want to submit to the LLM. Then, let it just decides which tool it wants to invoke and what params for the tools. The advantage is that it is now a transparent process and you can fully take control. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Checked other resources
Commit to Help
Example Code
Description
I have defined a variable named 'count'
Once the tool named 'multiply' be invoked, variable 'count' will increase then print the current value
I created an agent with this tool named 'agent_executor'
When above code was executed, I found the tool was invoked multiple times
This is the printout I got
My questions:
Why does agent invoke the tool multiple times? And how to invoke only once?
System Info
System Information
Package Information
Packages not installed (Not Necessarily a Problem)
The following packages were not found:
Beta Was this translation helpful? Give feedback.
All reactions