Agent keeps calling the same tool repeatedly
I have a strange issue with my Langchain agent setup. When I inquire about network details, it should only trigger my custom tool once and yield the response. However, it continuously invokes the same function, appearing to be stuck in a loop.
The tool executes correctly and provides the right information each time, yet the agent fails to recognize that it has obtained the information it requires. Has anyone else experienced this type of issue before?
Here’s my code:
from langchain_ollama import ChatOllama
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_core.tools import tool
from network_utils import fetch_user_ip
model = ChatOllama(
model="llama3.2",
temperature=0.2,
)
system_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"""You are a network assistant. Keep responses under 25 words.
When users ask for their IP, use the get_current_ip tool.
Sample interaction:
User: Show me my IP
Assistant: Your IP is 192.168.1.100""",
),
MessagesPlaceholder(variable_name="chat_history"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
("user", "{input}"),
]
)
session_store = {}
@tool
def get_current_ip():
"""Retrieves the current IPv4 address of the user."""
return fetch_user_ip()
available_tools = [get_current_ip]
network_agent = create_tool_calling_agent(model, available_tools, system_prompt)
executor = AgentExecutor(
agent=network_agent,
tools=available_tools,
verbose=True,
)
def retrieve_chat_history(session_id: str) -> BaseChatMessageHistory:
if session_id not in session_store:
session_store[session_id] = ChatMessageHistory()
return session_store[session_id]
def query_with_stream(user_query, session_id):
agent_with_history = RunnableWithMessageHistory(
executor,
retrieve_chat_history,
input_messages_key="input",
history_messages_key="chat_history",
)
return agent_with_history.stream({"input": user_query}, config={"configurable": {"session_id": session_id}})
def query_direct(user_query, session_id):
agent_with_history = RunnableWithMessageHistory(
executor,
retrieve_chat_history,
input_messages_key="input",
history_messages_key="chat_history",
)
return agent_with_history.invoke({"input": user_query}, config={"configurable": {"session_id": session_id}})
Debug output shows:
Starting new AgentExecutor chain…
Calling: get_current_ip with {}
Retrieving network address…
10.0.1.45
Calling: get_current_ip with {}
Retrieving network address…
10.0.1.45
Calling: get_current_ip with {}