Bird
Raised Fist0
Agentic AIml~20 mins

Rate limiting and budget controls in Agentic AI - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Rate limiting and budget controls
Problem:You have an AI agent that makes API calls to external services. The agent currently makes too many calls, exceeding the allowed rate limit and budget, causing service interruptions and extra costs.
Current Metrics:API calls per minute: 120 (limit is 60), Monthly cost: $300 (budget is $150), Number of failed calls due to rate limit: 30%
Issue:The agent is overusing API calls, causing rate limit errors and exceeding the budget.
Your Task
Implement rate limiting and budget controls to keep API calls under 60 per minute and monthly cost under $150, reducing failed calls to less than 5%.
You cannot reduce the agent's core functionality or accuracy.
You must keep the agent responsive and efficient.
Use only software-based controls (no hardware changes).
Hint 1
Hint 2
Hint 3
Hint 4
Solution
Agentic AI
import time
from collections import deque

class RateLimiter:
    def __init__(self, max_calls_per_minute):
        self.max_calls = max_calls_per_minute
        self.call_times = deque()

    def allow_call(self):
        current_time = time.time()
        while self.call_times and current_time - self.call_times[0] >= 60:
            self.call_times.popleft()
        if len(self.call_times) < self.max_calls:
            self.call_times.append(current_time)
            return True
        return False

class BudgetController:
    def __init__(self, max_budget):
        self.max_budget = max_budget
        self.current_cost = 0

    def can_spend(self, cost):
        return (self.current_cost + cost) <= self.max_budget

    def spend(self, cost):
        self.current_cost += cost

class Agent:
    def __init__(self, rate_limiter, budget_controller, cost_per_call=0.05):
        self.rate_limiter = rate_limiter
        self.budget_controller = budget_controller
        self.cost_per_call = cost_per_call

    def make_api_call(self):
        if not self.rate_limiter.allow_call():
            print("Rate limit exceeded, delaying call.")
            return False
        if not self.budget_controller.can_spend(self.cost_per_call):
            print("Budget exceeded, stopping calls.")
            return False
        # Simulate API call
        time.sleep(0.01)  # simulate network delay
        self.budget_controller.spend(self.cost_per_call)
        print("API call successful.")
        return True

# Setup
rate_limiter = RateLimiter(max_calls_per_minute=60)
budget_controller = BudgetController(max_budget=150)
agent = Agent(rate_limiter, budget_controller)

# Simulate calls
successful_calls = 0
failed_calls = 0
for _ in range(2000):
    if agent.make_api_call():
        successful_calls += 1
    else:
        failed_calls += 1
    time.sleep(1)  # simulate time between calls

print(f"Successful calls: {successful_calls}")
print(f"Failed calls: {failed_calls}")
print(f"Total cost: ${budget_controller.current_cost:.2f}")
Added a RateLimiter class to limit API calls to 60 per minute using a sliding window.
Added a BudgetController class to track and limit total spending to $150.
Modified the agent to check rate limits and budget before making calls.
Added delays and stopping conditions to prevent exceeding limits.
Results Interpretation

Before: 120 calls/min, $300 cost, 30% failed calls due to rate limit.

After: <=60 calls/min, <=$150 cost, <5% failed calls.

Implementing rate limiting and budget controls helps prevent overuse of resources, reduces errors, and keeps costs manageable without sacrificing core functionality.
Bonus Experiment
Try implementing a caching mechanism to store frequent API responses and reduce the number of calls needed.
💡 Hint
Use a dictionary with expiration times to store and reuse responses for repeated requests.

Practice

(1/5)
1. What is the main purpose of rate limiting in an AI system?
easy
A. To control how often users can make requests
B. To increase the speed of AI responses
C. To improve the accuracy of AI predictions
D. To store more user data for training

Solution

  1. Step 1: Understand rate limiting concept

    Rate limiting is about controlling the number of requests a user can make in a time period.
  2. Step 2: Identify the main purpose

    This control helps prevent overload and keeps the system fair for all users.
  3. Final Answer:

    To control how often users can make requests -> Option A
  4. Quick Check:

    Rate limiting = control request frequency [OK]
