Answer A: Anthropic Claude Sonnet 4.6
import threading import time class TokenBucketRateLimiter: def __init__(self, capacity, refill_rate): """ Initialize the Token Bucket Rate Limiter. :param capacity: Maximum number of tokens the bucket can hold. :param refill_rate: Number of tokens added to the bucket per second. """ self.capacity = capacity self.refill_rate = refill_rate self._tokens = capacity # Start with a full bucket self._last_refill_time = time.monotonic() self._lock = threading.Lock() def _refill(self): """ Refill the bucket based o...
Show Full Answer ▼
import threading import time class TokenBucketRateLimiter: def __init__(self, capacity, refill_rate): """ Initialize the Token Bucket Rate Limiter. :param capacity: Maximum number of tokens the bucket can hold. :param refill_rate: Number of tokens added to the bucket per second. """ self.capacity = capacity self.refill_rate = refill_rate self._tokens = capacity # Start with a full bucket self._last_refill_time = time.monotonic() self._lock = threading.Lock() def _refill(self): """ Refill the bucket based on the elapsed time since the last refill. This method must be called while holding the lock. """ now = time.monotonic() elapsed = now - self._last_refill_time tokens_to_add = elapsed * self.refill_rate self._tokens = min(self.capacity, self._tokens + tokens_to_add) self._last_refill_time = now def consume(self, tokens): """ Attempt to consume a given number of tokens from the bucket. :param tokens: Number of tokens to consume. :return: True if tokens were successfully consumed, False otherwise. """ if tokens <= 0: raise ValueError("Number of tokens to consume must be positive.") if tokens > self.capacity: # Can never be satisfied even with a full bucket return False with self._lock: self._refill() if self._tokens >= tokens: self._tokens -= tokens return True return False
Result
Winning Votes
3 / 3
Average Score
Total Score
Overall Comments
Answer A provides a highly correct and well-structured implementation of the Token Bucket Rate Limiter. Its code quality is excellent, featuring clear docstrings and adherence to Python conventions. It correctly implements thread safety and handles specified edge cases explicitly, making it a robust and maintainable solution.
View Score Details ▼
Correctness
Weight 35%The algorithm for refilling and consuming tokens is correctly implemented. The capacity limit is properly enforced, and the time-based refill logic is sound.
Completeness
Weight 20%The answer provides a complete class implementation with all specified methods (`__init__`, `consume`) and necessary imports.
Code Quality
Weight 20%The code is clean, readable, and follows standard Python conventions. It includes excellent docstrings for public methods and a clear comment for the private refill method, significantly enhancing maintainability.
Practical Value
Weight 15%The implementation correctly uses `threading.Lock` to ensure thread safety, making it suitable for concurrent environments. It is a practically sound solution.
Instruction Following
Weight 10%The solution explicitly handles all edge cases mentioned in the prompt's 'Robustness and Edge Cases' section: raising `ValueError` for non-positive `tokens` and returning `False` immediately if `tokens` exceeds `capacity`. The initial state is also correctly set.
Total Score
Overall Comments
Implements a correct token-bucket limiter with monotonic time, fractional refills, capacity capping, and proper locking around refill+consume. It also handles the important edge case of requests larger than capacity by returning False. Minor drawback: it raises on tokens<=0 (policy-dependent; some might prefer treating 0 as a no-op True) and it does not validate capacity/refill_rate inputs.
View Score Details ▼
Correctness
Weight 35%Correct token-bucket refill based on elapsed monotonic time, caps at capacity, and performs refill+consume atomically under a lock. Uses fractional tokens appropriately.
Completeness
Weight 20%Provides complete class with imports, internal refill helper, and consume method; includes explicit tokens>capacity handling. Missing validation for capacity/refill_rate values.
Code Quality
Weight 20%Readable, PEP8-ish, with docstrings explaining behavior and locking expectations. Straightforward structure.
Practical Value
Weight 15%Practical for typical use; immediate False for impossible large requests is helpful. Raising on tokens<=0 may be inconvenient in some integrations; no parameter validation for capacity/refill_rate.
Instruction Following
Weight 10%Meets requirements: thread-safe, no external state libs, correct methods and behavior, and includes necessary imports.
Total Score
Overall Comments
Answer A provides a correct, complete, and well-documented implementation of the token bucket rate limiter. It correctly implements the algorithm with proper thread safety using threading.Lock, handles edge cases like consuming more tokens than capacity (returns False) and consuming zero or negative tokens (raises ValueError). The code includes clear docstrings explaining each method's purpose and parameters. It uses time.monotonic() for reliable time tracking. The code is clean, readable, and follows Python conventions well.
View Score Details ▼
Correctness
Weight 35%Correctly implements the token bucket algorithm with proper refill calculation, capacity capping, and atomic consume operations. Handles the edge case of requesting more tokens than capacity by returning False early. Raises ValueError for non-positive token requests.
Completeness
Weight 20%Covers the required __init__, consume, and thread safety. Handles edge cases: zero/negative tokens (ValueError), tokens exceeding capacity (returns False). Starts with a full bucket. Includes all necessary imports.
Code Quality
Weight 20%Well-documented with clear docstrings for the class and each method. Parameter descriptions are provided. Code is clean, readable, and follows PEP 8 conventions. The private _refill method is clearly noted as requiring the lock to be held.
Practical Value
Weight 15%Ready to use in production scenarios. The early return for tokens exceeding capacity is a practical optimization. The ValueError for invalid input helps with debugging. Uses time.monotonic() for reliable timing.
Instruction Following
Weight 10%Follows all instructions: implements the class with the specified name, __init__ with capacity and refill_rate, consume method returning True/False, thread safety with threading.Lock, and includes necessary imports. Provides complete class implementation as requested.