v9.1.1
Menu

Enforce Per-Tool Rate Limits Over a Call Stream

mediumPROTool Use & Function CallingAI AgentsAI Agents 1

Problem Statement

Each tool has a rate limit of limit calls per window seconds. Given a timestamped stream of tool calls, decide which are allowed and which are throttled using a sliding window.

Background

For each tool, a call at time t is allowed if fewer than limit allowed calls to that same tool occurred in the half-open interval (t - window, t]. Throttled calls do not count toward the limit (they never executed). Process calls in the given order.

Your Task

Implement:

def rate_limit(calls, limit, window):
  • calls: list of (tool, time) tuples, time non-decreasing.
  • Return a list of booleans, True if the call was allowed.

Input Format

  • calls (list of (str, int)), limit (int), window (int).

Output Format

  • A list of booleans.

Sample

print(rate_limit([("a",0),("a",1),("a",2)], 2, 5))

Output:

[True, True, False]

Example

Input
print(rate_limit([("a",0),("a",1),("a",2)], 2, 5))
Output
[True, True, False]
Reasoning
  • Call 1 ("a", 0): The sliding window interval is (0−5,0]=(−5,0](0 - 5, 0] = (-5, 0]. There are currently 0 allowed calls for tool "a" in this interval. Since 0<20 < 2 (the limit), the call is allowed. The history for "a" becomes [0][0].

  • Call 2 ("a", 1): The window is (1−5,1]=(−4,1](1 - 5, 1] = (-4, 1]. The previous allowed call at t=0t=0 falls within this interval. There is 1 allowed call in the window. Since 1<21 < 2, the call is allowed. The history for "a" becomes [0,1][0, 1].

  • Call 3 ("a", 2): The window is (2−5,2]=(−3,2](2 - 5, 2] = (-3, 2]. Both previous allowed calls (t=0t=0 and t=1t=1) fall within this interval. There are 2 allowed calls in the window. Since 2≮22 \not< 2 (the limit is reached), the call is throttled. The history remains [0,1][0, 1] because throttled calls do not count.

  • The final output is [True, True, False]

Constraints

  • Times are non-decreasing ints; window and limit are positive.
  • Only previously-allowed calls to the same tool count.
  • Window is half-open: keep calls with t_prev > t - window.

Learn this in

More from AI Agents 1

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.