Memory, cache and rate limiting
Three parts sit around every call, each behind an interface you can replace:
| Part | Interface | Built in | Builder default | AddIntentSharp default |
|---|---|---|---|---|
| The operation log | ISemanticMemory |
InMemorySemanticMemory |
in process, the last 10,000 calls | in process, the last 10,000 calls |
| The request cache | IRequestCache |
InMemoryRequestCache |
none | in process, 1,000 entries |
| The rate limiter | IRateLimiter |
TokenBucketRateLimiter |
none | none |
Each belongs to the client it is given to. The built-in three live in one process and keep nothing across a restart; a log or a cache that does is an implementation of your own, such as one over a database.
var client = new IntentClientBuilder()
.UseProviderOptions(store)
.WithMemory(new InMemorySemanticMemory(maxEntries: 50_000))
.WithCache(new InMemoryRequestCache(capacity: 5_000))
.WithRateLimiter(new TokenBucketRateLimiter(requestsPerSecond: 2, burst: 5))
.Configure(options => options.CacheTtl = TimeSpan.FromMinutes(30))
.Build();
WithMemory(null) turns the log off; WithCache(null) and WithRateLimiter(null) leave those out. The client does
not dispose any of the three.
The operation log records every call
After each call, passed or failed, the client records one entry: the intent, the first 2,000 characters of the
serialized input, the last reply (up to the 16 MB reply limit), the result type, the outcome and attempts, the
provider and model, the tokens, the time and the tags. Nothing is recorded for a call answered from the cache, for a
call with DoNotRecord (or an intent file's doNotRecord), or when RecordInMemory is false. A failure to record is
logged at Warning and never fails the call, and the library never reads the log back into a request.
// Ask the model every time, and keep this input out of the operation log.
var options = new AIRequestOptions { BypassCache = true, DoNotRecord = true };
var summary = await patientNote.AIAsync(client, "Summarize this note for the billing team.", options);
DoNotRecord does not keep a reply out of the request cache; set BypassCache as well.
InMemorySemanticMemory(maxEntries)keeps the most recentmaxEntries, 10,000 by default (0 means no limit).- A log that survives a restart is an
ISemanticMemoryof your own:RecordAsync,RecallAsync,GetStatsAsyncandClearAsync. It holds your inputs and replies, so protect what it writes as you protect that data.
GetStatsAsync() counts the entries, successes and tokens; RecallAsync(query, maxResults) returns the entries
whose intent is most like the query, most similar first, with a Score from 0 to 1; ClearAsync() removes every
entry.
if (client.Memory is { } log)
{
MemoryStats stats = await log.GetStatsAsync();
Console.WriteLine($"{stats.TotalEntries} calls, {stats.SuccessRate:P0} succeeded, {stats.TotalTokens} tokens");
foreach (var match in await log.RecallAsync("order urgency", maxResults: 3))
Console.WriteLine($"{match.Score:0.00} {match.Entry.Timestamp:u} {match.Entry.Intent} -> {match.Entry.Output}");
}
Recall compares words by default. To recall by meaning, give the log an embedding provider:
// Recall by meaning: each recorded call costs one embeddings call to the embedder, an IEmbeddingProvider
// (a provider of your own, or ChatClientEmbeddingProvider over a Microsoft.Extensions.AI embedding generator).
var client = new IntentClientBuilder()
.UseProviderOptions(store)
.WithMemory(new InMemorySemanticMemory(maxEntries: 10_000, embeddingProvider: embedder))
.Build();
Each recorded call then sends its intent text to that provider, and so does each recall query; these calls are not
counted in TotalModelCalls, rate-limited, cached or checked by a rule set. An embedding that fails does not fail the
call: that entry, or that query, is matched by its words.
The request cache reuses answers to identical requests
With a cache, an identical request to the same provider is answered from it while the entry lasts. A cached answer is checked against the current rules, and by the judge when it is on, and one that fails is withdrawn and replaced by a fresh reply.
FromCache is true when the answer came from the cache. The cached answer makes no model call: no tokens, no count
toward MaxModelCalls or TotalModelCalls, no wait on the rate limiter. A judge, when on, still makes its own model
call, which waits, counts and adds its tokens. A cached answer is not recorded in the log, and refusals, replies cut
off by the output limit and replies a rule set does not allow are never stored.
| Setting | Default | Effect |
|---|---|---|
InMemoryRequestCache(capacity) |
1,000 entries | The most entries the cache holds. |
IntentClientOptions.CacheTtl |
1 hour | How long an entry lasts. |
IntentClientOptions.UseCache |
true |
False stops this client using its cache. |
AIRequestOptions.BypassCache |
false |
True keeps one call out of the cache: no read, no write. |
if (client.Cache is { } cache)
{
CacheStats stats = cache.GetStats();
Console.WriteLine($"Cache: {stats.Hits} hits, {stats.Misses} misses, {stats.HitRate:P0}, {stats.Entries}/{stats.Capacity} entries");
}
if (client.RateLimiter is { } limiter)
{
RateLimitSnapshot bucket = limiter.GetSnapshot(client.PrimaryProvider.Name);
Console.WriteLine($"{bucket.Provider}: {bucket.AvailableTokens:0.0}/{bucket.Capacity} free, {bucket.Allowed} allowed, {bucket.Denied} refused");
}
To share a cache between processes, implement IRequestCache: GetAsync(key), SetAsync(key, response, ttl),
ClearAsync() and GetStats(). The key is an opaque string; store the AIResponse under it as it is. To withdraw an
answer that failed its checks, the client stores a refusal with no text under its key, which it reads back as a miss:
store it like any other response.
The rate limiter spaces out calls to each provider
TokenBucketRateLimiter(requestsPerSecond, burst) allows burst model calls at once (10 by default), then
requestsPerSecond (5 by default), per provider name, in this process only. A call waits up to 30 seconds for its
turn; past that it fails at once with AIRateLimitException and goes to the next provider of its role when there is
one, or ends with a Provider issue. A judge call takes its turn from its own provider's allowance and never falls
back; embedding calls do not wait. GetSnapshot(provider) reports the calls that may start now and the calls allowed
and refused so far.
With dependency injection
AddIntentSharp sets up the cache and the limiter from EnableRequestCache, CacheCapacity, RateLimitPerSecond
and RateLimitBurst (Configuration and DI), and uses an
ISemanticMemory you register, or else the in-process log:
services.AddSingleton(yourMemory); // a memory of your own; without one, the in-process memory
services.AddIntentSharp(settings =>
{
settings.CacheCapacity = 5_000; // the cache is on by default
settings.RateLimitPerSecond = 2; // 0, the default, means no limiter
settings.RateLimitBurst = 5;
settings.Options.CacheTtl = TimeSpan.FromMinutes(30);
});
An implementation you register is used in place of the built-in one while its setting is on: to use your
IRateLimiter, register it and set RateLimitPerSecond above 0. To turn the log off, set
IntentSharp:Options:RecordInMemory to false.