Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Last active September 16, 2025 11:27
Show Gist options
  • Save pamelafox/994af836f962fb860a490679ac84481b to your computer and use it in GitHub Desktop.
Save pamelafox/994af836f962fb860a490679ac84481b to your computer and use it in GitHub Desktop.
ToolCallLimitMiddleware
from langchain.agents.middleware import AgentMiddleware, AgentState, ModelRequest
class ToolCallLimitMiddleware(AgentMiddleware):
def __init__(self, limit) -> None:
super().__init__()
self.limit = limit
def modify_model_request(
self, request: ModelRequest, state: AgentState
) -> ModelRequest:
tool_call_count = sum(
1
for msg in state["messages"]
if isinstance(msg, AIMessage) and msg.tool_calls
)
if tool_call_count >= self.limit:
logger.info(
"Tool call limit of %d reached, disabling further tool calls.",
self.limit,
)
request.tools = []
request.messages.append(
HumanMessage(
content="No more tool calls can be made, now it's time to summarize your findings based off previous research."
)
)
return request
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment