Files
spring-ai/llm-gateway/src/main/java/com/ankurm/gateway/TokenLimiter.java
T

61 lines
2.0 KiB
Java

package com.ankurm.gateway;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.ToLongFunction;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.TimeMeter;
/**
* Tokens-per-hour per tenant (Bucket4j, in memory). The unit is LLM tokens, not requests, because
* one summarisation can cost fifty lookups. Pre-consume an estimate, then settle with the real
* total: refund the surplus, or charge the shortfall. The old post refunded against prompt tokens
* only and never charged the completion, so every answer was free of the limit.
*/
public final class TokenLimiter {
private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
private final ToLongFunction<String> perHour;
private final TimeMeter clock;
public TokenLimiter(ToLongFunction<String> perHour, TimeMeter clock) {
this.perHour = perHour;
this.clock = clock;
}
private Bucket bucket(String tenant) {
return buckets.computeIfAbsent(tenant, t -> {
long cap = perHour.applyAsLong(t);
return Bucket.builder().withCustomTimePrecision(clock)
.addLimit(Bandwidth.builder().capacity(cap).refillGreedy(cap, Duration.ofHours(1)).build())
.build();
});
}
public void take(String tenant, long estimate) {
if (!bucket(tenant).tryConsume(estimate)) {
throw new BudgetExceededException("Token rate limit reached for " + tenant);
}
}
/** Correct the estimate once the real token count is known. */
public void settle(String tenant, long estimate, long actual) {
Bucket b = bucket(tenant);
if (actual < estimate) {
b.addTokens(estimate - actual);
}
else if (actual > estimate) {
b.consumeIgnoringRateLimits(actual - estimate);
}
}
public long available(String tenant) {
return bucket(tenant).getAvailableTokens();
}
}