Add llm-gateway module: routing, failover below the tool-calling advisor, per-provider circuit breakers, dollar caps and token limits, tenant-keyed cache; real OpenAI and Anthropic models against a local fake

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXVi2GMQ7bR5EmbUFdDj7N
This commit is contained in:
Claude
2026-10-09 10:24:57 +00:00
parent 80cd21f89b
commit cdee85d3f4
51 changed files with 2404 additions and 0 deletions
@@ -0,0 +1,60 @@
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();
}
}