Hint: Rate limiting means limiting request frequency [OK]
Common Mistakes:
  • Confusing rate limiting with improving AI accuracy
  • Thinking rate limiting increases speed
  • Mixing rate limiting with data storage
2. Which of the following is the correct way to set a budget control in an AI usage system?
easy
A. budget = max(1000)
B. limit_budget = 'max 1000 dollars'
C. setBudget(1000 dollars)
D. budget_limit = 1000 # sets max money allowed

Solution

  1. Step 1: Identify correct syntax for budget control

    Setting a budget limit usually involves assigning a numeric value to a variable representing money allowed.
  2. Step 2: Check each option

    budget_limit = 1000 # sets max money allowed uses a clear assignment with a comment, which is correct syntax. Others use invalid syntax or unclear expressions.
  3. Final Answer:

    budget_limit = 1000 # sets max money allowed -> Option D
  4. Quick Check:

    Assign numeric budget limit = correct [OK]
Hint: Budget control is a numeric variable assignment [OK]
Common Mistakes:
  • Using strings instead of numbers for budget
  • Calling undefined functions like setBudget
  • Using incorrect syntax like max(1000)
3. Given this code snippet controlling requests per minute:
requests = [1,1,1,1,1,1]
limit = 5
allowed = sum(requests[:limit])
print(allowed)
What will be the printed output?
medium
A. 1
B. 6
C. 5
D. Error

Solution

  1. Step 1: Understand the code slicing and summing

    The code sums the first 5 elements of the list requests, each element is 1.
  2. Step 2: Calculate the sum of first 5 elements

    Sum = 1+1+1+1+1 = 5
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    Sum first 5 ones = 5 [OK]
Hint: Sum first 5 elements of ones list = 5 [OK]
Common Mistakes:
  • Summing all 6 elements instead of 5
  • Confusing slicing syntax
  • Expecting an error due to slicing
4. Find the error in this rate limiting code snippet:
max_requests = 10
requests_made = 0
if requests_made > max_requests:
    print("Limit reached")
else:
    requests_made += 1
    print("Request allowed")
medium
A. No error, code is correct
B. The condition should be >= instead of >
C. The print statements are reversed
D. requests_made should start at 1

Solution

  1. Step 1: Analyze the condition for rate limiting

    The code blocks requests if requests_made is greater than max_requests, but it should block when equal too.
  2. Step 2: Correct the condition

    Change > to >= to include the max_requests limit properly.
  3. Final Answer:

    The condition should be >= instead of > -> Option B
  4. Quick Check:

    Use >= to block at limit [OK]
Hint: Use >= to block requests at limit [OK]
Common Mistakes:
  • Using > misses blocking at exact limit
  • Starting requests_made at 1 is unnecessary
  • Swapping print messages confuses logic
5. You want to limit AI usage to 1000 requests per day and a budget of $500. Which approach correctly combines rate limiting and budget control?
hard
A. Set daily_limit = 1000 and budget_limit = 500; check both before allowing requests
B. Set daily_limit = 1000; budget_limit is not needed if rate limiting is set
C. Only set budget_limit = 500; rate limiting is handled automatically
D. Set budget_limit = 1000 and daily_limit = 500; swap values for safety

Solution

  1. Step 1: Understand the need for both controls

    Rate limiting controls request count; budget controls money spent. Both must be checked.
  2. Step 2: Evaluate options for combining controls

    Set daily_limit = 1000 and budget_limit = 500; check both before allowing requests correctly sets both limits and checks them before allowing requests. Others ignore one control or swap values incorrectly.
  3. Final Answer:

    Set daily_limit = 1000 and budget_limit = 500; check both before allowing requests -> Option A
  4. Quick Check:

    Use both limits together for control [OK]
Hint: Always check both request count and budget before allowing [OK]
Common Mistakes:
  • Ignoring budget when rate limiting is set
  • Assuming budget controls requests automatically
  • Swapping limit values causing confusion