Bundle: redb-route / redb.Route.Llm (redb.Route.Llm.txt), 94 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Llm/Embeddings/EmbedComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Embeddings/EmbedComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Embeddings; /// /// Embedding transport. Scheme: embed. Producer-only, symmetric with /// llm://: To("embed://<connectionFactoryName>") turns the /// exchange body (a text, or a collection of texts) into an embedding vector /// (float[]) or vectors (float[][]) written to Out.Body. /// /// The URI host names an (Provider / BaseUrl / /// ApiKey / ModelId — set ModelId to the embedding model), so different /// routes can pick different embedding models by name — the same lever as /// llm://<factory>. /// /// /// /// From("kafka://texts").To("embed://openai").To("vector://sink"); /// /// /// [EndpointRole(EndpointRole.Producer, Hint = "Use To(\"embed://\").")] public sealed class EmbedComponent : ComponentBase { /// public override string Scheme => "embed"; /// /// Builds the from a resolved connection /// factory. Defaults to ; override /// for a custom provider or in tests. /// public Func ProviderFactory { get; set; } = OpenAiEmbeddingProvider.Create; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new EmbedEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new EmbedEndpoint(uri, this, options); } } /// Options for an embed:// endpoint. public sealed class EmbedEndpointOptions : EndpointOptions { /// Alternative to the URI host for the connection-factory name. [RegistryReference(typeof(LlmConnectionFactory))] public string? ConnectionFactory { get; set; } /// public override void Validate() { } } /// Embedding endpoint. URI path = connection-factory name. public sealed class EmbedEndpoint : EndpointBase { /// Connection-factory name (URI path or ?connectionFactory=). public string FactoryName { get; } /// Factory resolved from the route context (null when wired later). internal LlmConnectionFactory? ResolvedFactory { get; } /// Creates the endpoint. public EmbedEndpoint(EndpointUri uri, EmbedComponent component, EmbedEndpointOptions options) : base(uri, component, options) { FactoryName = !string.IsNullOrWhiteSpace(uri.Path) ? uri.Path : (options.ConnectionFactory ?? string.Empty); if (string.IsNullOrWhiteSpace(FactoryName)) throw new InvalidOperationException( "embed:// requires a connection factory — use 'embed://' or '?connectionFactory='."); if (component.Context is not null) ResolvedFactory = component.Context.GetFromRegistry(FactoryName); } /// public override IProducer CreateProducer() => new EmbedProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException("embed:// is producer-only. Use To(\"embed://\")."); } Path: redb-route/redb.Route.Llm/Embeddings/EmbedProducer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Embeddings/EmbedProducer.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Embeddings; /// /// Embedding producer: embeds the exchange body and writes the vector(s) to /// Out.Body. A single text → float[]; a collection of texts → /// float[][] (order preserved). /// public sealed class EmbedProducer : ConnectableProducer { private readonly EmbedEndpoint _endpoint; private readonly EmbedEndpointOptions _options; private IEmbeddingProvider? _provider; /// Creates the producer. public EmbedProducer(EmbedEndpoint endpoint, EmbedEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"embed:{_endpoint.FactoryName}"; /// protected override Task ConnectAsync(CancellationToken ct) => Task.CompletedTask; /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(exchange); var provider = ResolveProvider(); var body = exchange.In.Body; exchange.Out ??= exchange.In.Clone(); if (body is IEnumerable texts) // a string is IEnumerable, not , so single texts fall through { var list = texts.ToList(); var vectors = await provider.EmbedAsync(list, ct).ConfigureAwait(false); exchange.Out.Body = vectors is float[][] arr ? arr : vectors.ToArray(); exchange.Out.Headers["llm.embedding.count"] = vectors.Count; exchange.Out.Headers["llm.embedding.dims"] = vectors.Count > 0 ? vectors[0].Length : 0; } else { var text = body?.ToString() ?? string.Empty; var vector = await provider.EmbedOneAsync(text, ct).ConfigureAwait(false); exchange.Out.Body = vector; exchange.Out.Headers["llm.embedding.dims"] = vector.Length; } exchange.Out.Headers["llm.embedding.model"] = provider.ModelId; exchange.Out.Headers["llm.embedding.provider"] = provider.ProviderId; } private IEmbeddingProvider ResolveProvider() { if (_provider is not null) return _provider; var component = (EmbedComponent)_endpoint.Component; var factory = _endpoint.ResolvedFactory ?? component.Context?.GetFromRegistry(_endpoint.FactoryName) ?? throw new InvalidOperationException( $"embed://: connection factory '{_endpoint.FactoryName}' is not registered in the route context."); _provider = component.ProviderFactory(factory); return _provider; } } Path: redb-route/redb.Route.Llm/Engine/AgentBudgetFactory.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/AgentBudgetFactory.cs ---- using redb.Route.Llm.Engine.Governance; namespace redb.Route.Llm.Engine; /// /// Translates the nullable budget options of an endpoint / builder into an . /// /// The nulls matter: null means "this dimension is not limited", while /// spells that as <= 0. Collapsing an unset option to zero would be harmless here (zero is /// the same as unset for the enforcer) — but doing it in the URI would not, so the options are /// appended only when set. /// /// internal static class AgentBudgetFactory { /// Builds the per-run budget; all-null maps to . public static AgentBudget From(int? inputTokens, int? outputTokens, decimal? costUsd) => inputTokens is null && outputTokens is null && costUsd is null ? AgentBudget.Unbounded : new AgentBudget(inputTokens ?? 0, outputTokens ?? 0, costUsd ?? 0m); } Path: redb-route/redb.Route.Llm/Engine/AgentEngine.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/AgentEngine.cs ---- using System.Diagnostics; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Expressions; using redb.Route.Llm.Providers; using redb.Route.Llm.Telemetry; using redb.Route.Llm.Tools; namespace redb.Route.Llm.Engine; /// /// Default implementation. Drives the tool-loop with /// governance, idempotency, approval, conversation persistence and audit /// observability — every dependency is optional and defaults to a Noop /// implementation so that simple cases (a tool-less, persistence-less call /// against ) work out of the box. /// public sealed class AgentEngine : IAgentEngine { private static readonly JsonSerializerOptions JsonOptions = new() { // UTF-8, not \uXXXX — keep non-ASCII readable and token-cheap on the wire. Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private readonly ILogger? _logger; private readonly IProducerTemplate? _producerTemplate; private readonly IAgentObserver _observer; private readonly IBudgetEnforcer _budget; private readonly IApprovalGate _approval; private readonly IRedactionFilter _redaction; private readonly IShadowRunner _shadow; private readonly IConversationStore? _conversation; private readonly IToolIdempotencyStore? _idempotency; private readonly IApprovalStore? _approvalStore; private readonly IToolClaimsSource? _claimsSource; private readonly IToolCacheStore? _toolCache; private readonly ICostCalculator _costCalculator; // The route and connection factory pairs already warned about in-memory stores inside a transaction: the // warning is said once per step for the life of the engine, not on every exchange. private readonly System.Collections.Concurrent.ConcurrentDictionary _inMemoryInTransactionWarned = new(); /// /// Backwards-compatible constructor — wires every dependency to its no-op /// implementation. Use the DI-driven constructor for production wiring. /// public AgentEngine(ILogger? logger = null) : this(logger, producerTemplate: null, observer: null, budget: null, approval: null, redaction: null, shadow: null, conversation: null, idempotency: null, approvalStore: null) { } /// Creates an engine with explicit governance / storage dependencies. /// Optional logger for governance decisions and tool failures. /// Producer used to dispatch tool calls onto their endpoints. /// Observability sink; defaults to . /// Budget enforcer; defaults to (no ceiling). /// Approval gate; defaults to . /// Redaction filter; defaults to . /// Shadow runner; defaults to . /// Conversation store; absent means the run is not persisted. /// Idempotency store, consulted for tools with a declared side effect. /// Audit sink for approval decisions; absent means none are recorded. /// /// Optional claims source. When absent, a tool that declares /// is denied — fail closed by design. /// /// /// Optional cross-run tool cache. Consulted only for ToolCachingPolicy.Persist; /// Memoize is served by a run-scoped in-process cache. When absent, persisted caching /// degrades to "not cached" rather than failing. /// /// /// Prices provider responses for cost budgets; defaults to , which /// makes a run that requests a cost ceiling fail fast instead of enforcing a zero ceiling. /// public AgentEngine( ILogger? logger, IProducerTemplate? producerTemplate, IAgentObserver? observer, IBudgetEnforcer? budget, IApprovalGate? approval, IRedactionFilter? redaction, IShadowRunner? shadow, IConversationStore? conversation, IToolIdempotencyStore? idempotency, IApprovalStore? approvalStore, IToolClaimsSource? claimsSource = null, IToolCacheStore? toolCache = null, ICostCalculator? costCalculator = null) { _logger = logger; _producerTemplate = producerTemplate; _observer = observer ?? new NoopAgentObserver(); _budget = budget ?? new NoopBudgetEnforcer(); _approval = approval ?? new AutoApproveGate(); _redaction = redaction ?? new NoopRedactionFilter(); _shadow = shadow ?? new NoopShadowRunner(); _conversation = conversation; _idempotency = idempotency; _approvalStore = approvalStore; _claimsSource = claimsSource; _toolCache = toolCache; _costCalculator = costCalculator ?? new NullCostCalculator(); } /// /// Builds an engine from whatever the route context and its DI container can provide — the /// production composition path. Every seam is optional here (an absent store means "not configured", /// not "broken"), so a host only has to call AddRedbRouteLlm(), and the engine it resolves /// carries the governance the package registered. /// /// Constructing an engine by hand is still possible, but then every seam is the caller's to wire — /// including the ones added since: use this factory (or DI) unless you intend to replace them all. /// /// /// Route context whose locator and DI provider are searched for the dependencies. public static AgentEngine FromContext(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); return new AgentEngine( logger: Resolve>(context) ?? Resolve(context)?.CreateLogger(), producerTemplate: Resolve(context), // Absent collaborators fall back to the same no-ops AddRedbRouteLlm() registers, so a // bare context (a demo, a hand-rolled host) gets a working engine instead of null references. observer: Resolve(context) ?? new NoopAgentObserver(), budget: Resolve(context) ?? new NoopBudgetEnforcer(), approval: Resolve(context) ?? new AutoApproveGate(), redaction: Resolve(context) ?? new NoopRedactionFilter(), shadow: Resolve(context) ?? new NoopShadowRunner(), conversation: Resolve(context), idempotency: Resolve(context), approvalStore: Resolve(context), claimsSource: Resolve(context), toolCache: Resolve(context), costCalculator: Resolve(context)); } /// /// Finds the engine a host registered — first in the route context's own locator, then in the DI /// container — or null when the host registered none. Producers, consumers and the inline step /// must all use this: deliberately looks only at the locator, /// so asking it alone misses the engine AddRedbRouteLlm() registered in the container. /// public static IAgentEngine? FindRegistered(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); return context.GetService() ?? context.GetServiceProvider()?.GetService(typeof(IAgentEngine)) as IAgentEngine; } /// /// The context's own locator wins (a host may explicitly override a seam there), then the DI /// provider. deliberately looks only at the locator, so /// asking one place would miss everything a container registered. /// /// /// Inside an ambient transaction (a route's .Transacted()) the in-memory conversation and tool /// idempotency stores this package ships do not take part in it: after a rollback the transcript still holds the /// rolled-back run's tool calls and results, and a tool call id seen before is answered from memory, so a /// redelivered message may not call the tool again. The run goes on; one warning per route and connection /// factory says so. Only the stores the run uses count (the conversation store with a conversation, the /// idempotency store with tools), and a host's own store implementations are not judged. /// private void WarnInMemoryStoresInTransaction(AgentRequest request) { if (_logger is null || System.Transactions.Transaction.Current is null) return; var stores = new List(2); if (_conversation is InMemoryConversationStore && request.ConversationId is not null) stores.Add(nameof(InMemoryConversationStore)); if (_idempotency is InMemoryToolIdempotencyStore && request.Tools.Count > 0) stores.Add(nameof(InMemoryToolIdempotencyStore)); if (stores.Count == 0) return; var route = request.Exchange.RouteId ?? "(no route)"; if (!_inMemoryInTransactionWarned.TryAdd($"{route}\n{request.Factory.Name}", 0)) return; _logger.LogWarning( "The llm:{Factory} step of route '{Route}' runs inside an ambient transaction, but {Stores} keep state in memory " + "and do not take part in the transaction. If it rolls back, the conversation keeps the rolled-back run's tool " + "calls and their results, and a tool call id seen before is answered from memory, so a redelivered message " + "may not call the tool again. Register the redb stores with AddRedbLlmStorage(), or move the llm: step out " + "of .Transacted(). Said once per route and connection factory.", request.Factory.Name, route, string.Join(" and ", stores)); } private static T? Resolve(IRouteContext context) where T : class => context.GetService() ?? context.GetServiceProvider()?.GetService(typeof(T)) as T; /// public async Task RunAsync(AgentRequest request, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); // A cost ceiling that cannot be priced must fail loudly and before the first provider call: // the alternative is a run that reports "budget enforced" while pricing every call as zero. if (request.Budget.MaxCostUsd > 0m && _costCalculator.Estimate(LlmUsage.Empty, request.Factory) is null) { throw new InvalidOperationException( $"This run requests a cost budget of {request.Budget.MaxCostUsd:F4} USD, but the registered " + $"ICostCalculator cannot price model '{request.Factory.ModelId}'. Register a calculator that " + "knows the model's rates, or drop the cost ceiling."); } WarnInMemoryStoresInTransaction(request); var provider = request.Factory.Build(); var capabilities = ProjectCapabilities(request.Tools); var toolSetHash = ComputeToolSetHash(capabilities); var effectiveTemperature = request.Temperature ?? request.Factory.Temperature; var effectiveMaxTokens = request.MaxTokens ?? request.Factory.MaxTokens; var effectiveTopP = request.Factory.TopP; var runCtx = new AgentRunContext { ConversationId = request.ConversationId, FactoryName = request.Factory.Name, ProviderId = request.Factory.Provider, ModelId = request.Factory.ModelId ?? string.Empty, ExchangeId = request.Exchange.ExchangeId, RedbName = request.Exchange.Properties.TryGetValue(LlmKeys.RedbName, out var redbName) && redbName is string { Length: > 0 } chosen ? chosen : null }; await _observer.OnRunStartedAsync(runCtx, ct).ConfigureAwait(false); var retryCount = ReadRetryCount(request.Exchange); // One memo per run, dropped when this method returns: "memoised for the lifetime of the agent // run" is exactly what ToolCachingPolicy.Memoize promises, and nothing may outlive it. var runCache = new AgentRunToolCache(); // The preamble opens the transcript and stays out of the store: it is part of how the // assistant is assembled, not something said in this dialog (see AgentRequest.Preamble). var transcript = new List(request.Preamble); string? attachUnderId = request.ConversationParentMessageId; if (_conversation is not null && request.ConversationId is { } convIdToLoad) { var path = await _conversation.LoadPathAsync( convIdToLoad, request.ConversationParentMessageId, request.Exchange, ct).ConfigureAwait(false); foreach (var node in path) transcript.Add(node.Message); if (path.Count > 0) attachUnderId = path[^1].Id; // Orphan tool_use recovery: if the loaded transcript ends with an // assistant message that has unmatched tool_use blocks (e.g. a prior // run was cancelled / timed out between persisting the assistant // turn and dispatching tools), synthesize error tool_result blocks // so the next provider call doesn't 400 on "tool_use without matching // tool_result". Without this, the conversation poisons itself // permanently for InMemory and any persistent store alike. if (transcript.Count > 0 && transcript[^1].Role == "assistant") { var orphanResults = new List(); foreach (var block in transcript[^1].Content) { if (block is LlmToolUseBlock orphan) orphanResults.Add(new LlmToolResultBlock( orphan.ToolUseId, "{\"error\":\"orphaned_tool_use_recovered\"}", IsError: true)); } if (orphanResults.Count > 0) { var recovery = new LlmMessage { Role = "user", Content = orphanResults }; transcript.Add(recovery); attachUnderId = await PersistMessageAsync( request, attachUnderId, recovery, iteration: 0, stopReason: null, usage: LlmUsage.Empty, toolUseId: null, temperature: null, maxTokens: null, topP: null, toolSetHash: null, providerSystemFingerprint: null, providerResponseId: null, latencyMs: null, retryCount: retryCount, ct).ConfigureAwait(false); _logger?.LogWarning( "Recovered {Count} orphaned tool_use block(s) in conversation {Conv} on load.", orphanResults.Count, convIdToLoad); } } } transcript.Add(new LlmMessage { Role = "user", Content = request.UserContent }); PublishConversationContext(request, transcript, iterations: 0, totalUsage: AgentUsage.Zero); var parentMessageId = await PersistMessageAsync( request, parentId: attachUnderId, message: transcript[^1], iteration: 0, stopReason: null, usage: LlmUsage.Empty, toolUseId: null, temperature: null, maxTokens: null, topP: null, toolSetHash: null, providerSystemFingerprint: null, providerResponseId: null, latencyMs: null, retryCount: retryCount, ct).ConfigureAwait(false); var iter = 0; var totalUsage = AgentUsage.Zero; // Cache counters ride alongside AgentUsage rather than inside it. AgentUsage is the // BUDGET currency — what the run is allowed to spend — and cache reads/writes are not // billable input; folding them in would make every budget silently wrong. But dropping // them was worse: the run's own answer to "is the prompt cache working?" is these two // numbers, and until now RunAsync summed them per iteration and then threw them away. var cacheWrite = 0; var cacheRead = 0; LlmResponse? last = null; Exception? terminalException = null; var cancelled = false; try { while (true) { ct.ThrowIfCancellationRequested(); if (iter >= request.MaxIterations) { _logger?.LogWarning("Agent reached MaxIterations={Max}; stopping.", request.MaxIterations); break; } var pre = await OutsideTransactionAsync( () => _budget.PreCheckAsync(request.ConversationId, request.Budget, totalUsage, request.Exchange, ct)).ConfigureAwait(false); if (!pre.Continue) { _logger?.LogInformation("Budget pre-check stopped run: {Reason}", pre.Reason); break; } iter++; var llmRequest = new LlmRequest { ModelId = request.Factory.ModelId, SystemPrompt = request.SystemPrompt, // Every iteration of the tool loop resends the same system prompt, so the // flag rides along — the second turn onward is where the cache pays off. CacheSystemPrompt = request.CacheSystemPrompt, Messages = transcript, Tools = capabilities, Temperature = effectiveTemperature, MaxTokens = effectiveMaxTokens, TopP = effectiveTopP }; var providerTag = new KeyValuePair("llm.provider", request.Factory.Provider); var modelTag = new KeyValuePair("llm.model.id", request.Factory.ModelId); var factoryTag = new KeyValuePair("llm.factory", request.Factory.Name); var sw = Stopwatch.StartNew(); try { last = request.StreamModelCalls ? await CallStreamingAsync(provider, llmRequest, runCtx, iter, request.OnDelta, ct).ConfigureAwait(false) : await provider.CompleteAsync(llmRequest, ct).ConfigureAwait(false); LlmMetrics.Calls.Add(1, providerTag, modelTag, factoryTag); } catch { LlmMetrics.CallsFailed.Add(1, providerTag, modelTag, factoryTag); throw; } finally { LlmMetrics.CallDuration.Record(sw.Elapsed.TotalMilliseconds, providerTag, modelTag, factoryTag); } if (last.Usage.InputTokens > 0) LlmMetrics.TokensIn.Add(last.Usage.InputTokens, providerTag, modelTag, factoryTag); if (last.Usage.OutputTokens > 0) LlmMetrics.TokensOut.Add(last.Usage.OutputTokens, providerTag, modelTag, factoryTag); // Cost is what the deployment can price, not a placeholder zero: a cost ceiling must // not silently collapse into a tokens-only budget. var iterUsage = new AgentUsage( last.Usage.InputTokens, last.Usage.OutputTokens, _costCalculator.Estimate(last.Usage, request.Factory) ?? 0m); totalUsage = totalUsage.Add(iterUsage); cacheWrite += last.Usage.CacheCreationInputTokens; cacheRead += last.Usage.CacheReadInputTokens; await _observer.OnIterationCompletedAsync(new AgentIterationContext { Run = runCtx, Iteration = iter, StopReason = last.StopReason, IterationUsage = last.Usage, Duration = sw.Elapsed }, ct).ConfigureAwait(false); if (_shadow.Enabled) _ = SafeRunShadowAsync(provider, llmRequest, last, ct); transcript.Add(new LlmMessage { Role = "assistant", Content = last.Content }); parentMessageId = await PersistMessageAsync( request, parentMessageId, transcript[^1], iteration: iter, stopReason: last.StopReason, usage: last.Usage, toolUseId: null, temperature: effectiveTemperature, maxTokens: effectiveMaxTokens, topP: effectiveTopP, toolSetHash: toolSetHash, providerSystemFingerprint: last.ProviderSystemFingerprint, providerResponseId: last.ProviderResponseId, latencyMs: (long)sw.Elapsed.TotalMilliseconds, retryCount: retryCount, ct).ConfigureAwait(false); PublishConversationContext(request, transcript, iter, totalUsage); var post = await OutsideTransactionAsync(() => _budget.RecordAndCheckAsync( request.ConversationId, request.Budget, iterUsage, totalUsage, request.Exchange, ct)).ConfigureAwait(false); if (!post.Continue) { _logger?.LogInformation("Budget post-check stopped run: {Reason}", post.Reason); break; } if (last.StopReason != LlmStopReason.ToolUse) break; var toolResults = new List(last.Content.Count); foreach (var block in last.Content) { if (block is not LlmToolUseBlock use) continue; var resultBlock = await DispatchToolAsync(request, runCtx, runCache, use, parentMessageId, ct).ConfigureAwait(false); toolResults.Add(resultBlock); } transcript.Add(new LlmMessage { Role = "user", Content = toolResults }); parentMessageId = await PersistMessageAsync( request, parentMessageId, transcript[^1], iteration: iter, stopReason: null, usage: LlmUsage.Empty, toolUseId: null, temperature: null, maxTokens: null, topP: null, toolSetHash: null, providerSystemFingerprint: null, providerResponseId: null, latencyMs: null, retryCount: retryCount, ct).ConfigureAwait(false); } } catch (OperationCanceledException) { cancelled = true; throw; } catch (Exception ex) { terminalException = ex; throw; } finally { await _observer.OnRunCompletedAsync(new AgentRunCompletedContext { Run = runCtx, Iterations = iter, TotalUsage = new LlmUsage( totalUsage.InputTokens, totalUsage.OutputTokens, cacheWrite, cacheRead), StopReason = last?.StopReason ?? LlmStopReason.Other, Exception = terminalException, Cancelled = cancelled }, CancellationToken.None).ConfigureAwait(false); } // Return the last ASSISTANT content, not transcript[^1]: when the loop stops mid-round (MaxIterations // or budget) the tail is a tool-results user message with no text, which would surface as an empty // answer. The last assistant message carries the model's actual output. // ...and never the preamble's assistant turn: a run that stopped before its first call // (budget pre-check, MaxIterations=0) has no answer, and the fixed opening line must not // be handed back as if the model had just said it. LlmMessage? lastAssistant = null; for (var i = transcript.Count - 1; i >= request.Preamble.Count; i--) if (transcript[i].Role == "assistant") { lastAssistant = transcript[i]; break; } return new AgentResponse { Content = (lastAssistant ?? transcript[^1]).Content, Usage = new LlmUsage( totalUsage.InputTokens, totalUsage.OutputTokens, cacheWrite, cacheRead), Iterations = iter, StopReason = last?.StopReason ?? LlmStopReason.Other }; } /// /// One model call made as a stream (). The pieces go to the observer as /// they arrive; the loop goes on with the whole answer the stream assembled, the same answer a plain call returns, /// so nothing after the call differs from a run without streaming. /// private async Task CallStreamingAsync( ILlmProvider provider, LlmRequest llmRequest, AgentRunContext runCtx, int iteration, Func? onDelta, CancellationToken ct) { LlmResponse? answer = null; await foreach (var chunk in provider.StreamAsync(llmRequest, ct).WithCancellation(ct).ConfigureAwait(false)) { foreach (var piece in chunk.Content) { var (kind, text) = piece switch { LlmTextBlock t => (AgentDeltaKind.Text, t.Text), LlmThinkingBlock th => (AgentDeltaKind.Thinking, th.Text), // Completed tool calls ride on the last chunk; they are part of the answer, not a piece of text. _ => (default(AgentDeltaKind), (string?)null) }; if (string.IsNullOrEmpty(text)) continue; var delta = new AgentDeltaContext { Run = runCtx, Iteration = iteration, Kind = kind, Text = text }; await _observer.OnDeltaAsync(delta, ct).ConfigureAwait(false); if (onDelta is not null) await onDelta(delta, ct).ConfigureAwait(false); } if (chunk.Response is not null) answer = chunk.Response; } return answer ?? throw new InvalidOperationException( $"Provider '{provider.ProviderId}' ended its stream without the assembled answer (LlmStreamChunk.Response). " + "A provider that overrides StreamAsync must put the whole answer on its last chunk; one that does not " + "stream can leave StreamAsync to the interface's default, which does."); } private async Task DispatchToolAsync( AgentRequest request, AgentRunContext runCtx, AgentRunToolCache runCache, LlmToolUseBlock use, string? messageId, CancellationToken ct) { request.Exchange.setProperty(LlmExpressionKeys.Tool, new LlmToolContext { Name = use.Name, ToolUseId = use.ToolUseId, InputJson = use.InputJson, ResultJson = null, Duration = TimeSpan.Zero }); var sw = Stopwatch.StartNew(); try { var result = await DispatchToolCoreAsync(request, runCtx, runCache, use, messageId, ct).ConfigureAwait(false); sw.Stop(); request.Exchange.setProperty(LlmExpressionKeys.Tool, new LlmToolContext { Name = use.Name, ToolUseId = use.ToolUseId, InputJson = use.InputJson, ResultJson = result.OutputJson, Duration = sw.Elapsed }); return result; } finally { // Tool context lives only for the duration of dispatch — clear after the // caller has had a chance to read ${tool.*} for logging/metrics. request.Exchange.Properties.Remove(LlmExpressionKeys.Tool); } } private async Task DispatchToolCoreAsync( AgentRequest request, AgentRunContext runCtx, AgentRunToolCache runCache, LlmToolUseBlock use, string? messageId, CancellationToken ct) { var tool = FindTool(request.Tools, use.Name); if (tool is null) { return new LlmToolResultBlock(use.ToolUseId, JsonSerializer.Serialize(new { error = "unknown_tool", name = use.Name }, JsonOptions), IsError: true); } var redactedInput = _redaction.Redact(use.InputJson, RedactionContext.ToolInput); // Claims are verified before approval: a caller that cannot prove its identity must not even // reach the approver's queue. Fail closed — a tool that declares claims this run cannot // verify is never invoked. The model is told the error code only; the missing-claim list // stays in the observer/audit channel, so the tool's policy never leaks to the model. var requiredClaims = tool.Capability.Safety.RequiredClaims; if (requiredClaims.Count > 0) { var held = _claimsSource?.GetClaims(request.Exchange); var missing = held is null ? [.. requiredClaims] : requiredClaims.Where(c => !held.Contains(c, StringComparer.Ordinal)).ToArray(); if (missing.Length > 0) { await _observer.OnToolInvokedAsync(new AgentToolInvocationContext { Run = runCtx, Tool = tool.Capability, InputJson = redactedInput, OutputJson = null, ToolUseId = use.ToolUseId, Duration = TimeSpan.Zero, Skipped = true, SkipReason = $"{ToolSkipReasons.ClaimsMissing}:{string.Join(",", missing)}" }, ct).ConfigureAwait(false); if (held is null) { // No principal at all is usually a transport/wiring problem, so it earns a warning. _logger?.LogWarning( "Tool '{Tool}' denied: no verifiable principal. Missing: [{Claims}]. Claims source: {Source}.", use.Name, string.Join(", ", missing), _claimsSource is null ? "none registered" : _claimsSource.GetType().Name); } else { // A caller that simply does not hold the claim is a normal decision, not an incident. _logger?.LogInformation( "Tool '{Tool}' denied: the principal lacks the required claims. Missing: [{Claims}].", use.Name, string.Join(", ", missing)); } return new LlmToolResultBlock( use.ToolUseId, JsonSerializer.Serialize(new { error = ToolResultErrors.ClaimsMissing }, JsonOptions), IsError: true); } } // An external tool (mail, payment, deployment) does something no transaction can take back. Inside an // ambient transaction - a route's .Transacted() - the run's database work and deferred sends roll back // together, but the external action would stay done, and a retry after the rollback would do it again. // So it is not run there: the model gets an error it can answer around, the audit channel records why. // Checked before approval, so nobody is asked to approve a call that cannot run. if (tool.Capability.Safety.SideEffect == ToolSideEffect.External && System.Transactions.Transaction.Current is not null) { await _observer.OnToolInvokedAsync(new AgentToolInvocationContext { Run = runCtx, Tool = tool.Capability, InputJson = redactedInput, OutputJson = null, ToolUseId = use.ToolUseId, Duration = TimeSpan.Zero, Skipped = true, SkipReason = ToolSkipReasons.ExternalInTransaction }, ct).ConfigureAwait(false); _logger?.LogWarning( "Tool '{Tool}' declares SideEffect=External and was called inside an ambient transaction; it was not run, " + "because its action cannot be rolled back with the transaction. Call it from a route without .Transacted().", use.Name); return new LlmToolResultBlock( use.ToolUseId, JsonSerializer.Serialize(new { error = ToolResultErrors.ExternalInTransaction }, JsonOptions), IsError: true); } if (tool.Capability.Safety.RequiresApproval) { var approvalReq = new ApprovalRequest { ConversationId = request.ConversationId, Tool = tool.Capability, InputJson = redactedInput, Exchange = request.Exchange, ToolUseId = use.ToolUseId }; var decision = await _approval.AwaitAsync(approvalReq, ct).ConfigureAwait(false); if (_approvalStore is not null) await _approvalStore.RecordAsync(approvalReq, decision, request.Exchange, ct).ConfigureAwait(false); if (!decision.Approved) { await _observer.OnToolInvokedAsync(new AgentToolInvocationContext { Run = runCtx, Tool = tool.Capability, InputJson = redactedInput, OutputJson = null, ToolUseId = use.ToolUseId, Duration = TimeSpan.Zero, Skipped = true, SkipReason = $"{ToolSkipReasons.ApprovalDeniedPrefix} {decision.Reason ?? "no reason"}" }, ct).ConfigureAwait(false); return new LlmToolResultBlock(use.ToolUseId, JsonSerializer.Serialize(new { error = ToolResultErrors.ApprovalDenied, reason = decision.Reason }, JsonOptions), IsError: true); } } // Cache lookup runs before the idempotency reservation: a hit means "this exact input already // produced this output", which is cheaper than asking "was this tool_use already executed?". // Approval ran first, so a cached result can never bypass a gate. // // The gate is the tool's own declaration, checked here as well as at registration: only a // read-only tool may be cached, because a cached entry suppresses the side effect it stands for. // A descriptor that reached the engine without that check (a hand-built AgentRequest) is therefore // not cached — and says so, instead of silently mutating nothing. // // The address is resolved BEFORE the key is built and then REUSED for the dispatch: a descriptor // may address a per-tenant endpoint, and a BuildEndpointUri that is not pure must not produce one // address for the key and another for the call. string? memoKey = null; string? storeKey = null; string? resolvedToolUri = null; var lookedUp = false; var caching = tool.Capability.Safety.Caching; var cacheable = caching != ToolCachingPolicy.None && tool.Capability.Safety.SideEffect == ToolSideEffect.ReadOnly; if (caching != ToolCachingPolicy.None && !cacheable) { _logger?.LogWarning( "Tool '{Tool}' declares Caching={Caching} with SideEffect={SideEffect}; its result is not cached. " + "Only read-only tools may be cached — registration rejects this combination, so this descriptor " + "reached the engine without it.", use.Name, caching, tool.Capability.Safety.SideEffect); } if (cacheable) { resolvedToolUri = tool.BuildEndpointUri(use.InputJson, request.Exchange); var policyFingerprint = ToolCacheKey.PolicyFingerprint(tool.Capability.Safety); var callerFingerprint = CallerFingerprint(request); memoKey = caching == ToolCachingPolicy.Memoize ? ToolCacheKey.MemoKey( tool.Capability.Name, resolvedToolUri, policyFingerprint, callerFingerprint, use.InputJson) : null; storeKey = ToolCacheKey.StoreKey( tool.Capability.Name, resolvedToolUri, use.InputJson, caching, policyFingerprint, callerFingerprint); string? cachedOutput = null; if (memoKey is not null) { cachedOutput = runCache.Get(memoKey); lookedUp = true; } if (cachedOutput is null && storeKey is not null && _toolCache is not null) { // Best effort: a cache that cannot answer must not fail the run. A store outage is an // operational incident, not a reason to refuse work the tool itself can still do. try { cachedOutput = await _toolCache.GetAsync(storeKey, request.Exchange, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger?.LogWarning(ex, "Tool-cache read failed for '{Tool}'; continuing without the cache.", use.Name); cachedOutput = null; } lookedUp = true; } if (cachedOutput is not null) { LlmMetrics.ToolCacheHits.Add(1, new KeyValuePair("llm.tool.name", use.Name)); await _observer.OnToolInvokedAsync(new AgentToolInvocationContext { Run = runCtx, Tool = tool.Capability, InputJson = redactedInput, OutputJson = cachedOutput, ToolUseId = use.ToolUseId, Duration = TimeSpan.Zero, Skipped = true, SkipReason = ToolSkipReasons.CacheHit }, ct).ConfigureAwait(false); return new LlmToolResultBlock(use.ToolUseId, cachedOutput); } if (lookedUp) LlmMetrics.ToolCacheMisses.Add(1, new KeyValuePair("llm.tool.name", use.Name)); } // Idempotency is opt-in per side-effect class, as the tool's Safety declares: a read-only tool // has no side effect to de-duplicate, and reserving it costs store round-trips on every call. // Note what this implies for tools that declare nothing — SideEffect defaults to ReadOnly, so // "no declaration" means "no replay protection". var needsIdempotency = tool.Capability.Safety.SideEffect != ToolSideEffect.ReadOnly; ToolIdempotencyReservation? reservation = null; if (_idempotency is not null && request.ConversationId is { } convId && needsIdempotency) { reservation = await _idempotency.TryReserveAsync(convId, use.ToolUseId, request.Exchange, ct).ConfigureAwait(false); if (!reservation.IsNew) { await _observer.OnToolInvokedAsync(new AgentToolInvocationContext { Run = runCtx, Tool = tool.Capability, InputJson = redactedInput, OutputJson = reservation.CachedOutputJson, ToolUseId = use.ToolUseId, Duration = TimeSpan.Zero, Skipped = true, SkipReason = ToolSkipReasons.IdempotencyHit }, ct).ConfigureAwait(false); return new LlmToolResultBlock(use.ToolUseId, reservation.CachedOutputJson ?? "{}"); } } var sw = Stopwatch.StartNew(); try { var output = await DispatchToolEndpointAsync(request, tool, use, resolvedToolUri, ct).ConfigureAwait(false); sw.Stop(); LlmMetrics.ToolInvocations.Add(1, new KeyValuePair("llm.tool.name", use.Name)); if (reservation is not null && request.ConversationId is { } completeConvId) await _idempotency!.CompleteAsync(completeConvId, use.ToolUseId, output, request.Exchange, ct).ConfigureAwait(false); var redactedOutput = _redaction.Redact(output, RedactionContext.ToolOutput); // Store only an output the redaction filter left untouched. Storing the redacted body // would hand the model different data on a hit than on a miss (the returned block below // carries the raw body); storing the raw body would persist redaction-bypassing content in // the cache for the whole TTL. The price is honest and documented: a tool whose output is // redacted is not cached at all. if (!string.Equals(output, redactedOutput, StringComparison.Ordinal)) { _logger?.LogDebug( "Tool '{Name}' output was redacted — result is not cached.", use.Name); } else { if (memoKey is not null) runCache.Set(memoKey, output); if (storeKey is not null && _toolCache is not null) { // Best effort, same reasoning as the read: a failed write loses a future hit, it does // not invalidate a tool call that already succeeded. Letting it throw here would turn // a successful call into an error the model sees — and may retry. try { await _toolCache.SetAsync(storeKey, output, ToolCacheKey.StoreTtl, request.Exchange, ct) .ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger?.LogWarning(ex, "Tool-cache write failed for '{Tool}'; the result is not cached.", use.Name); } } } await _observer.OnToolInvokedAsync(new AgentToolInvocationContext { Run = runCtx, Tool = tool.Capability, InputJson = redactedInput, OutputJson = redactedOutput, ToolUseId = use.ToolUseId, Duration = sw.Elapsed }, ct).ConfigureAwait(false); return new LlmToolResultBlock(use.ToolUseId, output); } catch (Exception ex) { sw.Stop(); LlmMetrics.ToolFailures.Add(1, new KeyValuePair("llm.tool.name", use.Name), new KeyValuePair("exception.type", ex.GetType().Name)); _logger?.LogError(ex, "Tool '{Name}' failed", use.Name); if (reservation is not null && request.ConversationId is { } releaseConvId) await _idempotency!.ReleaseAsync(releaseConvId, use.ToolUseId, request.Exchange, ct).ConfigureAwait(false); await _observer.OnToolInvokedAsync(new AgentToolInvocationContext { Run = runCtx, Tool = tool.Capability, InputJson = redactedInput, OutputJson = null, ToolUseId = use.ToolUseId, Duration = sw.Elapsed, Exception = ex }, ct).ConfigureAwait(false); return new LlmToolResultBlock(use.ToolUseId, JsonSerializer.Serialize(new { error = ex.GetType().Name, message = ex.Message }, JsonOptions), IsError: true); } } private async Task PersistMessageAsync( AgentRequest request, string? parentId, LlmMessage message, int iteration, LlmStopReason? stopReason, LlmUsage usage, string? toolUseId, double? temperature, int? maxTokens, double? topP, string? toolSetHash, string? providerSystemFingerprint, string? providerResponseId, long? latencyMs, int? retryCount, CancellationToken ct) { if (_conversation is null || request.ConversationId is null) return parentId; return await _conversation.AppendAsync( request.ConversationId, parentId, message, new ConversationMessageMeta { CreatedAtUtc = DateTime.UtcNow, Iteration = iteration, ProviderId = request.Factory.Provider, ModelId = request.Factory.ModelId, StopReason = stopReason, Usage = usage, ToolUseId = toolUseId, Temperature = temperature, MaxTokens = maxTokens, TopP = topP, PromptTemplateName = request.PromptTemplateName, PromptTemplateVersion = request.PromptTemplateVersion, ToolSetHash = toolSetHash, ProviderSystemFingerprint = providerSystemFingerprint, UserId = request.UserId, AuditTags = request.AuditTags, FactoryName = string.IsNullOrEmpty(request.Factory.Name) ? null : request.Factory.Name, BaseUrl = request.Factory.BaseUrl?.ToString(), ProviderResponseId = providerResponseId, LatencyMs = latencyMs, ApiKeyFingerprint = ComputeApiKeyFingerprint(request.Factory.ApiKey), RetryCount = retryCount }, request.Exchange, ct).ConfigureAwait(false); } /// /// Reads the retry counter the route framework stamps on the inbound /// exchange before the engine runs. Sources, in priority order: the /// per-step RetryProcessor property, the OnExceptionProcessor /// header, then the DeadLetterProcessor header. Returns null when /// none are present (first / only delivery). /// private static int? ReadRetryCount(IExchange exchange) { if (exchange.Properties.TryGetValue("RetryAttempt", out var prop) && TryToInt(prop, out var fromProp)) return fromProp; if (exchange.In?.Headers is { } headers) { if (headers.TryGetValue("CamelRedeliveryCounter", out var redeliv) && TryToInt(redeliv, out var fromRedeliv)) return fromRedeliv; if (headers.TryGetValue("CamelDeadLetterRedeliveryCount", out var dlq) && TryToInt(dlq, out var fromDlq)) return fromDlq; } return null; static bool TryToInt(object? raw, out int value) { switch (raw) { case int i: value = i; return true; case long l: value = (int)l; return true; case string s when int.TryParse(s, out var parsed): value = parsed; return true; default: value = 0; return false; } } } /// /// Stable, non-secret fingerprint of the API key — SHA-256 of the UTF-8 /// bytes, first 16 hex chars. Empty / null key → null fingerprint. /// private static string? ComputeApiKeyFingerprint(string? apiKey) { if (string.IsNullOrEmpty(apiKey)) return null; Span hash = stackalloc byte[32]; SHA256.HashData(Encoding.UTF8.GetBytes(apiKey), hash); return Convert.ToHexString(hash[..8]).ToLowerInvariant(); } private async Task SafeRunShadowAsync(ILlmProvider provider, LlmRequest request, LlmResponse response, CancellationToken ct) { // The shadow runs beside the primary run, not inside its work: it must not write into the route's // transaction, and a command of its own on that transaction's connection at the same time as the // primary run's would be refused. using var outside = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Suppress, System.Transactions.TransactionScopeAsyncFlowOption.Enabled); try { await _shadow.RunAsync(provider, request, response, ct).ConfigureAwait(false); } catch { /* shadow failures must never affect the primary run */ } } /// /// Runs a budget call outside the ambient transaction. Tokens are paid when the provider answers, so a /// rollback of the route must not un-count them: a retry after the rollback would otherwise run against /// a budget that forgot the spend. /// private static async ValueTask OutsideTransactionAsync(Func> call) { using var outside = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Suppress, System.Transactions.TransactionScopeAsyncFlowOption.Enabled); var decision = await call().ConfigureAwait(false); outside.Complete(); return decision; } private static void PublishConversationContext( AgentRequest request, IReadOnlyList transcript, int iterations, AgentUsage totalUsage) { LlmMessage? lastAssistant = null; for (var i = transcript.Count - 1; i >= 0; i--) { if (transcript[i].Role == "assistant") { lastAssistant = transcript[i]; break; } } request.Exchange.setProperty(LlmExpressionKeys.Conversation, new LlmConversationContext { Id = request.ConversationId, MessageCount = transcript.Count, Tokens = new LlmUsage(totalUsage.InputTokens, totalUsage.OutputTokens), Iterations = iterations, LastMessage = lastAssistant }); } private static LlmToolCapability[] ProjectCapabilities(IReadOnlyList tools) { if (tools.Count == 0) return []; var arr = new LlmToolCapability[tools.Count]; for (var i = 0; i < tools.Count; i++) arr[i] = tools[i].Capability; return arr; } private static ILlmToolDescriptor? FindTool(IReadOnlyList tools, string name) { foreach (var t in tools) if (t.Capability.Name == name) return t; return null; } /// /// Everything a tool receives that is NOT the input JSON and still changes its answer: the caller's /// identity and the header values the route opted into propagating. Both belong in the cache key — /// a tool route sees a real principal and real headers (see ), so /// "same input" does not mean "same answer", and without this a persisted entry fetched for one /// caller could be served to another. /// /// The ambient conversation / correlation ids and the audit tags are deliberately left out: they are /// per-run bookkeeping, and folding them in would make a cross-run cache useless. A tool whose output /// depends on them must not declare Persist. /// /// private static string CallerFingerprint(AgentRequest request) { var sb = new StringBuilder(); var principal = ExchangePrincipal.Get(request.Exchange); string? subject = null; if (principal?.Identity is { IsAuthenticated: true } identity) subject = identity.Name ?? principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; sb.Append("caller:").Append(subject ?? request.UserId ?? string.Empty).Append('\n'); if (request.PropagateToolHeaders is { Count: > 0 } names) { var headers = request.Exchange.In?.Headers; foreach (var name in names .Where(n => !string.IsNullOrWhiteSpace(n)) .OrderBy(n => n, StringComparer.OrdinalIgnoreCase)) { sb.Append("header:").Append(name).Append('='); if (headers is not null && headers.TryGetValue(name, out var value) && value is not null) sb.Append(value); sb.Append('\n'); } } return sb.ToString(); } /// /// Dispatches one tool call onto its redb.Route endpoint. /// /// The tool runs on a child of the agent exchange, not on a freshly minted /// one: carries over the parent's /// Properties (including LlmKeys.RedbName), its RouteId and its /// DI scope, so scoped services the conversation resolved — principal, tenant /// accessor, per-exchange IRedbService — are the same instances inside the /// tool. This is what documents; building a naked /// exchange severed all of it. /// /// /// Linked (shared scope) rather than a scope of its own: tool calls are /// dispatched sequentially inside one iteration (see the foreach in /// ), so there is no concurrent resolution on the shared /// scope — a race on a shared scope applies to parallel forks, not to an inline /// request/reply. A child scope would also defeat /// the point: the tool would get an empty scope instead of the conversation's. /// /// /// Headers are filtered by (default-deny), never /// copied wholesale. /// /// private async Task DispatchToolEndpointAsync( AgentRequest request, ILlmToolDescriptor descriptor, LlmToolUseBlock use, string? resolvedUri, CancellationToken ct) { if (_producerTemplate is null) throw new InvalidOperationException( "AgentEngine has no IProducerTemplate. Register the engine via AddRedbRouteLlm() so the producer template is injected."); var parentExchange = request.Exchange; // The cache block resolves the address when it needs a key; passing it in keeps one resolution // per dispatch, so a descriptor that is not pure cannot index the cache by one address and call // another. var endpointUri = resolvedUri ?? descriptor.BuildEndpointUri(use.InputJson, parentExchange); if (string.IsNullOrWhiteSpace(endpointUri)) throw new InvalidOperationException( $"Tool '{descriptor.Capability.Name}' returned an empty endpoint URI."); var msg = new Message(use.InputJson) { ContentType = "application/json" }; msg.Headers[LlmHeaders.ToolName] = descriptor.Capability.Name; msg.Headers[LlmHeaders.ToolBridgeEndpoint] = endpointUri; ToolHeaderPolicy.Apply(request, msg.Headers); var child = parentExchange.CreateLinkedChild(msg); try { ct.ThrowIfCancellationRequested(); var done = await _producerTemplate.RequestAsync(endpointUri, child, ct).ConfigureAwait(false); return SerializeReply(done.Out?.Body ?? done.In.Body); } finally { // Releases only what the tool route itself opened — the named // `__redb_scope:*` entries it resolved (CreateLinkedChild does not copy the // parent's). The shared parent scope is marked not-owned on the child, so // the conversation keeps its scope and connections after the tool returns. await child.DisposeAsync().ConfigureAwait(false); } } private static readonly JsonSerializerOptions ToolReplyJsonOptions = new(JsonSerializerDefaults.Web) { // Non-ASCII tool output stays UTF-8 (not \uXXXX): escaped Cyrillic / CJK // would ~6× the tokens the model sees and can surface literal \u escapes. Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private static string SerializeReply(object? reply) { if (reply is null) return "null"; if (reply is string s) return JsonSerializer.Serialize(s, ToolReplyJsonOptions); if (reply is IMessage m) return SerializeReply(m.Body); if (reply is byte[] bytes) return JsonSerializer.Serialize(Convert.ToBase64String(bytes), ToolReplyJsonOptions); return JsonSerializer.Serialize(reply, reply.GetType(), ToolReplyJsonOptions); } /// /// Stable hash of the tool-capability set exposed to the model on a single /// run. Sorted by name; the source InputSchema string is folded in /// verbatim — if its key order or whitespace changes between runs, the /// hash changes too, which is exactly the signal an auditor wants /// ("the same prompt saw a different tool surface yesterday"). Returns /// null for the empty set so unused-tool runs don't pollute the column. /// private static string? ComputeToolSetHash(IReadOnlyList capabilities) { if (capabilities.Count == 0) return null; var sb = new StringBuilder(); foreach (var cap in capabilities.OrderBy(c => c.Name, StringComparer.Ordinal)) { sb.Append(cap.Name).Append('\n'); sb.Append(cap.Description ?? string.Empty).Append('\n'); sb.Append(cap.InputSchema ?? string.Empty).Append('\n'); // Safety is part of the tool surface the model was given: a policy change between two runs // is exactly the drift an auditor is looking for ("the same prompt, a weaker gate"). sb.Append("safety:") .Append(cap.Safety.SideEffect).Append('/') .Append(cap.Safety.Caching).Append('/') .Append(cap.Safety.Cost).Append('/') .Append(cap.Safety.RequiresApproval ? '1' : '0').Append('\n'); // Claims are length-prefixed: joining on a comma would hash ["a,b"] and ["a","b"] // identically, which is the one collision an audit hash must not have. foreach (var claim in cap.Safety.RequiredClaims.OrderBy(c => c, StringComparer.Ordinal)) sb.Append("claim:").Append(claim.Length).Append(':').Append(claim).Append('\n'); sb.Append("---\n"); } var hash = SHA256.HashData(Encoding.UTF8.GetBytes(sb.ToString())); return Convert.ToHexString(hash).ToLowerInvariant(); } } Path: redb-route/redb.Route.Llm/Engine/AgentRequest.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/AgentRequest.cs ---- using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Engine; /// /// Single agent execution request. Carries the user message, optional system prompt, /// conversation context and the parent exchange for TX/scope/principal. /// public sealed class AgentRequest { /// Connection factory used to build the provider. public required LlmConnectionFactory Factory { get; init; } /// Owning exchange — drives DI scope, headers, principal and observability. public required IExchange Exchange { get; init; } /// Initial user message (may include text and tool-result blocks). public required IReadOnlyList UserContent { get; init; } /// System prompt for this run. public string? SystemPrompt { get; init; } /// /// Ask the provider to cache the system prompt across turns — see /// . Worth it only when the system prompt /// is byte-stable; a prompt that varies per request never gets read back. /// public bool CacheSystemPrompt { get; init; } /// /// Messages placed before the loaded conversation history on every iteration of the /// run — a fixed opening exchange the model sees as its own past, a few-shot block, anything /// that must precede the dialog without being part of it. /// /// Not persisted and not part of the conversation. The store keeps what was /// said in this dialog; the preamble is part of how the assistant is assembled, so it is /// re-attached from the request each time rather than written as rows. That is also what /// makes it survive a branch rebuild: a fresh branch loads an empty path and the preamble is /// still there. /// /// Keep it byte-stable and mark its last message with /// when the system prompt is cached too — otherwise /// the cached prefix ends at the system block and the preamble is paid in full on every /// turn. The first preamble message must be a user turn: providers require the /// transcript to open with one. /// public IReadOnlyList Preamble { get; init; } = []; /// Tools available to the model on this run. public IReadOnlyList Tools { get; init; } = []; /// Conversation identifier (when conversation tracking is on). public string? ConversationId { get; init; } /// /// Message id of the conversation node this run should attach under. /// Null = attach under the conversation root (continue at head when resuming; /// new branch when the conversation already has children). /// public string? ConversationParentMessageId { get; init; } /// Per-run budget (defaults to unbounded). public AgentBudget Budget { get; init; } = AgentBudget.Unbounded; /// Maximum tool-loop iterations. public int MaxIterations { get; init; } = 8; /// Per-call sampling overrides. public double? Temperature { get; init; } /// Per-call max-tokens override. public int? MaxTokens { get; init; } /// /// Optional name of the prompt template that produced . /// When set together with , the engine /// stamps every persisted assistant message with the (name, version) pair so /// auditors can reconstruct "which exact prompt drove this answer". Stays /// null when the caller does not use a managed template. /// public string? PromptTemplateName { get; init; } /// Version of the prompt template named by . public string? PromptTemplateVersion { get; init; } /// /// Stable identifier of the principal that initiated this run (end-user, /// service account, on-behalf-of subject — host decides). Persisted on /// every row of the run so audit queries always have a consistent subject. /// Null when no principal is wired. /// public string? UserId { get; init; } /// /// Free-form audit tags captured pre-call (operator-controlled key/value /// pairs — e.g. ab-bucket=A, tier=premium). The same snapshot /// is stamped on every row of the run; null / empty when no tags are wired. /// public IReadOnlyDictionary? AuditTags { get; init; } /// /// Extra header names the route author opted into propagating from this /// exchange to every tool call of the run (e.g. x-tenant-id, /// accept-language). A trailing * makes the entry a prefix match /// (x-app-*). Propagation is default-deny: without an entry here only /// , the resolved /// and the resolved reach a tool — /// the inbound transport's own headers never do. Null / empty = defaults only. /// public IReadOnlyList? PropagateToolHeaders { get; init; } /// /// Make every model call of the run as a stream (stream=calls). The pieces go to /// as they arrive; the loop goes on with the whole answer /// the stream assembled, the same answer a plain call returns, so tools, the conversation, the budget and the /// route's transaction work as without streaming. The connection carries data while the model writes. /// public bool StreamModelCalls { get; init; } /// /// Receiver of this run's pieces, beside the observer: the observer is shared by every run of the engine, and this /// one belongs to the run that set it. stream=body feeds Out.Body through it. Called only when /// is on, in the order the pieces arrive. /// public Func? OnDelta { get; init; } } /// Final agent response. public sealed class AgentResponse { /// Last assistant content (text + any unanswered tool calls). public required IReadOnlyList Content { get; init; } /// Aggregate token usage across all iterations. public LlmUsage Usage { get; init; } = LlmUsage.Empty; /// Number of tool-loop iterations consumed. public int Iterations { get; init; } /// Final stop reason of the last provider call. public LlmStopReason StopReason { get; init; } = LlmStopReason.EndTurn; /// Convenience accessor — first text block in , or empty. public string Text { get { foreach (var b in Content) if (b is LlmTextBlock t) return t.Text; return string.Empty; } } } Path: redb-route/redb.Route.Llm/Engine/Eval/LlmEvalCase.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Eval/LlmEvalCase.cs ---- using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Engine.Eval; /// /// Declarative description of a single eval case. Combines the inputs the harness /// feeds to with the assertions it scores /// against the produced . Cases are pure data so the /// same set can be replayed offline (via ReplayProvider) and against a /// live provider. /// public sealed class LlmEvalCase { /// Stable scenario name — also persisted on . public required string Scenario { get; init; } /// System prompt for the run. Null = no system prompt. public string? SystemPrompt { get; init; } /// User content blocks for the initial turn. Use for the common text-only case. public IReadOnlyList UserContent { get; init; } = []; /// Tools available to the model on this case (empty = no tools). public IReadOnlyList Tools { get; init; } = []; /// Maximum tool-loop iterations forwarded to . public int MaxIterations { get; init; } = 4; /// Per-run budget forwarded to . public AgentBudget Budget { get; init; } = AgentBudget.Unbounded; /// Sampling temperature override. public double? Temperature { get; init; } /// Max-tokens override. public int? MaxTokens { get; init; } /// Substrings the final assistant text must contain (case-sensitive). public IReadOnlyList ExpectedTextContains { get; init; } = []; /// Substrings the final assistant text must NOT contain (case-sensitive). public IReadOnlyList ExpectedTextNotContains { get; init; } = []; /// Tool names that must be invoked at least once across the run (in any order). public IReadOnlyList ExpectedToolCalls { get; init; } = []; /// When set, the run's final stop reason must equal this value. public LlmStopReason? ExpectedStopReason { get; init; } /// When set, the run's iteration count must be ≤ this value. public int? MaxObservedIterations { get; init; } /// When set, the run's total cost must be ≤ this value (USD). public decimal? MaxObservedCostUsd { get; init; } /// /// Optional custom scorer — receives the final and /// returns a . Composes with the built-in /// assertions: a case fails when any built-in assertion fails OR the custom /// scorer returns = false. /// public Func? CustomScorer { get; init; } /// Convenience: builds a single-text-block . public static IReadOnlyList UserText(string text) => [new LlmTextBlock(text)]; } /// /// Outcome of a custom scorer. Pass=false marks the case as failed regardless of /// other assertions; and flow into /// the persisted . /// public readonly record struct LlmEvalCaseScore( bool Pass, double? Score = null, IReadOnlyDictionary? Dimensions = null, string? Notes = null) { /// Convenience: passing score with no extras. public static readonly LlmEvalCaseScore Passed = new(true); } Path: redb-route/redb.Route.Llm/Engine/Eval/LlmEvalRunner.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Eval/LlmEvalRunner.cs ---- using System.Diagnostics; using redb.Route.Core; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Engine.Eval; /// /// Drives a batch of through an , /// scores each run against the case's assertions, and (when configured) persists /// the outcome via . Designed for both offline /// regression suites (paired with ReplayProvider) and live smoke runs. /// public sealed class LlmEvalRunner { private readonly IAgentEngine _engine; private readonly LlmConnectionFactory _factory; private readonly IEvalRunStore? _store; /// Creates a runner bound to a concrete engine + provider factory. /// Engine implementation under test. /// Provider factory threaded through every . /// Optional store for run records — null disables persistence. public LlmEvalRunner(IAgentEngine engine, LlmConnectionFactory factory, IEvalRunStore? store = null) { _engine = engine ?? throw new ArgumentNullException(nameof(engine)); _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _store = store; } /// Runs a single case to completion and returns the scored result. public async Task RunAsync(LlmEvalCase @case, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(@case); var sw = Stopwatch.StartNew(); AgentResponse? response = null; Exception? failure = null; try { response = await _engine.RunAsync(BuildRequest(@case), ct).ConfigureAwait(false); } catch (Exception ex) { failure = ex; } sw.Stop(); var result = Score(@case, response, failure, sw.Elapsed); if (_store is not null) await _store.SaveAsync(ToRecord(@case, result), ct: ct).ConfigureAwait(false); return result; } /// /// Runs every case in sequentially. Failures in one /// case never prevent the others from running — each /// captures its own pass/fail and exception (if any). /// public async Task> RunAllAsync( IEnumerable cases, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(cases); var results = new List(); foreach (var c in cases) { ct.ThrowIfCancellationRequested(); results.Add(await RunAsync(c, ct).ConfigureAwait(false)); } return results; } private AgentRequest BuildRequest(LlmEvalCase @case) { var content = @case.UserContent.Count > 0 ? @case.UserContent : LlmEvalCase.UserText(@case.Scenario); var bodyText = content.OfType().FirstOrDefault()?.Text ?? @case.Scenario; return new AgentRequest { Factory = _factory, Exchange = new Exchange(new Message(bodyText)), UserContent = content, SystemPrompt = @case.SystemPrompt, Tools = @case.Tools, MaxIterations = @case.MaxIterations, Budget = @case.Budget, Temperature = @case.Temperature, MaxTokens = @case.MaxTokens }; } private static LlmEvalResult Score( LlmEvalCase @case, AgentResponse? response, Exception? failure, TimeSpan duration) { var failures = new List(); if (failure is not null) { failures.Add($"engine threw: {failure.GetType().Name}: {failure.Message}"); return new LlmEvalResult { Case = @case, Response = null, Pass = false, Failures = failures, Duration = duration, Exception = failure }; } var resp = response!; var text = resp.Text; foreach (var needle in @case.ExpectedTextContains) if (!text.Contains(needle, StringComparison.Ordinal)) failures.Add($"expected text to contain '{needle}'"); foreach (var needle in @case.ExpectedTextNotContains) if (text.Contains(needle, StringComparison.Ordinal)) failures.Add($"expected text to NOT contain '{needle}'"); if (@case.ExpectedStopReason is { } expectedStop && resp.StopReason != expectedStop) failures.Add($"expected stop reason {expectedStop}, got {resp.StopReason}"); if (@case.MaxObservedIterations is { } maxIter && resp.Iterations > maxIter) failures.Add($"iterations {resp.Iterations} exceeded max {maxIter}"); // Tool-call expectations are checked against the assistant turns recorded // in the final transcript — only the last assistant message is on // AgentResponse.Content, so we approximate by detecting tool-use blocks // there. The integration tests use FakeProvider/ReplayProvider which // surface tool calls explicitly enough for this check. if (@case.ExpectedToolCalls.Count > 0) { var seen = new HashSet(StringComparer.Ordinal); foreach (var b in resp.Content) if (b is LlmToolUseBlock use) seen.Add(use.Name); foreach (var name in @case.ExpectedToolCalls) if (!seen.Contains(name)) failures.Add($"expected tool '{name}' to be invoked"); } var customScore = @case.CustomScorer?.Invoke(resp); if (customScore is { Pass: false } cs) failures.Add(cs.Notes is { Length: > 0 } ? $"custom scorer failed: {cs.Notes}" : "custom scorer failed"); return new LlmEvalResult { Case = @case, Response = resp, Pass = failures.Count == 0, Failures = failures, Duration = duration, Score = customScore?.Score, Dimensions = customScore?.Dimensions, Notes = customScore?.Notes }; } private EvalRunRecord ToRecord(LlmEvalCase @case, LlmEvalResult result) { var resp = result.Response; var iterUsage = resp is null ? AgentUsage.Zero : new AgentUsage(resp.Usage.InputTokens, resp.Usage.OutputTokens, 0m); var iterations = resp is null ? Array.Empty() : new[] { new EvalIterationRecord { Iteration = resp.Iterations, InputTokens = resp.Usage.InputTokens, OutputTokens = resp.Usage.OutputTokens, DurationMs = (int)result.Duration.TotalMilliseconds, Score = result.Score, Notes = result.Notes } }; return new EvalRunRecord { RunId = Guid.NewGuid().ToString("N"), Scenario = @case.Scenario, AgentFingerprint = BuildFingerprint(@case), Score = result.Score ?? (result.Pass ? 1.0 : 0.0), TotalUsage = iterUsage, Iterations = iterations, Dimensions = result.Dimensions }; } private string BuildFingerprint(LlmEvalCase @case) => $"{_factory.Provider}/{_factory.ModelId ?? "default"}#{@case.Scenario}"; } /// Outcome of a single evaluated case. public sealed class LlmEvalResult { /// The case that produced this result. public required LlmEvalCase Case { get; init; } /// Agent response — null when the engine threw. public AgentResponse? Response { get; init; } /// True when every assertion passed. public required bool Pass { get; init; } /// Human-readable failure messages — empty when is true. public IReadOnlyList Failures { get; init; } = []; /// Wall-clock duration of the run. public TimeSpan Duration { get; init; } /// Custom scorer's score, if any. public double? Score { get; init; } /// Custom scorer's dimensions, if any. public IReadOnlyDictionary? Dimensions { get; init; } /// Custom scorer's free-form notes, if any. public string? Notes { get; init; } /// Engine exception, when the run threw. public Exception? Exception { get; init; } } Path: redb-route/redb.Route.Llm/Engine/Governance/IApprovalGate.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Governance/IApprovalGate.cs ---- using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Engine.Governance; /// /// Gate that blocks a tool call until an approver responds. The agent loop calls /// before dispatching a tool whose /// is set — that flag is the only trigger in this /// release; a tool's side-effect class does not reach the gate on its own. /// public interface IApprovalGate { /// /// Awaits an approval decision for the given tool call. /// /// Pending approval request. /// Cancellation token. /// The approver's decision. Task AwaitAsync(ApprovalRequest request, CancellationToken ct = default); } /// Pending tool-call approval request handed to the gate. public sealed class ApprovalRequest { /// Conversation identifier (when persistence is on). public string? ConversationId { get; init; } /// Tool that will be executed. public required LlmToolCapability Tool { get; init; } /// Tool input JSON exactly as it would be passed to the bridged endpoint. public required string InputJson { get; init; } /// Parent exchange owning the call (carries principal, headers, scope). public required IExchange Exchange { get; init; } /// Tool-use id from the model response — propagated to the approver and audit. public required string ToolUseId { get; init; } } /// Outcome of an approval decision. public sealed class ApprovalDecision { /// True = proceed with the tool call; false = abort. public required bool Approved { get; init; } /// Identifier of the approval (for audit / receipt). May be null. public string? ApprovalId { get; init; } /// Optional reason supplied by the approver (especially on rejection). public string? Reason { get; init; } /// Convenience factory for an auto-approval decision. public static ApprovalDecision Approve(string? approvalId = null) => new() { Approved = true, ApprovalId = approvalId }; /// Convenience factory for a denial decision. public static ApprovalDecision Deny(string reason) => new() { Approved = false, Reason = reason }; } /// /// Default gate that auto-approves every request — used in development and in /// fully-trusted scenarios. **Do not use in production** for tools with /// or . /// public sealed class AutoApproveGate : IApprovalGate { /// public Task AwaitAsync(ApprovalRequest request, CancellationToken ct = default) => Task.FromResult(ApprovalDecision.Approve("auto")); } /// /// Gate that denies every approval request. Opt-in: it is not registered by default /// (the shipped default is ), and nothing picks it up automatically /// when mutating tools are present. Swap it in explicitly when a host wants approvals to fail closed: /// services.Replace(ServiceDescriptor.Singleton<IApprovalGate, DenyAllGate>()); /// public sealed class DenyAllGate : IApprovalGate { /// public Task AwaitAsync(ApprovalRequest request, CancellationToken ct = default) => Task.FromResult(ApprovalDecision.Deny("no approval gate configured")); } Path: redb-route/redb.Route.Llm/Engine/Governance/IBudgetEnforcer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Governance/IBudgetEnforcer.cs ---- using redb.Route.Abstractions; namespace redb.Route.Llm.Engine.Governance; /// /// Enforces token and cost budgets on agent runs. Called before and after each /// provider call so the engine can stop early or refuse an iteration when the /// budget is exhausted. /// public interface IBudgetEnforcer { /// /// Checks whether the agent run is allowed to continue at the start of an /// iteration. Implementations may inspect /// against a configured budget and return . /// /// Conversation identifier (null when no persistence). /// Per-run budget (zero or negative components mean unlimited). /// Aggregated usage across iterations completed so far. /// Cancellation token. ValueTask PreCheckAsync( string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default); /// /// Records usage produced by the iteration and returns a decision whether the agent may /// continue. The engine passes per-iteration and running totals; accumulating them on an /// is up to the implementation — see /// , the one shipped enforcer that does. /// ValueTask RecordAndCheckAsync( string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, CancellationToken ct = default); /// /// with the run's exchange, which /// the engine calls: an enforcer that stores usage reads it from the instance the endpoint chose /// (?redb=). The default ignores the exchange, so an enforcer that stores nothing implements only the /// member without it. /// ValueTask PreCheckAsync( string? conversationId, AgentBudget budget, AgentUsage usageSoFar, IExchange? exchange, CancellationToken ct = default) => PreCheckAsync(conversationId, budget, usageSoFar, ct); /// /// with the /// run's exchange, which the engine calls: an enforcer that stores usage writes it to the instance the endpoint /// chose (?redb=). The default ignores the exchange. /// ValueTask RecordAndCheckAsync( string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, IExchange? exchange, CancellationToken ct = default) => RecordAndCheckAsync(conversationId, budget, iterationUsage, totalUsage, ct); } /// Per-run budget. Components ≤ 0 disable that dimension of enforcement. public readonly record struct AgentBudget(int MaxInputTokens, int MaxOutputTokens, decimal MaxCostUsd) { /// Unbounded budget — used when caller didn't supply one. public static readonly AgentBudget Unbounded = new(0, 0, 0m); /// True when every dimension is disabled (Unbounded). public bool IsUnbounded => MaxInputTokens <= 0 && MaxOutputTokens <= 0 && MaxCostUsd <= 0m; } /// Running usage measured against an . public readonly record struct AgentUsage(int InputTokens, int OutputTokens, decimal CostUsd) { /// Zero usage — used as the running total starting point. public static readonly AgentUsage Zero = new(0, 0, 0m); /// Adds two usages component-wise. public AgentUsage Add(AgentUsage other) => new(InputTokens + other.InputTokens, OutputTokens + other.OutputTokens, CostUsd + other.CostUsd); } /// Outcome of a budget enforcement decision. public readonly record struct BudgetDecision(bool Continue, string? Reason) { /// Allows the iteration to proceed. public static readonly BudgetDecision Allow = new(true, null); /// Stops the agent run with a human-readable reason. public static BudgetDecision Stop(string reason) => new(false, reason); } /// Default no-op budget enforcer — always allows execution. public sealed class NoopBudgetEnforcer : IBudgetEnforcer { /// public ValueTask PreCheckAsync( string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default) => ValueTask.FromResult(BudgetDecision.Allow); /// public ValueTask RecordAndCheckAsync( string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, CancellationToken ct = default) => ValueTask.FromResult(BudgetDecision.Allow); } /// /// In-process budget enforcer — checks components against the running /// total. Does NOT persist between runs and takes no store: cross-run budgets need a custom /// over an . /// public sealed class InMemoryBudgetEnforcer : IBudgetEnforcer { /// public ValueTask PreCheckAsync( string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default) { if (budget.IsUnbounded) return ValueTask.FromResult(BudgetDecision.Allow); return ValueTask.FromResult(Check(budget, usageSoFar)); } /// public ValueTask RecordAndCheckAsync( string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, CancellationToken ct = default) { if (budget.IsUnbounded) return ValueTask.FromResult(BudgetDecision.Allow); return ValueTask.FromResult(Check(budget, totalUsage)); } private static BudgetDecision Check(AgentBudget budget, AgentUsage usage) { if (budget.MaxInputTokens > 0 && usage.InputTokens >= budget.MaxInputTokens) return BudgetDecision.Stop($"input-token budget exceeded ({usage.InputTokens}/{budget.MaxInputTokens})"); if (budget.MaxOutputTokens > 0 && usage.OutputTokens >= budget.MaxOutputTokens) return BudgetDecision.Stop($"output-token budget exceeded ({usage.OutputTokens}/{budget.MaxOutputTokens})"); if (budget.MaxCostUsd > 0m && usage.CostUsd >= budget.MaxCostUsd) return BudgetDecision.Stop($"cost budget exceeded ({usage.CostUsd:F4}/{budget.MaxCostUsd:F4} USD)"); return BudgetDecision.Allow; } } Path: redb-route/redb.Route.Llm/Engine/Governance/ICostCalculator.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Governance/ICostCalculator.cs ---- using redb.Route.Llm.Providers; namespace redb.Route.Llm.Engine.Governance; /// /// Prices one provider response so a cost budget can be enforced. The engine asks this once per /// iteration and once before the first call (to prove the model can be priced at all). /// /// Return null only when this deployment cannot price the call at all — a model whose rates it /// does not know. A calculator that knows the rates returns 0m for zero usage; returning /// null there would make the engine refuse a cost-budgeted run it could actually enforce. /// /// public interface ICostCalculator { /// Estimated cost in USD for one response, or null when the model cannot be priced. /// Token usage reported by the provider for the call. /// The connection factory the call was made through (model id, provider id). decimal? Estimate(LlmUsage usage, LlmConnectionFactory factory); } /// /// Default calculator: prices nothing. Registered by AddRedbRouteLlm() so the engine always has /// a calculator to ask; a run that requests a cost budget while this one is registered fails fast /// instead of silently enforcing a zero ceiling. /// public sealed class NullCostCalculator : ICostCalculator { /// public decimal? Estimate(LlmUsage usage, LlmConnectionFactory factory) => null; } Path: redb-route/redb.Route.Llm/Engine/Governance/IRedactionFilter.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Governance/IRedactionFilter.cs ---- namespace redb.Route.Llm.Engine.Governance; /// /// Removes secrets / PII from strings before they are logged, persisted to /// , or sent to observers. Applied to /// both inbound user content and outbound model content, plus tool input/output. /// public interface IRedactionFilter { /// /// Returns the redacted form of . Implementations /// must be deterministic so re-saves don't re-redact already-masked tokens. /// string Redact(string text, RedactionContext context); } /// Context flags that influence how a piece of text is redacted. [Flags] public enum RedactionContext { /// Unspecified. None = 0, /// Text is part of the user-supplied prompt. UserInput = 1, /// Text is model-generated content. ModelOutput = 2, /// Text is tool input JSON. ToolInput = 4, /// Text is tool output JSON. ToolOutput = 8, /// Text is going to be logged (vs stored). Log = 16 } /// Default redaction filter — returns the input untouched. public sealed class NoopRedactionFilter : IRedactionFilter { /// public string Redact(string text, RedactionContext context) => text; } Path: redb-route/redb.Route.Llm/Engine/Governance/IShadowRunner.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Governance/IShadowRunner.cs ---- using redb.Route.Llm.Providers; namespace redb.Route.Llm.Engine.Governance; /// /// Optional shadow runner — when enabled, every primary provider call is also /// executed against an alternate factory, results compared and the divergence /// recorded via the for offline review. /// The user-visible response always comes from the primary call; the shadow run /// never affects routing. /// public interface IShadowRunner { /// True when a shadow run should be executed alongside the primary. bool Enabled { get; } /// /// Executes the shadow call. Implementations should be fire-and-forget from /// the caller's perspective — exceptions must not propagate. /// /// Provider used for the visible response. /// Request that was sent to the primary provider. /// Primary provider response — for divergence comparison. /// Cancellation token. Task RunAsync( ILlmProvider primary, LlmRequest request, LlmResponse primaryResponse, CancellationToken ct = default); } /// Default no-op shadow runner — disabled, never executes anything. public sealed class NoopShadowRunner : IShadowRunner { /// public bool Enabled => false; /// public Task RunAsync(ILlmProvider primary, LlmRequest request, LlmResponse primaryResponse, CancellationToken ct = default) => Task.CompletedTask; } Path: redb-route/redb.Route.Llm/Engine/Governance/StoreBudgetEnforcer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Governance/StoreBudgetEnforcer.cs ---- using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; namespace redb.Route.Llm.Engine.Governance; /// /// Budget enforcement that survives the run: usage is accumulated per conversation in an /// , and the per-run ceiling from is checked /// against that running total. A conversation that already spent its budget therefore stops the next /// run as well — that is the point of storing it, and it is a behaviour change worth knowing about: /// a run that passes today can stop once the conversation's total crosses the ceiling. /// /// Registered by AddRedbLlmStorage() in place of the shipped per-run defaults. The engine calls the /// members that carry the run's exchange, and the store gets it: the rows go to the redb instance the endpoint /// chose (?redb=), else the store's own default. The members without an exchange use the store's default. /// /// /// Without a conversation id there is nowhere to accumulate, so the check degrades to the per-run one. /// /// public sealed class StoreBudgetEnforcer : IBudgetEnforcer { private readonly ICostBudgetStore _store; private readonly InMemoryBudgetEnforcer _perRun = new(); /// Creates the enforcer over . public StoreBudgetEnforcer(ICostBudgetStore store) { ArgumentNullException.ThrowIfNull(store); _store = store; } /// public ValueTask PreCheckAsync( string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default) => PreCheckAsync(conversationId, budget, usageSoFar, exchange: null, ct); /// public ValueTask RecordAndCheckAsync( string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, CancellationToken ct = default) => RecordAndCheckAsync(conversationId, budget, iterationUsage, totalUsage, exchange: null, ct); /// public async ValueTask PreCheckAsync( string? conversationId, AgentBudget budget, AgentUsage usageSoFar, IExchange? exchange, CancellationToken ct = default) { if (budget.IsUnbounded) return BudgetDecision.Allow; if (conversationId is null) return await _perRun.PreCheckAsync(null, budget, usageSoFar, ct).ConfigureAwait(false); var accumulated = await _store.GetUsageAsync(conversationId, exchange, ct).ConfigureAwait(false); return await _perRun.PreCheckAsync(conversationId, budget, accumulated, ct).ConfigureAwait(false); } /// public async ValueTask RecordAndCheckAsync( string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, IExchange? exchange, CancellationToken ct = default) { if (budget.IsUnbounded) return BudgetDecision.Allow; if (conversationId is null) return await _perRun.RecordAndCheckAsync(null, budget, iterationUsage, totalUsage, ct).ConfigureAwait(false); var total = await _store.AddAsync(conversationId, iterationUsage, exchange, ct).ConfigureAwait(false); return await _perRun.RecordAndCheckAsync(conversationId, budget, iterationUsage, total, ct).ConfigureAwait(false); } } Path: redb-route/redb.Route.Llm/Engine/IAgentEngine.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/IAgentEngine.cs ---- namespace redb.Route.Llm.Engine; /// /// Drives the tool-loop: provider call → tool dispatch → provider call → ... until /// end_turn, max iterations, budget cap or cancellation. Owns governance /// (budget, shadow, idempotency, approval) — provider implementations stay pure. /// public interface IAgentEngine { /// Runs the agent to completion. Task RunAsync(AgentRequest request, CancellationToken ct = default); } Path: redb-route/redb.Route.Llm/Engine/Observability/IAgentObserver.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Observability/IAgentObserver.cs ---- using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Engine.Observability; /// /// Receives lifecycle notifications about an agent run. Implementations are /// expected to be non-blocking — heavy work (DB writes, network IO) should be /// queued. Multiple observers may be registered via DI; the engine fans out /// calls in registration order. /// public interface IAgentObserver { /// Called once when an agent run begins. Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default); /// Called after each provider call returns, before tool dispatch. Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default); /// Called for each tool invocation, after it returns or throws. Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default); /// Called once when an agent run ends (whether normally or via cancellation/error). Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default); /// /// Called for each piece of a streamed model call (stream=calls) as it arrives: visible text or the /// model's thinking. A piece is partial; the whole answer follows in /// and in the stored conversation. Not called when the model call is not streamed. Pieces come at the rate the /// model writes, so an observer must not do slow work here. Default: nothing. /// Task OnDeltaAsync(AgentDeltaContext context, CancellationToken ct = default) => Task.CompletedTask; } /// What a streamed piece is. public enum AgentDeltaKind { /// Visible text of the answer. Text, /// The model's thinking: never part of the visible answer. Thinking } /// One piece of a streamed model call. public sealed class AgentDeltaContext { /// Identifiers shared with the rest of the run. public required AgentRunContext Run { get; init; } /// Iteration index, starting from 1: the model call this piece belongs to. public required int Iteration { get; init; } /// What the piece is. public required AgentDeltaKind Kind { get; init; } /// The piece, as the provider sent it. public required string Text { get; init; } } /// Common identifiers passed to every observer call within one agent run. public sealed class AgentRunContext { /// Conversation identifier (when persistence is on). public string? ConversationId { get; init; } /// Connection factory name, model id, provider id. public required string FactoryName { get; init; } /// Provider identifier ("openai", "anthropic", ...). public required string ProviderId { get; init; } /// Model identifier as resolved from the factory. public required string ModelId { get; init; } /// Exchange id of the parent exchange that initiated the run. public required string ExchangeId { get; init; } /// /// The redb instance the endpoint chose for its storage (?redb=, ), or null for /// the registration's default. An observer that writes (the audit) writes there, as the stores do. /// public string? RedbName { get; init; } } /// Per-iteration snapshot — usage, stop reason, content shape. public sealed class AgentIterationContext { /// Identifiers shared with the rest of the run. public required AgentRunContext Run { get; init; } /// Iteration index, starting from 1. public required int Iteration { get; init; } /// Stop reason of this iteration's provider response. public required LlmStopReason StopReason { get; init; } /// Usage produced by this iteration alone (not cumulative). public required LlmUsage IterationUsage { get; init; } /// Wall-clock duration of the provider call. public required TimeSpan Duration { get; init; } } /// Tool invocation outcome. public sealed class AgentToolInvocationContext { /// Identifiers shared with the rest of the run. public required AgentRunContext Run { get; init; } /// Tool that was invoked (or attempted). public required LlmToolCapability Tool { get; init; } /// Tool input JSON. public required string InputJson { get; init; } /// Tool output JSON (null when the call raised an exception). public string? OutputJson { get; init; } /// Tool-use id from the model response. public required string ToolUseId { get; init; } /// Wall-clock duration of the tool execution. public required TimeSpan Duration { get; init; } /// Exception thrown by the tool, if any. public Exception? Exception { get; init; } /// /// True when the call was skipped instead of executed: an idempotency hit, an approval denial, an /// unverifiable claim requirement, or a tool-cache hit. carries which. /// public bool Skipped { get; init; } /// /// Reason for skipping (when is true). Engine-emitted values are the /// constants of ; the approval path adds the gate's own reason text. /// public string? SkipReason { get; init; } } /// Final state of an agent run. public sealed class AgentRunCompletedContext { /// Identifiers shared with the rest of the run. public required AgentRunContext Run { get; init; } /// Number of iterations the loop completed. public required int Iterations { get; init; } /// Aggregate usage across all iterations. public required LlmUsage TotalUsage { get; init; } /// Final stop reason from the last iteration. public required LlmStopReason StopReason { get; init; } /// Exception that terminated the run, if any. public Exception? Exception { get; init; } /// True when the run was cancelled (via CancellationToken or budget stop). public bool Cancelled { get; init; } } /// Default observer — discards all events. public sealed class NoopAgentObserver : IAgentObserver { /// public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Task.CompletedTask; } /// /// Composite observer — fans out events to every registered . /// Exceptions in one observer never break the fan-out. /// public sealed class CompositeAgentObserver : IAgentObserver { private readonly IReadOnlyList _observers; /// Creates a composite over the provided observers (order preserved). public CompositeAgentObserver(IEnumerable observers) { _observers = observers?.ToArray() ?? throw new ArgumentNullException(nameof(observers)); } /// public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Fan(o => o.OnRunStartedAsync(context, ct)); /// public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Fan(o => o.OnIterationCompletedAsync(context, ct)); /// public Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) => Fan(o => o.OnToolInvokedAsync(context, ct)); /// public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Fan(o => o.OnRunCompletedAsync(context, ct)); /// public Task OnDeltaAsync(AgentDeltaContext context, CancellationToken ct = default) => Fan(o => o.OnDeltaAsync(context, ct)); private async Task Fan(Func dispatch) { foreach (var observer in _observers) { try { await dispatch(observer).ConfigureAwait(false); } catch { /* observers must not break the fan-out */ } } } } Path: redb-route/redb.Route.Llm/Engine/PromptRef.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/PromptRef.cs ---- using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; namespace redb.Route.Llm.Engine; /// /// Resolver for prompt references used by ?initialBodyRef= and /// ?systemPromptRef= URI parameters. /// /// Convention (matches the framework-wide #name registry-ref pattern /// already used by Kafka/S3/Firebase connection-factory refs in redb.Route): /// /// /// null / empty → null /// #name → lookup name in (latest version), /// then fall back to as a plain string. /// anything else → returned verbatim as a literal prompt /// /// A #name ref that does not resolve in either registry returns null — /// callers decide whether to substitute an empty string or surface an error. /// internal static class PromptRef { public static async ValueTask ResolveAsync( string? raw, IPromptTemplateRegistry? templates, IRouteContext? context, IExchange? exchange, CancellationToken ct) { if (string.IsNullOrEmpty(raw)) return null; if (raw[0] != '#') return raw; var name = raw[1..]; if (name.Length == 0) return null; if (templates is not null) { var tmpl = await templates.GetAsync(name, version: null, exchange, ct).ConfigureAwait(false); if (tmpl is not null) return tmpl.Body; } return context?.GetFromRegistry(name); } } Path: redb-route/redb.Route.Llm/Engine/Storage/IApprovalStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IApprovalStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Governance; namespace redb.Route.Llm.Engine.Storage; /// /// Persists approval decisions for audit and replay. Every call answered by /// should land here so reviewers can correlate the /// gate's verdict with the resulting tool call. /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange) using the named-redb /// hint stored in . In-memory implementations /// ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IApprovalStore { /// Records a decision against the pending request. Task RecordAsync(ApprovalRequest request, ApprovalDecision decision, IExchange? exchange = null, CancellationToken ct = default); /// Looks up the previously-recorded decision for . Task FindAsync(string approvalId, IExchange? exchange = null, CancellationToken ct = default); } /// An approval decision joined with the request that triggered it. public sealed class ApprovalRecord { /// Approval identifier (also stored on the audit row). public required string ApprovalId { get; init; } /// Conversation the approval belonged to. public string? ConversationId { get; init; } /// Tool name that was gated. public required string ToolName { get; init; } /// Tool input JSON as it was about to be dispatched. public required string InputJson { get; init; } /// True when the gate allowed the call. public required bool Approved { get; init; } /// Reason text supplied by the approver (especially on denial). public string? Reason { get; init; } /// Wall-clock timestamp the decision was recorded. public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow; } /// In-memory approval store — sufficient for tests and demos. public sealed class InMemoryApprovalStore : IApprovalStore { private readonly ConcurrentDictionary _records = new(StringComparer.Ordinal); /// public Task RecordAsync(ApprovalRequest request, ApprovalDecision decision, IExchange? exchange = null, CancellationToken ct = default) { var id = decision.ApprovalId ?? Guid.NewGuid().ToString("N"); _records[id] = new ApprovalRecord { ApprovalId = id, ConversationId = request.ConversationId, ToolName = request.Tool.Name, InputJson = request.InputJson, Approved = decision.Approved, Reason = decision.Reason }; return Task.CompletedTask; } /// public Task FindAsync(string approvalId, IExchange? exchange = null, CancellationToken ct = default) => Task.FromResult(_records.TryGetValue(approvalId, out var rec) ? rec : null); } Path: redb-route/redb.Route.Llm/Engine/Storage/IBatchStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IBatchStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Llm.Engine.Storage; /// /// Tracks async-batch jobs submitted to LLM providers (Anthropic Message /// Batches, OpenAI Batch API, vLLM batch endpoints). The framework does not /// prescribe a submit protocol — providers stay free to implement /// SubmitAsync however they like — but every submitted batch should be /// registered here so that incoming webhooks can be correlated, deduplicated /// and routed back to the originating conversation. /// /// Idempotency of the callback itself is the caller's responsibility (use /// with the batch id as key); this store /// only persists the submit-time metadata. /// /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange) using the named-redb /// hint stored in . In-memory implementations /// ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IBatchStore { /// Records a batch submission. Replaces an existing row with the same id. Task RegisterAsync(BatchJobRecord record, IExchange? exchange = null, CancellationToken ct = default); /// /// Records many batch submissions at once. Bulk-friendly stores commit the /// whole set in a single transaction; the default falls back to a loop. /// async Task RegisterManyAsync(IEnumerable records, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(records); foreach (var record in records) { ct.ThrowIfCancellationRequested(); await RegisterAsync(record, exchange, ct).ConfigureAwait(false); } } /// Loads a previously-registered batch by id; null if unknown. Task GetAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default); /// /// Updates lifecycle status and optional fields. Unknown ids are ignored /// silently — callers should treat a missing row as "not ours" and not as /// an error condition. /// Task UpdateStatusAsync( string batchId, string status, DateTimeOffset? completedAtUtc = null, string? errorMessage = null, IExchange? exchange = null, CancellationToken ct = default); /// Marks a batch as completed; convenience wrapper around . Task MarkCompletedAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default) => UpdateStatusAsync(batchId, "completed", DateTimeOffset.UtcNow, null, exchange, ct); /// Marks a batch as failed; convenience wrapper around . Task MarkFailedAsync(string batchId, string errorMessage, IExchange? exchange = null, CancellationToken ct = default) => UpdateStatusAsync(batchId, "failed", DateTimeOffset.UtcNow, errorMessage, exchange, ct); } /// A persisted batch-submission record. public sealed class BatchJobRecord { /// Provider-issued batch identifier — the business key. public required string BatchId { get; init; } /// "anthropic", "openai", or any custom provider id. public required string ProviderId { get; init; } /// Model id at submit-time. public string ModelId { get; init; } = string.Empty; /// Optional conversation correlation; empty when the batch is conversation-less. public string ConversationId { get; init; } = string.Empty; /// Lifecycle: "submitted" / "running" / "completed" / "failed" / "cancelled". public string Status { get; init; } = "submitted"; /// When the host submitted the batch. public DateTime SubmittedAtUtc { get; init; } = DateTime.UtcNow; /// When the callback fired (or the host marked completion); null while pending. public DateTime? CompletedAtUtc { get; init; } /// Optional URL where the host can fetch results; null when results arrive inline. public string? ResultUrl { get; init; } /// Free-form metadata captured at submit time (caller-controlled JSON). public string? MetadataJson { get; init; } /// Last error message recorded against the batch; null while healthy. public string? ErrorMessage { get; init; } /// /// Opt-in: when true and the batch resolves to "completed", /// appends the assistant /// turn extracted from the callback body to /// under . Has no effect when the conversation /// id is empty or the conversation store is not registered. Default false. /// public bool AppendToConversation { get; init; } } /// In-memory — entries live only for the process lifetime. public sealed class InMemoryBatchStore : IBatchStore { private readonly ConcurrentDictionary _rows = new(StringComparer.Ordinal); /// public Task RegisterAsync(BatchJobRecord record, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(record); ArgumentException.ThrowIfNullOrWhiteSpace(record.BatchId); _rows[record.BatchId] = record; return Task.CompletedTask; } /// public Task GetAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(batchId); return Task.FromResult(_rows.TryGetValue(batchId, out var hit) ? hit : null); } /// public Task UpdateStatusAsync( string batchId, string status, DateTimeOffset? completedAtUtc = null, string? errorMessage = null, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(batchId); ArgumentException.ThrowIfNullOrWhiteSpace(status); if (!_rows.TryGetValue(batchId, out var existing)) return Task.CompletedTask; var updated = new BatchJobRecord { BatchId = existing.BatchId, ProviderId = existing.ProviderId, ModelId = existing.ModelId, ConversationId = existing.ConversationId, Status = status, SubmittedAtUtc = existing.SubmittedAtUtc, CompletedAtUtc = completedAtUtc?.UtcDateTime ?? existing.CompletedAtUtc, ResultUrl = existing.ResultUrl, MetadataJson = existing.MetadataJson, ErrorMessage = errorMessage ?? existing.ErrorMessage, AppendToConversation = existing.AppendToConversation }; _rows[batchId] = updated; return Task.CompletedTask; } } Path: redb-route/redb.Route.Llm/Engine/Storage/IConversationStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IConversationStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Engine.Storage; /// /// Persists conversation transcripts so that an agent run can be resumed, /// branched, or replayed offline. The contract is intentionally tree-shaped: /// every message has an optional parent identifier, which lets callers branch /// from any node — required to model regenerate / parallel tool-calls / what-if /// flows. The flat "append-only history" pattern falls out naturally when the /// caller always passes the previously-appended message id as parentId. /// /// The optional exchange parameter on every method carries the current /// route exchange when the call originates from inside a route pipeline. /// REDB-backed implementations resolve a per-exchange IRedbService /// (and its named siblings via ) through /// IRouteContext.GetRedbService(name, exchange), which already manages /// per-exchange scopes and disposal. In-memory implementations ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IConversationStore { /// /// Appends as a child of /// (or as the root when is null) and returns the /// new message identifier. /// Task AppendAsync( string conversationId, string? parentId, LlmMessage message, ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default); /// /// Loads the linear path from the conversation root to . /// Passing null returns the path to the most-recently-appended leaf. /// Task> LoadPathAsync( string conversationId, string? leafId = null, IExchange? exchange = null, CancellationToken ct = default); /// /// Loads the full tree for the conversation (every branch). Used for /// observability dashboards and eval replays — NOT for hot-path requests. /// Task> LoadTreeAsync( string conversationId, IExchange? exchange = null, CancellationToken ct = default); } /// Queryable metadata that lives on the message node — hoisted from /// the message body so that index-friendly filters (date range, role, /// iteration) can run without scanning the full payload. public sealed class ConversationMessageMeta { /// Wall-clock timestamp the message was appended. public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow; /// Agent iteration index (1-based) that produced the message; 0 for the user prompt. public int Iteration { get; init; } /// Provider id ("openai", "anthropic", ...) — null for non-provider messages. public string? ProviderId { get; init; } /// Model id as resolved at the time of the call. public string? ModelId { get; init; } /// Stop reason for assistant messages. public LlmStopReason? StopReason { get; init; } /// Token usage attributed to this turn. public LlmUsage Usage { get; init; } = LlmUsage.Empty; /// Tool-use id when the message is a tool result. public string? ToolUseId { get; init; } /// /// Effective sampling temperature passed to the provider for the call /// that produced this assistant message; null on user / tool-result rows. /// public double? Temperature { get; init; } /// Effective max-output-tokens cap; null on non-assistant rows. public int? MaxTokens { get; init; } /// Effective top-p value; null on non-assistant rows. public double? TopP { get; init; } /// Prompt-template name resolved at call time (FK into PromptTemplateProps). public string? PromptTemplateName { get; init; } /// Prompt-template version paired with . public string? PromptTemplateVersion { get; init; } /// /// Stable hash of the tool-capabilities set exposed to the model on this /// call. Allows auditors to detect tool-surface drift across runs. /// public string? ToolSetHash { get; init; } /// /// Opaque provider-side fingerprint identifying the backend configuration /// that served the call (OpenAI's system_fingerprint). Null when the /// provider does not surface one. /// public string? ProviderSystemFingerprint { get; init; } /// /// Stable identifier of the principal that initiated the agent turn that /// produced this row. The same value is stamped on every row of the turn /// (system / user / tool / assistant) so audit queries always have a /// consistent subject. Captured pre-call; null when no principal is wired. /// public string? UserId { get; init; } /// /// Free-form audit tags captured pre-call from the fluent /// .Audit(k,v) builder and / or llm.audit.<name> headers. /// The same snapshot is stamped on every row of the turn. Null / empty /// when no tags are wired. /// public IReadOnlyDictionary? AuditTags { get; init; } /// /// Connection-factory alias used for this call (LlmConnectionFactory.Name) — /// the operator-chosen profile name. Audits the *intent* on top of /// / . /// public string? FactoryName { get; init; } /// /// Effective base URL set on the connection factory. Null when the /// factory used the provider's built-in default endpoint. /// public string? BaseUrl { get; init; } /// /// Provider-issued response identifier (top-level id on /// OpenAI / Anthropic / xAI / Together). Null on non-assistant rows. /// public string? ProviderResponseId { get; init; } /// /// Wall-clock time (milliseconds) the provider spent producing the /// assistant turn this row belongs to. Null on non-assistant rows. /// public long? LatencyMs { get; init; } /// /// Stable, non-secret fingerprint of the API key used for the call — /// SHA-256 of the key, first 16 hex chars. Null when the factory exposes /// no ApiKey. /// public string? ApiKeyFingerprint { get; init; } /// /// How many times the route framework retried the inbound exchange before /// the call succeeded. Read from /// exchange.Properties["RetryAttempt"] (set by /// RetryProcessor) with fallbacks to /// exchange.In.Headers["CamelRedeliveryCounter"] /// (OnExceptionProcessor) and /// exchange.In.Headers["CamelDeadLetterRedeliveryCount"] /// (DeadLetterProcessor). Null on first / only delivery. /// public int? RetryCount { get; init; } } /// A persisted conversation message with its tree placement and metadata. public sealed class ConversationMessage { /// Store-assigned message id. public required string Id { get; init; } /// Parent message id; null for the root. public string? ParentId { get; init; } /// Conversation this message belongs to. public required string ConversationId { get; init; } /// Persisted message payload. public required LlmMessage Message { get; init; } /// Metadata captured at append time. public required ConversationMessageMeta Meta { get; init; } } /// /// In-memory conversation store — suitable for unit tests and demos. /// Replace with the redb-backed implementation in redb.Route.Llm.Storage.Redb. /// public sealed class InMemoryConversationStore : IConversationStore { private readonly ConcurrentDictionary> _byConversation = new(); /// public Task AppendAsync(string conversationId, string? parentId, LlmMessage message, ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default) { var id = Guid.NewGuid().ToString("N"); var node = new ConversationMessage { Id = id, ParentId = parentId, ConversationId = conversationId, Message = message, Meta = meta }; var bucket = _byConversation.GetOrAdd(conversationId, _ => new List()); lock (bucket) bucket.Add(node); return Task.FromResult(id); } /// public Task> LoadPathAsync(string conversationId, string? leafId = null, IExchange? exchange = null, CancellationToken ct = default) { if (!_byConversation.TryGetValue(conversationId, out var bucket)) return Task.FromResult>([]); ConversationMessage[] snapshot; lock (bucket) snapshot = bucket.ToArray(); var leaf = leafId is null ? snapshot.LastOrDefault() : snapshot.FirstOrDefault(m => m.Id == leafId); if (leaf is null) return Task.FromResult>([]); var byId = snapshot.ToDictionary(m => m.Id); var path = new List(); var cursor = leaf; while (cursor is not null) { path.Add(cursor); cursor = cursor.ParentId is { } pid && byId.TryGetValue(pid, out var parent) ? parent : null; } path.Reverse(); return Task.FromResult>(path); } /// public Task> LoadTreeAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default) { if (!_byConversation.TryGetValue(conversationId, out var bucket)) return Task.FromResult>([]); lock (bucket) return Task.FromResult>(bucket.ToArray()); } } Path: redb-route/redb.Route.Llm/Engine/Storage/ICostBudgetStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/ICostBudgetStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Governance; namespace redb.Route.Llm.Engine.Storage; /// /// Persists running cost / token usage per conversation so that an /// implementation can enforce budgets across multiple agent runs /// (not just within one). /// /// is that consumer: AddRedbLlmStorage() registers it in /// place of the shipped per-run defaults, and it reads this store before each run and adds to it after /// each iteration. Implementations must be safe for concurrent updates. /// /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange) using the named-redb /// hint stored in . In-memory implementations /// ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface ICostBudgetStore { /// Returns the running total for the conversation, or when unknown. ValueTask GetUsageAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default); /// Atomically adds the iteration usage to the running total and returns the updated total. ValueTask AddAsync(string conversationId, AgentUsage delta, IExchange? exchange = null, CancellationToken ct = default); /// Resets the running total — used after a billing period rollover or by tests. ValueTask ResetAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default); } /// In-memory cost/token store. Replace with the redb-backed implementation in production. public sealed class InMemoryCostBudgetStore : ICostBudgetStore { private readonly ConcurrentDictionary _totals = new(StringComparer.Ordinal); /// public ValueTask GetUsageAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default) => ValueTask.FromResult(_totals.TryGetValue(conversationId, out var u) ? u : AgentUsage.Zero); /// public ValueTask AddAsync(string conversationId, AgentUsage delta, IExchange? exchange = null, CancellationToken ct = default) { var updated = _totals.AddOrUpdate(conversationId, delta, (_, current) => current.Add(delta)); return ValueTask.FromResult(updated); } /// public ValueTask ResetAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default) { _totals.TryRemove(conversationId, out _); return ValueTask.CompletedTask; } } Path: redb-route/redb.Route.Llm/Engine/Storage/IEvalRunStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IEvalRunStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Governance; namespace redb.Route.Llm.Engine.Storage; /// /// Persists the outcome of a recorded evaluation run. Used by the eval harness /// to track regression scores between agent / prompt / model versions. /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange). In-memory /// implementations ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IEvalRunStore { /// Persists a completed evaluation run. Task SaveAsync(EvalRunRecord record, IExchange? exchange = null, CancellationToken ct = default); /// /// Persists many evaluation runs at once. Bulk-friendly stores commit the /// whole set in a single transaction; the default falls back to a loop. /// async Task SaveManyAsync(IEnumerable records, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(records); foreach (var record in records) { ct.ThrowIfCancellationRequested(); await SaveAsync(record, exchange, ct).ConfigureAwait(false); } } /// Loads a single run by its identifier. Task GetAsync(string runId, IExchange? exchange = null, CancellationToken ct = default); /// /// Lists runs filtered by scenario name. Returns newest first. /// Task> ListAsync(string? scenario = null, int take = 50, IExchange? exchange = null, CancellationToken ct = default); } /// An evaluation run snapshot. public sealed class EvalRunRecord { /// Identifier assigned by the eval harness. public required string RunId { get; init; } /// Scenario name (e.g. "summarize-pr", "sql-rag"). public required string Scenario { get; init; } /// Agent / prompt / model fingerprint that produced the run. public required string AgentFingerprint { get; init; } /// Aggregate score in [0.0, 1.0]; null when not scored. public double? Score { get; init; } /// Total usage observed across the run. public AgentUsage TotalUsage { get; init; } = AgentUsage.Zero; /// Per-iteration metrics — empty when the harness did not record per-iteration data. public IReadOnlyList Iterations { get; init; } = []; /// Custom scoring dimensions (e.g. "accuracy" = 0.92). public IReadOnlyDictionary? Dimensions { get; init; } /// Fixture identifiers / version hashes consumed by the run. public IReadOnlyDictionary? Fixtures { get; init; } /// Wall-clock timestamp the record was created. public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow; } /// Per-iteration metric inside an . public sealed class EvalIterationRecord { /// 1-based iteration index within the run. public int Iteration { get; init; } /// Input tokens consumed by this iteration. public int InputTokens { get; init; } /// Output tokens produced by this iteration. public int OutputTokens { get; init; } /// Wall-clock duration of the iteration in milliseconds. public int DurationMs { get; init; } /// Per-iteration score in [0.0, 1.0]; null when not scored. public double? Score { get; init; } /// Optional free-form note (judge rationale, failure tag, etc.). public string? Notes { get; init; } } /// In-memory eval run store — used by unit tests; production swaps in the redb implementation. public sealed class InMemoryEvalRunStore : IEvalRunStore { private readonly ConcurrentDictionary _records = new(StringComparer.Ordinal); /// public Task SaveAsync(EvalRunRecord record, IExchange? exchange = null, CancellationToken ct = default) { _records[record.RunId] = record; return Task.CompletedTask; } /// public Task GetAsync(string runId, IExchange? exchange = null, CancellationToken ct = default) => Task.FromResult(_records.TryGetValue(runId, out var rec) ? rec : null); /// public Task> ListAsync(string? scenario = null, int take = 50, IExchange? exchange = null, CancellationToken ct = default) { IEnumerable q = _records.Values; if (scenario is not null) q = q.Where(r => string.Equals(r.Scenario, scenario, StringComparison.Ordinal)); var result = q.OrderByDescending(r => r.CreatedAtUtc).Take(take).ToArray(); return Task.FromResult>(result); } } Path: redb-route/redb.Route.Llm/Engine/Storage/IKnowledgeStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IKnowledgeStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Llm.Engine.Storage; /// /// Persists embedding-backed knowledge chunks for retrieval-augmented agent /// runs. The MVP contract is intentionally narrow — upsert + cosine-similarity /// query over an opaque vector. Providers that index the chunks separately /// (e.g. pgvector, Qdrant) wrap this interface. /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange). In-memory /// implementations ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IKnowledgeStore { /// Persists or replaces a chunk by its . Task UpsertAsync(KnowledgeChunk chunk, IExchange? exchange = null, CancellationToken ct = default); /// /// Persists or replaces many chunks at once. Bulk-friendly stores commit /// the whole set in a single transaction — orders of magnitude faster than /// looping . The default implementation falls back /// to a sequential loop for stores that have no bulk path. /// async Task UpsertManyAsync(IEnumerable chunks, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(chunks); foreach (var chunk in chunks) { ct.ThrowIfCancellationRequested(); await UpsertAsync(chunk, exchange, ct).ConfigureAwait(false); } } /// Drops a chunk by id; no-op when not found. Task DeleteAsync(string chunkId, IExchange? exchange = null, CancellationToken ct = default); /// Returns the most-similar chunks for the query embedding. Task> SearchAsync( ReadOnlyMemory queryEmbedding, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default); /// /// Keyword fallback — returns up to chunks whose text /// contains (case-insensitive substring), ranked by /// occurrence count. For corpora with no embeddings, or callers with no query /// vector (e.g. a small structured rule-set where exact terms beat semantic /// similarity). Backends push the substring filter down (SQL LIKE) and /// rank only the matched set — no full-table scan. /// /// The default implementation throws ; /// stores that can express a substring filter override it. Adding this as a /// default member keeps the interface source-compatible for existing /// implementers. /// /// Task> SearchTextAsync( string query, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) => throw new NotSupportedException( $"{GetType().Name} does not support keyword search; supply a query embedding and call SearchAsync."); } /// A single embedded knowledge chunk. public sealed class KnowledgeChunk { /// Stable identifier — caller-supplied so updates can replace a chunk in place. public required string Id { get; init; } /// Optional collection / namespace partition (e.g. tenant id, document set). public string? Collection { get; init; } /// Original chunk text shown to the model when the chunk is retrieved. public required string Text { get; init; } /// Embedding vector; dimensionality is implementation-defined. public required ReadOnlyMemory Embedding { get; init; } /// Optional structured metadata (JSON) — e.g. source URL, page number. public string? MetadataJson { get; init; } /// Wall-clock timestamp the chunk was last upserted. public DateTime UpdatedAtUtc { get; init; } = DateTime.UtcNow; } /// A chunk returned by , with score. public sealed record KnowledgeSearchResult(KnowledgeChunk Chunk, double Score); /// /// In-memory knowledge store — does an O(N) cosine-similarity scan on every /// query. Suitable for unit tests and small fixtures only; swap in the /// production store for anything larger than a few thousand chunks. /// public sealed class InMemoryKnowledgeStore : IKnowledgeStore { private readonly ConcurrentDictionary _chunks = new(StringComparer.Ordinal); /// public Task UpsertAsync(KnowledgeChunk chunk, IExchange? exchange = null, CancellationToken ct = default) { _chunks[chunk.Id] = chunk; return Task.CompletedTask; } /// public Task DeleteAsync(string chunkId, IExchange? exchange = null, CancellationToken ct = default) { _chunks.TryRemove(chunkId, out _); return Task.CompletedTask; } /// public Task> SearchAsync( ReadOnlyMemory queryEmbedding, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) { var query = queryEmbedding.Span; var ranked = new List(); foreach (var chunk in _chunks.Values) { if (collection is not null && !string.Equals(chunk.Collection, collection, StringComparison.Ordinal)) continue; var score = CosineSimilarity(query, chunk.Embedding.Span); ranked.Add(new KnowledgeSearchResult(chunk, score)); } var top = ranked.OrderByDescending(r => r.Score).Take(Math.Max(1, topK)).ToArray(); return Task.FromResult>(top); } /// public Task> SearchTextAsync( string query, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(query)) return Task.FromResult>([]); var ranked = new List(); foreach (var chunk in _chunks.Values) { if (collection is not null && !string.Equals(chunk.Collection, collection, StringComparison.Ordinal)) continue; var score = KnowledgeTextMatch.CountOccurrences(chunk.Text, query); if (score == 0) continue; ranked.Add(new KnowledgeSearchResult(chunk, score)); } var top = ranked.OrderByDescending(r => r.Score).Take(Math.Max(1, topK)).ToArray(); return Task.FromResult>(top); } private static double CosineSimilarity(ReadOnlySpan a, ReadOnlySpan b) { var len = Math.Min(a.Length, b.Length); if (len == 0) return 0d; double dot = 0, na = 0, nb = 0; for (var i = 0; i < len; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; } var denom = Math.Sqrt(na) * Math.Sqrt(nb); return denom <= 0 ? 0d : dot / denom; } } /// Shared keyword-match scoring for implementations. internal static class KnowledgeTextMatch { /// Case-insensitive count of non-overlapping occurrences in . public static int CountOccurrences(string? haystack, string? needle) { if (string.IsNullOrEmpty(haystack) || string.IsNullOrEmpty(needle)) return 0; var count = 0; var i = 0; while ((i = haystack.IndexOf(needle, i, StringComparison.OrdinalIgnoreCase)) >= 0) { count++; i += needle.Length; } return count; } } Path: redb-route/redb.Route.Llm/Engine/Storage/IPromptTemplateRegistry.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IPromptTemplateRegistry.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Llm.Engine.Storage; /// /// Resolves a named prompt template into the actual system / user text the /// engine should send to the provider. Versioning is required so that a /// recorded eval run can be replayed against the exact template that produced it. /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange). In-memory /// implementations ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IPromptTemplateRegistry { /// /// Returns the requested template. When is null, /// the latest version is returned. /// Task GetAsync(string name, string? version = null, IExchange? exchange = null, CancellationToken ct = default); /// Registers or updates a template version. Task SetAsync(PromptTemplate template, IExchange? exchange = null, CancellationToken ct = default); /// Enumerates every version of every template — used for tooling. Task> ListAsync(IExchange? exchange = null, CancellationToken ct = default); } /// A versioned prompt template. public sealed class PromptTemplate { /// Stable template name (free of versioning). public required string Name { get; init; } /// Version string (semver, hash, or monotonically-increasing tag). public required string Version { get; init; } /// Template body — placeholder substitution is the caller's responsibility. public required string Body { get; init; } /// Optional human description. public string? Description { get; init; } /// Wall-clock timestamp the version was registered. public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow; } /// In-memory registry — registered templates live only for the process lifetime. public sealed class InMemoryPromptTemplateRegistry : IPromptTemplateRegistry { private readonly ConcurrentDictionary _templates = new(StringComparer.Ordinal); /// public Task GetAsync(string name, string? version = null, IExchange? exchange = null, CancellationToken ct = default) { if (version is not null) { return Task.FromResult(_templates.TryGetValue(Key(name, version), out var exact) ? exact : null); } var latest = _templates.Values .Where(t => string.Equals(t.Name, name, StringComparison.Ordinal)) .OrderByDescending(t => t.CreatedAtUtc) .FirstOrDefault(); return Task.FromResult(latest); } /// public Task SetAsync(PromptTemplate template, IExchange? exchange = null, CancellationToken ct = default) { _templates[Key(template.Name, template.Version)] = template; return Task.CompletedTask; } /// public Task> ListAsync(IExchange? exchange = null, CancellationToken ct = default) => Task.FromResult>(_templates.Values.ToArray()); private static string Key(string name, string version) => $"{name}@{version}"; } Path: redb-route/redb.Route.Llm/Engine/Storage/IToolCacheStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IToolCacheStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Llm.Engine.Storage; /// /// Caches deterministic / read-only tool outputs by a content-hash key so repeated calls can skip /// the underlying work: inside one run for ToolCachingPolicy.Memoize (served in process, /// never through this store) and across runs for ToolCachingPolicy.Persist. /// /// The agent loop consults this store for Persist tools, after approval and before the /// idempotency store: a hit means "this exact input already produced this output", which is cheaper /// than asking "was this tool_use already executed?", and it is reported to observers as a skipped /// invocation with SkipReason = "cache_hit". Only read-only tools may declare a caching /// policy — a cached entry suppresses the side effect it stands for, so the route build rejects /// Caching != None on a mutating tool. /// /// /// An output the redaction filter changed is never stored: persisting the raw body would keep /// redaction-bypassing content in the store, and persisting the redacted body would hand the model /// different data on a hit than on a miss. /// /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange). In-memory /// implementations ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// /// A store does not report metrics. Hit/miss counters belong to the agent loop, which is the /// only layer that sees both this store and the run-scoped memo; a store that counted as well would /// count every persisted read twice. /// /// public interface IToolCacheStore { /// Returns the cached output for , or null on a miss. ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default); /// Stores the cached output and (optionally) sets a relative time-to-live. ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default); /// Drops every entry — used by tests. ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default); } /// In-memory tool cache. TTL is honoured lazily — entries are dropped on read. public sealed class InMemoryToolCacheStore : IToolCacheStore { private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); /// public ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default) { if (!_entries.TryGetValue(cacheKey, out var entry)) return ValueTask.FromResult(null); if (entry.ExpiresAtUtc is { } exp && exp <= DateTime.UtcNow) { _entries.TryRemove(cacheKey, out _); return ValueTask.FromResult(null); } return ValueTask.FromResult(entry.OutputJson); } /// public ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default) { var expires = ttl is { } t && t > TimeSpan.Zero ? DateTime.UtcNow.Add(t) : (DateTime?)null; _entries[cacheKey] = new Entry(outputJson, expires); return ValueTask.CompletedTask; } /// public ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default) { _entries.Clear(); return ValueTask.CompletedTask; } private readonly record struct Entry(string OutputJson, DateTime? ExpiresAtUtc); } Path: redb-route/redb.Route.Llm/Engine/Storage/IToolIdempotencyStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IToolIdempotencyStore.cs ---- using redb.Route.Abstractions; namespace redb.Route.Llm.Engine.Storage; /// /// Tracks tool invocations so that retried or duplicated tool calls produce a /// single side effect. The contract is intentionally a thin wrapper over /// — the redb-backed implementation reuses /// the existing IdempotentEntryProps table to avoid duplicating schema. /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange). In-memory /// implementations ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IToolIdempotencyStore { /// /// Attempts to reserve for the given conversation. /// Returns the cached result on a duplicate, or /// when the caller should execute the tool and finalize via . /// Task TryReserveAsync( string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default); /// Persists the tool output JSON for the previously-reserved key. Task CompleteAsync( string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default); /// Releases the reservation on failure so a retry can re-run the tool. Task ReleaseAsync( string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default); } /// Outcome of . public sealed class ToolIdempotencyReservation { /// True when this caller owns the reservation and must execute the tool. public required bool IsNew { get; init; } /// Cached output JSON when is false and the prior call completed. public string? CachedOutputJson { get; init; } /// Sentinel reservation indicating the caller must execute the tool. public static readonly ToolIdempotencyReservation NewReservation = new() { IsNew = true }; /// Builds a hit reservation that returns the previously-recorded output. public static ToolIdempotencyReservation Hit(string outputJson) => new() { IsNew = false, CachedOutputJson = outputJson }; } /// /// In-memory idempotency store backed by a thin /// composition — the registered repository handles the dedup key, an internal /// dictionary remembers the cached output. /// /// With a ttl, a completed call is forgotten that long after it completed: its key leaves the repository and /// its output leaves the store, lazily, on a later reservation (no timer). A reservation still in flight (reserved, /// neither completed nor released) is never aged out, so a second run of the same call cannot start while the first is /// still running, however long it takes. Without a ttl nothing expires. /// /// public sealed class InMemoryToolIdempotencyStore : IToolIdempotencyStore { private sealed record Completed(string OutputJson, DateTimeOffset At); private readonly IIdempotentRepository _repository; private readonly TimeSpan? _ttl; private readonly TimeProvider _time; private readonly System.Collections.Concurrent.ConcurrentDictionary _outputs = new(StringComparer.Ordinal); /// Creates a store over the given idempotency repository. /// Keeps the reservation keys. /// How long a completed call is remembered after it completed; null keeps it for the life of the store. /// The clock the ttl is measured with; by default. public InMemoryToolIdempotencyStore(IIdempotentRepository repository, TimeSpan? ttl = null, TimeProvider? time = null) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); if (ttl is { } t && t <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl), ttl, "The ttl must be positive."); _ttl = ttl; _time = time ?? TimeProvider.System; } /// public async Task TryReserveAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { if (_ttl is { } ttl) await EvictCompletedBeforeAsync(_time.GetUtcNow() - ttl, ct).ConfigureAwait(false); var key = BuildKey(conversationId, toolUseId); var added = await _repository.Add(key, ct).ConfigureAwait(false); if (added) return ToolIdempotencyReservation.NewReservation; return _outputs.TryGetValue(key, out var cached) ? ToolIdempotencyReservation.Hit(cached.OutputJson) : ToolIdempotencyReservation.Hit("{}"); } /// public async Task CompleteAsync(string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default) { var key = BuildKey(conversationId, toolUseId); _outputs[key] = new Completed(outputJson, _time.GetUtcNow()); await _repository.Confirm(key, ct).ConfigureAwait(false); } /// public async Task ReleaseAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = BuildKey(conversationId, toolUseId); _outputs.TryRemove(key, out _); await _repository.Remove(key, ct).ConfigureAwait(false); } /// /// Forgets every call completed before : the key first, so a concurrent reservation either /// still finds key and output or starts afresh, never a key without its output; then exactly the output that was /// read, so an output a new run of the same call wrote in between stays. /// private async Task EvictCompletedBeforeAsync(DateTimeOffset cutoff, CancellationToken ct) { foreach (var entry in _outputs) { if (entry.Value.At >= cutoff) continue; await _repository.Remove(entry.Key, ct).ConfigureAwait(false); _outputs.TryRemove(entry); } } private static string BuildKey(string conversationId, string toolUseId) => $"llm-tool:{conversationId}:{toolUseId}"; } Path: redb-route/redb.Route.Llm/Engine/ToolHeaderPolicy.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/ToolHeaderPolicy.cs ---- namespace redb.Route.Llm.Engine; /// /// Decides which headers of the agent's exchange are visible to a tool route. /// /// The policy is default-deny: a tool never sees the raw inbound header set /// (an HTTP consumer's Authorization / Cookie must not leak into every /// tool call just because the tool is mounted on the same host). Only /// , the run's resolved principal / audit tags, and the /// names the route author opted into via /// AgentRequest.PropagateToolHeaders are copied. /// /// /// Principal and audit tags are propagated as resolved values, not as raw headers. /// LlmProducer resolves the principal from the ?user= option first /// (including its ${header.X} expression form) and only falls back to the /// llm.user.id header; copying the header alone would silently drop the /// option-driven case. Same for ?audit= tags. The raw headers are used as a /// fallback so an engine driven without LlmProducer still propagates them. /// /// /// Trust model: llm.user.id and llm.audit.* are read off the /// inbound exchange by the producer, so a transport that forwards client headers /// verbatim (a plain HTTP consumer) lets the caller set them. That is already true /// for what the engine persists in MessageProps.UserId; propagating the same /// value to tools does not widen it. The route — not this policy — is responsible /// for stripping or overwriting client-supplied llm.* headers before the /// llm:// hop when tools make access decisions on them. /// /// public static class ToolHeaderPolicy { /// /// Headers copied from the agent exchange to every tool call without opt-in: /// the conversation id and the two correlation-id spellings the framework /// already treats as ambient. /// public static readonly IReadOnlyList DefaultHeaders = [ LlmHeaders.ConversationId, "X-Correlation-Id", "CorrelationId" ]; /// /// Fills with the headers a tool route is allowed to see /// for this run. Existing entries in (the engine's own /// llm.tool.* stamps) are never overwritten by propagation. /// /// The agent run — source of the parent exchange, resolved principal, audit tags and opt-in list. /// Header dictionary of the tool message being built. public static void Apply(AgentRequest request, IDictionary target) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(target); var source = request.Exchange.In?.Headers; foreach (var name in DefaultHeaders) Copy(source, target, name); // Principal: resolved value wins over the raw header (see class remarks). if (!string.IsNullOrEmpty(request.UserId)) target[LlmHeaders.UserId] = request.UserId; else Copy(source, target, LlmHeaders.UserId); // Audit tags: same rule — resolved snapshot first, raw llm.audit.* as fallback. if (request.AuditTags is { Count: > 0 }) { foreach (var tag in request.AuditTags) target[LlmHeaders.AuditTagPrefix + tag.Key] = tag.Value; } else { CopyByPrefix(source, target, LlmHeaders.AuditTagPrefix); } if (request.PropagateToolHeaders is not { Count: > 0 } optIn) return; foreach (var pattern in optIn) { if (string.IsNullOrWhiteSpace(pattern)) continue; if (pattern.Length > 1 && pattern[^1] == '*') CopyByPrefix(source, target, pattern[..^1]); else Copy(source, target, pattern); } } private static void Copy(IDictionary? from, IDictionary to, string key) { if (from is null) return; if (from.TryGetValue(key, out var v) && v is not null) to[key] = v; } private static void CopyByPrefix(IDictionary? from, IDictionary to, string prefix) { if (from is null || prefix.Length == 0) return; foreach (var kv in from) { if (kv.Value is null) continue; if (!kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; to[kv.Key] = kv.Value; } } /// /// Parses the CSV form used by the endpoint URI /// (?propagateToolHeaders=x-tenant-id,x-app-*) into a name list. /// Returns null for null/empty input so callers can leave the field unset. /// /// Comma-separated header names; a trailing * marks a prefix match. public static IReadOnlyList? ParseCsv(string? csv) { if (string.IsNullOrWhiteSpace(csv)) return null; var names = new List(); foreach (var raw in csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { var name = System.Web.HttpUtility.UrlDecode(raw).Trim(); if (name.Length > 0) names.Add(name); } return names.Count == 0 ? null : names; } } Path: redb-route/redb.Route.Llm/Expressions/LlmExpressionContexts.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Expressions/LlmExpressionContexts.cs ---- using redb.Route.Llm.Providers; namespace redb.Route.Llm.Expressions; /// /// Snapshot of the current conversation visible to the /// ${conversation.*} expression family. Set by /// on the parent exchange under /// the well-known key . /// public sealed class LlmConversationContext { /// Conversation identifier (matches AgentRequest.ConversationId). public string? Id { get; init; } /// Number of messages in the transcript so far (includes the seeding user message). public int MessageCount { get; init; } /// Aggregate token usage across the current run. public LlmUsage Tokens { get; init; } = LlmUsage.Empty; /// Number of completed tool-loop iterations. public int Iterations { get; init; } /// Latest assistant message in the transcript (null before the first model response). public LlmMessage? LastMessage { get; init; } } /// /// Snapshot of the tool currently being dispatched, visible to the /// ${tool.*} expression family. Set by /// on the parent exchange under /// the well-known key . /// public sealed class LlmToolContext { /// Tool name as declared in the tool_use block. public string Name { get; init; } = string.Empty; /// Provider-issued tool use id (correlates the call to its result block). public string ToolUseId { get; init; } = string.Empty; /// Raw JSON input passed to the tool. public string InputJson { get; init; } = "{}"; /// Raw JSON output produced by the tool. Null while the tool is in flight. public string? ResultJson { get; init; } /// Wall-clock execution duration. while in flight. public System.TimeSpan Duration { get; init; } } /// Well-known exchange property keys used by the LLM expression integration. public static class LlmExpressionKeys { /// Exchange property holding the current . public const string Conversation = "llm.conversation"; /// Exchange property holding the current . public const string Tool = "llm.tool"; } Path: redb-route/redb.Route.Llm/Expressions/LlmExpressionResolverSetup.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Expressions/LlmExpressionResolverSetup.cs ---- using System; using System.Reflection; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Llm.Expressions; /// /// Registers ${conversation.*} and ${tool.*} resolvers with /// . The resolvers read the well-known /// exchange properties published by /// (, ) /// and walk the requested path via reflection — so adding fields to /// / /// automatically makes them available in templates. /// public static class LlmExpressionResolverSetup { private static int _initialized; /// /// Idempotently registers the LLM prefix resolvers. Safe to call from /// every host's composition root — subsequent calls are no-ops. /// public static void EnsureRegistered() { if (System.Threading.Interlocked.CompareExchange(ref _initialized, 1, 0) != 0) return; ExpressionResolver.RegisterPrefixResolver("conversation.", (exchange, path) => ResolvePath(exchange.getProperty(LlmExpressionKeys.Conversation), path)); ExpressionResolver.RegisterPrefixResolver("tool.", (exchange, path) => ResolvePath(exchange.getProperty(LlmExpressionKeys.Tool), path)); } private static object? ResolvePath(object? root, string path) { if (root is null || string.IsNullOrEmpty(path)) return root; var current = root; foreach (var part in path.Split('.', StringSplitOptions.RemoveEmptyEntries)) { if (current is null) return null; var type = current.GetType(); var prop = type.GetProperty(part, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); if (prop is not null) { current = prop.GetValue(current); continue; } var field = type.GetField(part, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); if (field is not null) { current = field.GetValue(current); continue; } return null; } return current; } } Path: redb-route/redb.Route.Llm/Extensions/LlmRouteDefinitionExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Extensions/LlmRouteDefinitionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Extensions; /// /// Inline LLM step for . Pure syntactic sugar over /// .Process(Func<IExchange, CancellationToken, Task>) — every option here /// translates into a single in-memory call to . /// /// Use this when the LLM step is an inline transformation in a route, instead of /// going through a To("llm://...") endpoint. The endpoint form is preferred /// for routes that mix transports (e.g. kafka → llm → sql); the inline form /// is preferred for one-off prompts that don't need a registered factory. /// /// public static class LlmRouteDefinitionExtensions { /// /// Inline LLM step. Reads the user message from exchange.In.Body, runs the /// agent engine, writes the assistant text to exchange.Out.Body. /// /// Route definition. /// Name of the registered . /// Optional per-call options. public static IRouteDefinition Llm( this IRouteDefinition route, string connectionFactoryName, Action? configure = null) { ArgumentNullException.ThrowIfNull(route); ArgumentException.ThrowIfNullOrWhiteSpace(connectionFactoryName); var builder = new LlmCallBuilder(); configure?.Invoke(builder); return route.Process(async (exchange, ct) => { var sp = exchange.ServiceProvider ?? throw new InvalidOperationException( "Inline .Llm(...) requires an IServiceProvider on the exchange. " + "Ensure the route is hosted by RouteHostedService or call AddRedbRouteLlm() in DI."); var context = sp.GetService() ?? throw new InvalidOperationException( "Inline .Llm(...) requires an IRouteContext in DI."); var factory = context.GetFromRegistry(connectionFactoryName) ?? throw new InvalidOperationException( $"LlmConnectionFactory '{connectionFactoryName}' is not registered. " + "Register via context.AddToRegistry(name, factory)."); // Same wiring as the container: a naked engine here would lack the producer template (so every // tool call would fail) and every governance seam — the route would look healthy and do less. // FindRegistered covers the container too: AddRedbRouteLlm() registers the engine there. var engine = AgentEngine.FindRegistered(context) ?? AgentEngine.FromContext(context); var registry = context.GetService(); var userContent = builder.UserContentFactory is { } ucf ? ucf(exchange) : DefaultUserContent(exchange); var tools = builder.ResolveTools(registry); var conversationId = builder.ConversationId ?? (builder.ConversationHeaderName is { } hdr ? exchange.In.Headers.TryGetValue(hdr, out var v) ? v?.ToString() : null : null); var request = new AgentRequest { Factory = factory, Exchange = exchange, UserContent = userContent, SystemPrompt = builder.SystemPrompt, Tools = tools, ConversationId = conversationId, MaxIterations = builder.MaxIterations, Budget = AgentBudgetFactory.From( builder.BudgetInputTokens, builder.BudgetOutputTokens, builder.BudgetCostUsd), Temperature = builder.Temperature, MaxTokens = builder.MaxTokens, PropagateToolHeaders = builder.PropagateToolHeaders.Count > 0 ? builder.PropagateToolHeaders : null }; var response = await engine.RunAsync(request, ct).ConfigureAwait(false); exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = response.Text; exchange.Out.Headers[LlmHeaders.ProviderId] = factory.Provider; exchange.Out.Headers[LlmHeaders.ModelId] = factory.ModelId; exchange.Out.Headers[LlmHeaders.TokensIn] = response.Usage.InputTokens; exchange.Out.Headers[LlmHeaders.TokensOut] = response.Usage.OutputTokens; exchange.Out.Headers[LlmHeaders.CacheWriteTokens] = response.Usage.CacheCreationInputTokens; exchange.Out.Headers[LlmHeaders.CacheReadTokens] = response.Usage.CacheReadInputTokens; exchange.Out.Headers[LlmHeaders.ToolIterations] = response.Iterations; exchange.Out.Headers[LlmHeaders.StopReason] = response.StopReason.ToString(); }); } private static IReadOnlyList DefaultUserContent(IExchange exchange) { var text = exchange.In.Body switch { null => string.Empty, string s => s, var x => x.ToString() ?? string.Empty }; return [new LlmTextBlock(text)]; } } /// Builder for the inline step. public sealed class LlmCallBuilder { /// System prompt for this call. public string? SystemPrompt { get; set; } /// Per-call temperature override. public double? Temperature { get; set; } /// Per-call max-tokens override. public int? MaxTokens { get; set; } /// Conversation id (when conversation tracking is on). public string? ConversationId { get; set; } /// /// When set, conversation id is read from this header on the incoming /// exchange (only used when is null). /// public string? ConversationHeaderName { get; set; } /// Maximum tool-loop iterations. public int MaxIterations { get; set; } = 8; /// Per-run input-token ceiling (summed across iterations). Null = no ceiling. public int? BudgetInputTokens { get; set; } /// Per-run output-token ceiling (summed across iterations). Null = no ceiling. public int? BudgetOutputTokens { get; set; } /// Per-run cost ceiling in USD. Null = no ceiling. Needs an /// that can price the model. public decimal? BudgetCostUsd { get; set; } /// Tools available for this call. Empty when no opt-in was made. public List Tools { get; } = []; /// Tool names to resolve from the registry at dispatch time. public List ToolNames { get; } = []; /// When true, every descriptor in the registry is exposed for this call. public bool UseAllTools { get; set; } /// /// Extra header names propagated from the exchange to every tool call /// (trailing * = prefix match). Default-deny — see /// . /// public List PropagateToolHeaders { get; } = []; /// /// Optional factory for the initial user content. When null, the body of /// exchange.In is wrapped in a single . /// public Func>? UserContentFactory { get; set; } /// Sets the system prompt. public LlmCallBuilder WithSystemPrompt(string prompt) { SystemPrompt = prompt; return this; } /// Sets per-call temperature. public LlmCallBuilder WithTemperature(double t) { Temperature = t; return this; } /// Sets per-call max-tokens. public LlmCallBuilder WithMaxTokens(int n) { MaxTokens = n; return this; } /// Sets max tool-loop iterations. public LlmCallBuilder WithMaxIterations(int n) { MaxIterations = n; return this; } /// /// Sets the per-run budget. Only the dimensions you pass are limited; the cost ceiling requires a /// registered — without one the run /// fails fast instead of silently enforcing a zero cost ceiling. /// public LlmCallBuilder WithBudget(int? inputTokens = null, int? outputTokens = null, decimal? costUsd = null) { BudgetInputTokens = inputTokens; BudgetOutputTokens = outputTokens; BudgetCostUsd = costUsd; return this; } /// Sets the conversation id explicitly. public LlmCallBuilder WithConversation(string id) { ConversationId = id; return this; } /// Reads the conversation id from the named header on the inbound exchange. public LlmCallBuilder WithConversationFromHeader(string headerName) { ArgumentException.ThrowIfNullOrWhiteSpace(headerName); ConversationHeaderName = headerName; return this; } /// Adds a tool to this call by descriptor instance. public LlmCallBuilder WithTool(ILlmToolDescriptor tool) { Tools.Add(tool); return this; } /// Adds multiple tools at once by descriptor instance. public LlmCallBuilder WithTools(params ILlmToolDescriptor[] tools) { ArgumentNullException.ThrowIfNull(tools); Tools.AddRange(tools); return this; } /// Resolves tools by name from the global registry at dispatch time. public LlmCallBuilder UseTools(params string[] names) { ArgumentNullException.ThrowIfNull(names); ToolNames.AddRange(names); return this; } /// Exposes every descriptor in the global registry to this call. public LlmCallBuilder UseAllRegisteredTools() { UseAllTools = true; return this; } /// /// Opts extra headers into propagation from this exchange to the tool calls of /// this run (trailing * = prefix match). Propagation is default-deny: /// conversation id, correlation ids, resolved principal and resolved audit tags /// travel without opt-in; inbound transport headers never do. /// public LlmCallBuilder WithPropagatedToolHeaders(params string[] names) { ArgumentNullException.ThrowIfNull(names); foreach (var n in names) if (!string.IsNullOrWhiteSpace(n)) PropagateToolHeaders.Add(n.Trim()); return this; } internal IReadOnlyList ResolveTools(IToolDescriptorRegistry? registry) { if (UseAllTools) return registry?.All() ?? []; if (Tools.Count == 0 && ToolNames.Count == 0) return []; if (ToolNames.Count == 0) return Tools; var result = new List(Tools.Count + ToolNames.Count); result.AddRange(Tools); if (registry is not null) { foreach (var name in ToolNames) { var d = registry.Get(name); if (d is not null) result.Add(d); } } return result; } /// /// Overrides the user content with a custom factory. Use for multi-block /// inputs (e.g. text + tool-result continuations). /// public LlmCallBuilder WithUserContent(Func> factory) { ArgumentNullException.ThrowIfNull(factory); UserContentFactory = factory; return this; } } Path: redb-route/redb.Route.Llm/Extensions/ServiceCollectionExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Expressions; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Tools; using redb.Route.Processors; namespace redb.Route.Llm.Extensions; /// /// Extension methods for registering the LLM transport, governance defaults /// and redb-backed storage in a DI container. /// public static class LlmServiceCollectionExtensions { /// /// How long the in-memory tool idempotency store registers remembers a completed /// call: 24 hours. A host that wants another value registers the store itself, /// new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), ttl), before or after the call. /// public static readonly TimeSpan DefaultToolIdempotencyTtl = TimeSpan.FromHours(24); /// /// Registers the LLM component, agent engine, tool registry and no-op /// defaults for every governance dependency. Call /// afterwards to swap the in-memory defaults for redb-backed stores. /// /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteLlm(); /// route.Services.AddRedbLlmStorage(); /// route.Services.AddLlmConnectionFactory("claude", f => /// { /// f.Provider = "anthropic"; /// f.ModelId = "claude-haiku-4.5"; /// f.ApiKeySecretRef = "anthropic.api-key"; /// }); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// /// public static IServiceCollection AddRedbRouteLlm(this IServiceCollection services) { // Register ${conversation.*} / ${tool.*} expression prefix resolvers exactly once. LlmExpressionResolverSetup.EnsureRegistered(); services.AddSingleton(); // The engine is built from the context on purpose: the container's constructor-selection would pick // whatever it can satisfy, and a shorter overload silently yields an engine without a producer // template, claims source or cache — governance that exists only in tests. One factory, one wiring. services.AddSingleton(sp => AgentEngine.FromContext(sp.GetRequiredService())); // Producer template — used by the engine to dispatch tool-bridge endpoints. // Started lazily on first resolution so it is ready before any tool call. services.TryAddSingleton(sp => { var template = new ProducerTemplate(sp.GetRequiredService()); template.Start(); return template; }); // Tool descriptor registry — auto-collects every ILlmToolDescriptor registered // in DI (via AddLlmTool() / services.AddSingleton() / // the .AsLlmTool(...) DSL after route bootstrap). services.AddSingleton(sp => { var registry = new ToolDescriptorRegistry(); foreach (var descriptor in sp.GetServices()) registry.Register(descriptor); return registry; }); // Governance Noop defaults — TryAdd so consumers can swap in real impls. services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); // Claims are checked against the caller the exchange came from (a property, never a header). // TryAdd on purpose: a host with its own identity vocabulary registers its own source instead. services.TryAddSingleton(); // Storage InMemory fallbacks — TryAdd so AddRedbLlmStorage() (or any // custom registration) overrides cleanly, in either call order. The tool // idempotency default keeps its keys and outputs in this process only, and // forgets a completed call 24 hours after it completed. services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(_ => new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), DefaultToolIdempotencyTtl)); // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteComponent(); return services; } /// /// Registers an implementation as a DI singleton. /// The descriptor is automatically picked up by the /// factory registered in . /// public static IServiceCollection AddLlmTool(this IServiceCollection services) where TTool : class, ILlmToolDescriptor { services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); return services; } /// /// Registers an already-constructed instance. /// Useful for descriptors built via RouteToolBridge / LlmTool.Define(...). /// public static IServiceCollection AddLlmTool(this IServiceCollection services, ILlmToolDescriptor descriptor) { ArgumentNullException.ThrowIfNull(descriptor); services.AddSingleton(descriptor); return services; } /// /// Scans for non-abstract /// implementations and registers each as a singleton via . /// public static IServiceCollection AddLlmToolsFromAssemblies( this IServiceCollection services, params System.Reflection.Assembly[] assemblies) { ArgumentNullException.ThrowIfNull(assemblies); foreach (var asm in assemblies) { foreach (var type in asm.GetTypes()) { if (type.IsAbstract || type.IsInterface) continue; if (!typeof(ILlmToolDescriptor).IsAssignableFrom(type)) continue; services.AddSingleton(type); services.AddSingleton(typeof(ILlmToolDescriptor), sp => sp.GetRequiredService(type)); } } return services; } /// /// Scans for class-level and method-level /// declarations and registers a /// descriptor for each one. The caller is /// responsible for mounting the actual route on the produced endpoint URI /// (e.g. From("direct:llm.tools.weather").Process(...)) — this /// helper only exposes descriptors to the model. /// /// The endpoint URI for each tool is built via ; /// when omitted the default is direct:llm.tools.{toolName}. /// /// /// Type to scan. Class-level attribute exposes the type itself /// as one tool; method-level attributes expose each annotated method as a separate tool. /// DI services. /// Optional override. Receives the tool name from the attribute. public static IServiceCollection AddLlmToolsFromType( this IServiceCollection services, Func? endpointUriFactory = null) => AddLlmToolsFromType(services, typeof(T), endpointUriFactory); /// Non-generic overload of . public static IServiceCollection AddLlmToolsFromType( this IServiceCollection services, Type type, Func? endpointUriFactory = null) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(type); endpointUriFactory ??= static name => $"direct:llm.tools.{name}"; var classAttr = (ExposeAsLlmToolAttribute?)Attribute.GetCustomAttribute( type, typeof(ExposeAsLlmToolAttribute), inherit: false); if (classAttr is not null) { services.AddLlmTool(new RouteToolBridge( classAttr.ToCapability(RouteToolBridge.DefaultInputSchema), endpointUriFactory(classAttr.Name))); } const System.Reflection.BindingFlags methodFlags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly; foreach (var method in type.GetMethods(methodFlags)) { var attr = (ExposeAsLlmToolAttribute?)Attribute.GetCustomAttribute( method, typeof(ExposeAsLlmToolAttribute), inherit: false); if (attr is null) continue; services.AddLlmTool(new RouteToolBridge( attr.ToCapability(RouteToolBridge.DefaultInputSchema), endpointUriFactory(attr.Name))); } return services; } /// /// Replaces the in-memory storage fallbacks with redb-backed implementations of /// , , /// , and the /// . Replaces the default /// with the audit observer. /// /// The redb-backed idempotency store keeps the reservation of a tool's idempotency key in the same redb as the /// tool's stored output: the instance an endpoint's ?redb= names, else the default name given here, else /// the context's default redb. Nothing else needs registering. /// /// public static IServiceCollection AddRedbLlmStorage(this IServiceCollection services) => AddRedbLlmStorageCore(services, redbName: null); /// /// with the agent's memory in the named redb instance /// (a Tsak context's named Redb instance, or one registered with /// RegisterRedbService): every store, the tool-call audit and the conversation's accumulated cost go there. /// An endpoint's ?redb= still decides for what that endpoint writes, the reservation of tool idempotency /// keys included: it is kept in that instance, next to the tool's stored output. /// public static IServiceCollection AddRedbLlmStorage(this IServiceCollection services, string redbName) { ArgumentException.ThrowIfNullOrWhiteSpace(redbName); return AddRedbLlmStorageCore(services, redbName); } private static IServiceCollection AddRedbLlmStorageCore(IServiceCollection services, string? redbName) { // Schemes for every props row used below are auto-synced by the host's // own `redb.InitializeAsync()` (it scans loaded assemblies for // [RedbScheme] — see RedbServiceBase.AutoSyncSchemesAsync). The host // owns startup; stores stay free of any "is the scheme there yet?" // gates. services.AddSingleton(sp => new RedbConversationStore(sp.GetRequiredService(), redbName)); services.AddSingleton(sp => new RedbToolIdempotencyStore(sp.GetRequiredService(), redbName)); services.AddSingleton(sp => new RedbApprovalStore(sp.GetRequiredService(), redbName)); services.AddSingleton(sp => new RedbCostBudgetStore(sp.GetRequiredService(), redbName)); services.AddSingleton(sp => new RedbPromptTemplateRegistry(sp.GetRequiredService(), redbName)); services.AddSingleton(sp => new RedbToolResultCache(sp.GetRequiredService(), redbName)); services.AddSingleton(sp => new RedbEvalRunStore(sp.GetRequiredService(), redbName)); services.AddSingleton(sp => new RedbKnowledgeStore(sp.GetRequiredService(), redbName)); services.AddSingleton(sp => new RedbBatchStore(sp.GetRequiredService(), redbName)); // Only the defaults this package ships are replaced — a host's own observer or budget enforcer // is left exactly as registered. Taking a user registration away is what `Replace` used to do // here silently, and the audit observer is not worth breaking someone's governance for. ReplaceShippedDefault(services, sp => new RedbAuditObserver(sp.GetRequiredService(), redbName), typeof(NoopAgentObserver)); // Cross-run budgets arrive with the store: the per-run ceiling is now also checked against the // conversation's accumulated usage, which can stop a run that used to pass. ReplaceShippedDefault(services, sp => new StoreBudgetEnforcer(sp.GetRequiredService()), typeof(NoopBudgetEnforcer), typeof(InMemoryBudgetEnforcer)); return services; } /// /// Replaces a registration only while it still points at one of the defaults this package ships; /// anything a host registered — an instance, a factory or its own type — survives untouched. /// private static void ReplaceShippedDefault( IServiceCollection services, Func factory, params Type[] shippedDefaults) where TService : class { var current = services.LastOrDefault(d => d.ServiceType == typeof(TService)); var isShippedDefault = current?.ImplementationType is { } type && shippedDefaults.Contains(type); if (current is not null && !isShippedDefault) return; services.RemoveAll(); services.AddSingleton(factory); } /// /// Registers a named in the route registry. /// The supplied is set on /// automatically and used as the registry key (matches llm://<name>). /// public static IServiceCollection AddLlmConnectionFactory( this IServiceCollection services, string name, Action configure) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(configure); // One configurator per named factory: each AddLlmConnectionFactory call lands its // own registry entry when RouteHostedService applies the configurators at startup. services.AddRouteContextConfigurator((sp, context) => { var factory = new LlmConnectionFactory { Name = name }; configure(factory); factory.Name = name; // re-assert in case configure overwrote it factory.LoggerFactory ??= sp.GetService(); // for provider diagnostics context.AddToRegistry(name, factory); }); return services; } } Path: redb-route/redb.Route.Llm/Fluent/Llm.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Fluent/Llm.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Llm.Fluent; /// /// Fluent API for LLM endpoints. /// /// .To(Llm.Factory("claude").Temperature(0.2).MaxTokens(1024)) /// .To(Llm.Factory("claude").Tools("*").Stream(LlmStreamMode.Calls)) /// /// public static class Llm { /// Creates an LLM endpoint targeting the named connection factory. public static LlmBuilder Factory(string connectionFactoryName) => new(connectionFactoryName); } /// Fluent builder for LLM endpoint URIs. public sealed class LlmBuilder { private readonly string _factory; private string? _temperature; private string? _maxTokens; private string? _topP; private string? _systemPromptRef; private string? _conversation; private LlmStreamMode _stream; private string? _schedule; private string? _initialBodyRef; private string? _maxIterations; private string? _budgetInputTokens; private string? _budgetOutputTokens; private string? _budgetCostUsd; private bool _cacheSystemPrompt; private string? _tools; private string? _user; private readonly List> _auditTags = []; private readonly List _propagateToolHeaders = []; private string? _promptTemplateName; private string? _promptTemplateVersion; internal LlmBuilder(string factory) { ArgumentException.ThrowIfNullOrWhiteSpace(factory); _factory = factory; } /// Sampling temperature. public LlmBuilder Temperature(double v) { _temperature = v.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Maximum output tokens. public LlmBuilder MaxTokens(int v) { _maxTokens = v.ToString(); return this; } /// Top-p sampling. public LlmBuilder TopP(double v) { _topP = v.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Reference (or literal) for system-prompt template. public LlmBuilder SystemPromptRef(string r) { _systemPromptRef = r; return this; } /// Tracks conversation by reading llm.conversation.id header. public LlmBuilder ConversationFromHeader() { _conversation = "header"; return this; } /// Tracks conversation using the route id as conversation key. public LlmBuilder ConversationFromRoute() { _conversation = "property"; return this; } /// /// Streams the step: — every model call streamed inside the route, tools and /// the route's transaction as without streaming, the pieces to the observer; — /// the text streamed into Out.Body while the model writes it. /// public LlmBuilder Stream(LlmStreamMode mode) { _stream = mode; return this; } /// Schedule for consumer mode (cron or fixed interval). public LlmBuilder Schedule(string s) { _schedule = s; return this; } /// Initial body template for scheduled consumers. public LlmBuilder InitialBody(string bodyRef) { _initialBodyRef = bodyRef; return this; } /// Maximum tool-loop iterations. public LlmBuilder MaxIterations(int n) { _maxIterations = n.ToString(); return this; } /// /// Per-run budget. Only the dimensions you pass reach the URI — an omitted ceiling stays absent, /// because "not set" and "zero" are different states in the URI. /// /// A value of 0 or less means no ceiling for that dimension, exactly as /// AgentBudget.Unbounded does: the enforcer only checks a limit that is positive. To stop a /// route from doing work, take the tool away, require an approval or require a claim — a zero ceiling /// is not a switch, and pretending otherwise would silently do nothing. /// /// /// The cost ceiling needs a registered that can /// price the model; without one the run fails fast rather than pretending to enforce it. /// /// public LlmBuilder Budget(int? inputTokens = null, int? outputTokens = null, decimal? costUsd = null) { if (inputTokens is not null) _budgetInputTokens = inputTokens.Value.ToString(); if (outputTokens is not null) _budgetOutputTokens = outputTokens.Value.ToString(); if (costUsd is not null) _budgetCostUsd = costUsd.Value.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// /// Asks the provider to cache the system prompt across turns /// (). /// Only pays off when the system prompt is byte-stable: caching matches on the /// rendered prefix, so a prompt that varies per request is written and never read back. /// LlmUsage.CacheReadInputTokens is what says it works. /// public LlmBuilder CacheSystemPrompt() { _cacheSystemPrompt = true; return this; } /// /// Tool exposure filter — "*" for every descriptor in the registry, /// or a CSV of tool names (e.g. "get_order,get_invoice"). /// public LlmBuilder Tools(string filter) { _tools = filter; return this; } /// Exposes every descriptor registered in the global tool registry. public LlmBuilder UseAllTools() { _tools = "*"; return this; } /// /// Principal identifier for audit — literal value ("system") or a /// header reference ("${header.X-User-Id}"). The producer resolves /// this expression pre-call against the inbound exchange and stamps the /// resolved value on every persisted row of the run as /// MessageProps.UserId. When unset, LlmHeaders.UserId /// (llm.user.id) is used as a fallback. /// public LlmBuilder User(string expression) { _user = expression; return this; } /// /// Adds one audit tag to the run. may be a literal /// or a ${header.X} expression. The producer resolves the value /// pre-call and stamps the (key, value) pair on every persisted row as /// MessageProps.AuditTags entry. Headers named /// llm.audit.<key> merge on top of these; headers win on /// collision. Repeatable — call once per tag. /// public LlmBuilder Audit(string key, string value) { ArgumentException.ThrowIfNullOrWhiteSpace(key); _auditTags.Add(new KeyValuePair(key, value ?? string.Empty)); return this; } /// /// Opts extra headers into propagation from this exchange to every tool call /// of the run. A trailing * makes an entry a prefix match: /// .PropagateToolHeaders("x-tenant-id", "x-app-*"). /// /// Propagation is default-deny. Without this call a tool route already /// receives the conversation id, both correlation-id spellings, the resolved /// principal (llm.user.id — see ) and the resolved /// audit tags (llm.audit.* — see ). The inbound /// transport's own headers are never forwarded implicitly; name here only /// headers the route itself sets or has sanitized. /// /// Repeatable — names accumulate across calls. /// public LlmBuilder PropagateToolHeaders(params string[] names) { ArgumentNullException.ThrowIfNull(names); foreach (var n in names) if (!string.IsNullOrWhiteSpace(n)) _propagateToolHeaders.Add(n.Trim()); return this; } /// /// Locks the prompt-template (name, version) pair onto every persisted row /// of the run as MessageProps.PromptTemplateName / /// PromptTemplateVersion. Independent of /// — you can carry name/version even when the prompt body comes from /// elsewhere. /// public LlmBuilder PromptTemplate(string name, string version) { _promptTemplateName = name; _promptTemplateVersion = version; return this; } /// Implicit conversion to for use in .To(...) / .From(...). public static implicit operator EndpointUri(LlmBuilder b) => EndpointUriParser.Parse(b.ToString()); /// Returns the URI string. Useful for .To(builder.AsUri()) overloads that take string. public string AsUri() => ToString(); /// public override string ToString() { var sb = new StringBuilder("llm://").Append(Uri.EscapeDataString(_factory)); var first = true; Append(sb, ref first, "temperature", _temperature); Append(sb, ref first, "maxTokens", _maxTokens); Append(sb, ref first, "topP", _topP); Append(sb, ref first, "systemPromptRef", _systemPromptRef); Append(sb, ref first, "conversation", _conversation); if (_stream != LlmStreamMode.Off) Append(sb, ref first, "stream", _stream.ToString().ToLowerInvariant()); Append(sb, ref first, "schedule", _schedule); Append(sb, ref first, "initialBodyRef", _initialBodyRef); Append(sb, ref first, "maxIterations", _maxIterations); Append(sb, ref first, "budgetInputTokens", _budgetInputTokens); Append(sb, ref first, "budgetOutputTokens", _budgetOutputTokens); Append(sb, ref first, "budgetCostUsd", _budgetCostUsd); if (_cacheSystemPrompt) Append(sb, ref first, "cacheSystemPrompt", "true"); Append(sb, ref first, "tools", _tools); Append(sb, ref first, "user", _user); Append(sb, ref first, "audit", BuildAuditCsv(_auditTags)); Append(sb, ref first, "propagateToolHeaders", BuildCsv(_propagateToolHeaders)); Append(sb, ref first, "promptTemplateName", _promptTemplateName); Append(sb, ref first, "promptTemplateVersion", _promptTemplateVersion); return sb.ToString(); } private static string? BuildCsv(List values) { if (values.Count == 0) return null; var sb = new StringBuilder(); for (var i = 0; i < values.Count; i++) { if (i > 0) sb.Append(','); sb.Append(Uri.EscapeDataString(values[i])); } return sb.ToString(); } private static string? BuildAuditCsv(List> tags) { if (tags.Count == 0) return null; var sb = new StringBuilder(); for (var i = 0; i < tags.Count; i++) { if (i > 0) sb.Append(','); sb.Append(Uri.EscapeDataString(tags[i].Key)) .Append('=') .Append(Uri.EscapeDataString(tags[i].Value)); } return sb.ToString(); } private static void Append(StringBuilder sb, ref bool first, string key, string? value) { if (string.IsNullOrEmpty(value)) return; sb.Append(first ? '?' : '&'); first = false; sb.Append(key).Append('=').Append(Uri.EscapeDataString(value)); } } Path: redb-route/redb.Route.Llm/Knowledge/KnowledgeComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Knowledge/KnowledgeComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Llm.Knowledge; /// /// Ingest transport for the knowledge base. Scheme: knowledge. /// /// To("knowledge://<collection>?chunkChars=1000&overlap=100&embed=true") — /// takes the inbound exchange body as a document, splits it into chunks, optionally /// embeds them (when an is registered), /// and upserts into the . Producer-only. /// /// /// /// From("file://docs?include=*.md").To("knowledge://handbook"); /// /// /// [EndpointRole(EndpointRole.Producer, Hint = "It ingests: use To(\"knowledge://\").")] public sealed class KnowledgeComponent : ComponentBase { /// public override string Scheme => "knowledge"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new KnowledgeEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new KnowledgeEndpoint(uri, this, options); } } /// Options for a knowledge:// endpoint (URI query auto-binds by name). public sealed class KnowledgeEndpointOptions : EndpointOptions { /// Target chunk size in characters. public int ChunkChars { get; set; } = 1000; /// Overlap (chars) between consecutive chunks. Must be in [0, ChunkChars). public int Overlap { get; set; } = 0; /// /// Embed chunks on ingest when an is /// available. Set ?embed=false to force keyword-only ingest (empty vectors). /// public bool Embed { get; set; } = true; /// /// Stable document id base — chunk ids are {DocId}#{index}, so a re-ingest /// of the same document replaces its chunks in place. Falls back to the /// knowledge.doc.id header, then to "doc". /// public string? DocId { get; set; } /// Collection fallback when the URI has no path (knowledge://?collection=...). public string? Collection { get; set; } /// public override void Validate() { if (ChunkChars < 1) throw new InvalidOperationException("knowledge://: chunkChars must be >= 1."); if (Overlap < 0 || Overlap >= ChunkChars) throw new InvalidOperationException("knowledge://: overlap must be in [0, chunkChars)."); } } /// Knowledge ingest endpoint. URI path = collection name. public sealed class KnowledgeEndpoint : EndpointBase { /// Target collection (URI path, or ?collection=). public string Collection { get; } /// Creates the endpoint. public KnowledgeEndpoint(EndpointUri uri, KnowledgeComponent component, KnowledgeEndpointOptions options) : base(uri, component, options) { Collection = !string.IsNullOrWhiteSpace(uri.Path) ? uri.Path : (options.Collection ?? string.Empty); if (string.IsNullOrWhiteSpace(Collection)) throw new InvalidOperationException( "knowledge:// requires a collection — use 'knowledge://' or '?collection='."); } /// public override IProducer CreateProducer() => new KnowledgeProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException( "knowledge:// is producer-only (ingest). Use To(\"knowledge://\")."); } Path: redb-route/redb.Route.Llm/Knowledge/KnowledgeProducer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Knowledge/KnowledgeProducer.cs ---- using System.Text.Json.Nodes; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Knowledge; /// /// Ingest producer: chunks the exchange body, (optionally) embeds, and upserts /// into the resolved . Writes a small summary /// ({"collection","docId","chunks"}) to Out.Body. /// public sealed class KnowledgeProducer : ConnectableProducer { /// Header carrying a per-document id base (chunk ids become {docId}#{i}). public const string DocIdHeader = "knowledge.doc.id"; private readonly KnowledgeEndpoint _endpoint; private readonly KnowledgeEndpointOptions _options; /// Creates the producer. public KnowledgeProducer(KnowledgeEndpoint endpoint, KnowledgeEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"knowledge:{_endpoint.Collection}"; /// protected override Task ConnectAsync(CancellationToken ct) => Task.CompletedTask; /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(exchange); var store = ResolveStore(exchange) ?? throw new InvalidOperationException( "knowledge://: no IKnowledgeStore is registered. Call AddRedbLlmStorage() or register one."); var embedder = _options.Embed ? ResolveEmbedder(exchange) : null; var text = exchange.In.Body?.ToString() ?? string.Empty; var docId = exchange.In.Headers.TryGetValue(DocIdHeader, out var h) && h is string s && s.Length > 0 ? s : (_options.DocId ?? "doc"); var pieces = KnowledgeChunker.Split(text, _options.ChunkChars, _options.Overlap); IReadOnlyList vectors = Array.Empty(); if (embedder is not null && pieces.Count > 0) vectors = await embedder.EmbedAsync(pieces, ct).ConfigureAwait(false); var chunks = new List(pieces.Count); for (var i = 0; i < pieces.Count; i++) { chunks.Add(new KnowledgeChunk { Id = $"{docId}#{i}", Text = pieces[i], Collection = _endpoint.Collection, Embedding = i < vectors.Count ? vectors[i] : Array.Empty() }); } if (chunks.Count > 0) await store.UpsertManyAsync(chunks, exchange, ct).ConfigureAwait(false); exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = new JsonObject { ["collection"] = _endpoint.Collection, ["docId"] = docId, ["chunks"] = chunks.Count }.ToJsonString(); exchange.Out.Headers["llm.knowledge.ingested"] = chunks.Count; } private IKnowledgeStore? ResolveStore(IExchange exchange) { var ctx = (_endpoint.Component as ComponentBase)?.Context; return ctx?.GetService() ?? ctx?.GetServiceProvider()?.GetService(typeof(IKnowledgeStore)) as IKnowledgeStore ?? exchange.ServiceProvider?.GetService(typeof(IKnowledgeStore)) as IKnowledgeStore; } private IEmbeddingProvider? ResolveEmbedder(IExchange exchange) { var ctx = (_endpoint.Component as ComponentBase)?.Context; return ctx?.GetService() ?? ctx?.GetServiceProvider()?.GetService(typeof(IEmbeddingProvider)) as IEmbeddingProvider ?? exchange.ServiceProvider?.GetService(typeof(IEmbeddingProvider)) as IEmbeddingProvider; } } /// /// Deterministic character-window chunker: fixed /// windows with chars shared between neighbours. /// public static class KnowledgeChunker { /// Splits into overlapping windows. public static IReadOnlyList Split(string? text, int chunkChars, int overlap) { text = (text ?? string.Empty).Trim(); if (text.Length == 0) return Array.Empty(); if (chunkChars < 1) chunkChars = 1; if (overlap < 0 || overlap >= chunkChars) overlap = 0; if (text.Length <= chunkChars) return new[] { text }; var step = chunkChars - overlap; var chunks = new List(); for (var start = 0; start < text.Length; start += step) { var len = Math.Min(chunkChars, text.Length - start); chunks.Add(text.Substring(start, len)); if (start + len >= text.Length) break; } return chunks; } } Path: redb-route/redb.Route.Llm/Knowledge/KnowledgeRetrievalDsl.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Knowledge/KnowledgeRetrievalDsl.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Knowledge; /// Options for the step. public sealed class KnowledgeRetrievalOptions { /// Collection to search (null = across all collections). public string? Collection { get; set; } /// How many chunks to inject. public int TopK { get; set; } = 5; /// Explicit store. When null, resolved from the exchange's . public IKnowledgeStore? Store { get; set; } /// /// When set (or resolvable from DI), retrieval is semantic (embed query → cosine /// ); otherwise keyword /// (). /// public IEmbeddingProvider? EmbeddingProvider { get; set; } /// Chooses the query text. Default: the exchange body as string. public Func? Query { get; set; } /// Max chars of each chunk injected (0 = full). public int MaxCharsPerChunk { get; set; } = 1000; /// Line placed above the retrieved chunks in the system prompt. public string Preamble { get; set; } = "Relevant knowledge (ground your answer on it; do not quote it verbatim to the user):"; } /// /// DSL step that retrieves top-K knowledge chunks for the current message and /// injects them into the system prompt (LlmHeaders.SystemPrompt), /// so a following .To("llm://...") answers grounded on them. A no-op when /// no store is available or nothing is retrieved — never breaks the pipeline. /// /// /// From("kafka://questions") /// .Knowledge("handbook", k: 5) // retrieve + inject /// .To("llm://claude"); // answer, grounded /// /// /// public static class KnowledgeRetrievalDsl { /// Retrieve + inject, shorthand. public static IRouteDefinition Knowledge(this IRouteDefinition self, string? collection, int k = 5) => Knowledge(self, new KnowledgeRetrievalOptions { Collection = collection, TopK = k }); /// Retrieve + inject with explicit options. public static IRouteDefinition Knowledge(this IRouteDefinition self, KnowledgeRetrievalOptions options) { ArgumentNullException.ThrowIfNull(self); ArgumentNullException.ThrowIfNull(options); return self.Process(async (exchange, ct) => { var store = options.Store ?? exchange.ServiceProvider?.GetService(typeof(IKnowledgeStore)) as IKnowledgeStore; if (store is null) return; // no store wired → no-op var query = (options.Query?.Invoke(exchange) ?? exchange.In.Body?.ToString())?.Trim(); if (string.IsNullOrEmpty(query)) return; var topK = Math.Clamp(options.TopK, 1, 50); var embedder = options.EmbeddingProvider ?? exchange.ServiceProvider?.GetService(typeof(IEmbeddingProvider)) as IEmbeddingProvider; IReadOnlyList hits; if (embedder is not null) { var vector = await embedder.EmbedOneAsync(query, ct).ConfigureAwait(false); hits = await store.SearchAsync(vector, topK, options.Collection, exchange, ct).ConfigureAwait(false); } else { hits = await store.SearchTextAsync(query, topK, options.Collection, exchange, ct).ConfigureAwait(false); } if (hits.Count == 0) return; var block = BuildBlock(hits, options); var existing = exchange.In.Headers.TryGetValue(LlmHeaders.SystemPrompt, out var sp) ? sp?.ToString() : null; exchange.In.Headers[LlmHeaders.SystemPrompt] = string.IsNullOrEmpty(existing) ? block : existing + "\n\n" + block; exchange.In.Headers["llm.knowledge.injected"] = hits.Count; }); } private static string BuildBlock(IReadOnlyList hits, KnowledgeRetrievalOptions options) { var sb = new StringBuilder(options.Preamble); foreach (var hit in hits) { var text = hit.Chunk.Text; if (options.MaxCharsPerChunk > 0 && text.Length > options.MaxCharsPerChunk) text = text[..options.MaxCharsPerChunk] + "…"; sb.Append("\n- ").Append(text.Replace("\r\n", " ").Replace('\n', ' ')); } return sb.ToString(); } } Path: redb-route/redb.Route.Llm/LazyAgentBody.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LazyAgentBody.cs ---- using System.Runtime.CompilerServices; using System.Threading.Channels; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Observability; namespace redb.Route.Llm; /// /// The body of stream=body: an agent run made when the body is read, after the route, the way a streamed SQL /// result is read. The visible text of every model call is yielded as the model writes it; thinking stays out. The run /// reads its exchange's resources (the conversation store, the redb scope), so the body is bound to the exchange /// (): it is released with it through , a read after the /// exchange ended fails, and it can be read once — one read is one run, tools included. /// internal sealed class LazyAgentBody : IAsyncEnumerable, IExchangeBoundBody { private readonly Func, CancellationToken, Task> _run; private readonly CancellationTokenSource _released = new(); private Task? _running; private int _read; /// /// The agent run: given the receiver of the pieces, it runs the engine and writes the summary. Its failure reaches /// the reader. /// internal LazyAgentBody(Func, CancellationToken, Task> run) => _run = run; /// The handle the exchange releases when it ends: it stops a run in progress and closes the body. internal IAsyncDisposable Release => new ReleaseHandle(this); /// /// The body was already read, or its exchange has ended. public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _read, 1) != 0) throw new InvalidOperationException( "A streamed agent answer (stream=body) can be read once: one read is one agent run, with its tools."); if (_released.IsCancellationRequested) throw new InvalidOperationException( "This streamed agent answer (stream=body) was released when its exchange ended; it can no longer be read. " + "Read the body before the exchange ends: ProducerTemplate.RequestAsync, then dispose the exchange."); return ReadAsync(cancellationToken).GetAsyncEnumerator(cancellationToken); } private async IAsyncEnumerable ReadAsync([EnumeratorCancellation] CancellationToken ct) { using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct, _released.Token); var pieces = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }); var running = RunAsync(pieces.Writer, stop.Token); _running = running; try { await foreach (var piece in pieces.Reader.ReadAllAsync(stop.Token).ConfigureAwait(false)) yield return piece; } finally { // A reader that stops early ends the run, and the run is awaited: nothing of it outlives the read. if (!running.IsCompleted) await stop.CancelAsync().ConfigureAwait(false); await running.ConfigureAwait(false); } } private async Task RunAsync(ChannelWriter pieces, CancellationToken ct) { try { await _run((delta, token) => delta.Kind == AgentDeltaKind.Text ? pieces.WriteAsync(delta.Text, token).AsTask() : Task.CompletedTask, ct).ConfigureAwait(false); pieces.TryComplete(); } catch (Exception ex) { // Handed to the reader, who is the one waiting for the answer: reading the channel rethrows it. pieces.TryComplete(ex); } } private async ValueTask ReleaseAsync() { if (_released.IsCancellationRequested) return; await _released.CancelAsync().ConfigureAwait(false); // The exchange releases its DI scopes right after its resources: a run still reading them must be over first. if (_running is { } running) await running.ConfigureAwait(false); } private sealed class ReleaseHandle(LazyAgentBody body) : IAsyncDisposable { public ValueTask DisposeAsync() => body.ReleaseAsync(); } } Path: redb-route/redb.Route.Llm/LlmCallbackProcessor.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmCallbackProcessor.cs ---- using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; namespace redb.Route.Llm; /// /// Processes inbound webhook callbacks from async-batch LLM APIs (Anthropic /// Message Batches, OpenAI Batch, vLLM batch endpoints, ...). /// /// Wire it into a vanilla HTTP route — no llm-callback:// scheme: /// /// r.From("http:0.0.0.0:5099/api/llm/callback?inOut=true") /// .Process(new LlmCallbackProcessor()) /// .Choice() /// .When(e => (bool)e.In.Headers[LlmHeaders.BatchDuplicate]!).Stop() /// .End() /// .To("direct:llm-batch-handler"); /// /// /// /// Behaviour: /// /// Resolve the batch id (header → query → JSON body in this order). /// Deduplicate via , keyed on /// "batch:<batchId>". A duplicate sets /// =true and stops further work. /// If an is registered, load the original /// submission to populate , /// , . /// Mark the batch completed and confirm idempotency. /// /// /// /// The processor never fetches results from the provider on its own — that /// step belongs to a follow-up route or the host application. It only /// guarantees a single, conversation-aware delivery of every callback. /// /// public sealed class LlmCallbackProcessor : IProcessor { private readonly LlmCallbackOptions _options; private readonly IToolIdempotencyStore _idempotency; private readonly IBatchStore? _batchStore; private readonly IConversationStore? _conversationStore; /// Creates a callback processor. /// Required — used to deduplicate batch ids. /// Optional — when present, the processor enriches headers with submit-time metadata. /// /// Optional — when present together with , completed callbacks whose record /// has set are appended to the conversation as /// an assistant turn (extracted from the callback body via ). /// /// Optional — overrides for header / query / JSON-body field names. public LlmCallbackProcessor( IToolIdempotencyStore idempotency, IBatchStore? batchStore = null, IConversationStore? conversationStore = null, LlmCallbackOptions? options = null) { _idempotency = idempotency ?? throw new ArgumentNullException(nameof(idempotency)); _batchStore = batchStore; _conversationStore = conversationStore; _options = options ?? new LlmCallbackOptions(); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); var batchId = ResolveBatchId(exchange) ?? throw new InvalidOperationException( $"LlmCallbackProcessor: batch id not found. Looked at header '{_options.BatchIdHeader}', " + $"query parameter '{_options.BatchIdQueryParam}', JSON fields {string.Join(", ", _options.BatchIdJsonFields)}."); var status = ResolveStatus(exchange); // Pre-create Out so the rest of the route sees the enrichments. exchange.Out ??= exchange.In.Clone(); exchange.Out.Headers[LlmHeaders.BatchId] = batchId; exchange.Out.Headers[LlmHeaders.BatchStatus] = status; // Idempotency: batch id is namespaced under conversation "batch" so // it does not collide with regular tool_use_id reservations. var reservation = await _idempotency .TryReserveAsync(IdempotencyConversation, batchId, exchange, ct) .ConfigureAwait(false); if (!reservation.IsNew) { exchange.Out.Headers[LlmHeaders.BatchDuplicate] = true; return; } // Best-effort enrichment from IBatchStore — failures must not stop the route. BatchJobRecord? record = null; if (_batchStore is not null) { try { record = await _batchStore.GetAsync(batchId, exchange, ct).ConfigureAwait(false); if (record is not null) { if (!string.IsNullOrEmpty(record.ConversationId)) exchange.Out.Headers[LlmHeaders.ConversationId] = record.ConversationId; if (!string.IsNullOrEmpty(record.ProviderId)) exchange.Out.Headers[LlmHeaders.ProviderId] = record.ProviderId; if (!string.IsNullOrEmpty(record.ModelId)) exchange.Out.Headers[LlmHeaders.ModelId] = record.ModelId; } if (string.Equals(status, "failed", StringComparison.OrdinalIgnoreCase)) { var err = ResolveErrorMessage(exchange) ?? "callback reported failure"; await _batchStore.MarkFailedAsync(batchId, err, exchange, ct).ConfigureAwait(false); } else { await _batchStore.MarkCompletedAsync(batchId, exchange, ct).ConfigureAwait(false); } } catch { // Tracking failures are non-fatal; the callback still has to flow downstream. } } // Opt-in: append the assistant turn to the conversation tree on success. // The append is best-effort — failure here must not break the callback flow. if (_conversationStore is not null && record is { AppendToConversation: true, ConversationId: { Length: > 0 } convId } && !string.Equals(status, "failed", StringComparison.OrdinalIgnoreCase)) { try { var assistantText = ExtractJsonField(exchange.In.Body, _options.AssistantContentJsonFields); if (!string.IsNullOrEmpty(assistantText)) { var path = await _conversationStore .LoadPathAsync(convId, leafId: null, exchange, ct) .ConfigureAwait(false); var parentId = path.Count > 0 ? path[^1].Id : null; var msgId = await _conversationStore.AppendAsync( convId, parentId, LlmMessage.Assistant(assistantText), new ConversationMessageMeta { CreatedAtUtc = DateTime.UtcNow, Iteration = path.Count, ProviderId = record.ProviderId, ModelId = record.ModelId, StopReason = LlmStopReason.EndTurn }, exchange, ct) .ConfigureAwait(false); exchange.Out.Headers[LlmHeaders.ConversationMessageId] = msgId; } } catch { // Append failures are non-fatal; the callback still has to flow downstream. } } exchange.Out.Headers[LlmHeaders.BatchDuplicate] = false; // Confirm the reservation so a retried webhook lands in the duplicate branch. // We persist the raw status as the "output"; downstream routes can use // it for diagnostic queries. await _idempotency .CompleteAsync(IdempotencyConversation, batchId, status, exchange, ct) .ConfigureAwait(false); } private string? ResolveBatchId(IExchange exchange) { if (exchange.In.Headers.TryGetValue(_options.BatchIdHeader, out var hv) && hv is string hs && hs.Length > 0) return hs; if (exchange.In.Headers.TryGetValue(_options.BatchIdQueryParam, out var qv) && qv is string qs && qs.Length > 0) return qs; var fromBody = ExtractJsonField(exchange.In.Body, _options.BatchIdJsonFields); return fromBody; } private string ResolveStatus(IExchange exchange) { if (exchange.In.Headers.TryGetValue(_options.StatusHeader, out var hv) && hv is string hs && hs.Length > 0) return hs; var fromBody = ExtractJsonField(exchange.In.Body, _options.StatusJsonFields); return fromBody ?? "completed"; } private string? ResolveErrorMessage(IExchange exchange) { if (exchange.In.Headers.TryGetValue(_options.ErrorHeader, out var hv) && hv is string hs && hs.Length > 0) return hs; return ExtractJsonField(exchange.In.Body, _options.ErrorJsonFields); } private static string? ExtractJsonField(object? body, IReadOnlyList candidates) { if (candidates.Count == 0) return null; var text = body switch { null => null, string s => s, byte[] bytes => System.Text.Encoding.UTF8.GetString(bytes), _ => body.ToString() }; if (string.IsNullOrWhiteSpace(text)) return null; try { using var doc = JsonDocument.Parse(text); foreach (var candidate in candidates) { if (TryReadDotted(doc.RootElement, candidate, out var value) && !string.IsNullOrEmpty(value)) return value; } } catch (JsonException) { // Body wasn't JSON — fall through with no match. } return null; } private static bool TryReadDotted(JsonElement root, string path, out string? value) { value = null; if (string.IsNullOrEmpty(path)) return false; var current = root; var idx = 0; while (idx < path.Length) { var dot = path.IndexOf('.', idx); var segment = dot == -1 ? path[idx..] : path[idx..dot]; if (current.ValueKind == JsonValueKind.Array && int.TryParse(segment, out var arrIdx)) { if (arrIdx < 0 || arrIdx >= current.GetArrayLength()) return false; current = current[arrIdx]; } else { if (current.ValueKind != JsonValueKind.Object) return false; if (!current.TryGetProperty(segment, out var next)) return false; current = next; } if (dot == -1) break; idx = dot + 1; } value = current.ValueKind switch { JsonValueKind.String => current.GetString(), JsonValueKind.Number => current.GetRawText(), JsonValueKind.True or JsonValueKind.False => current.GetRawText(), _ => null }; return value is not null; } /// Conversation id used to namespace batch reservations inside the idempotency store. private const string IdempotencyConversation = "batch"; } /// Configuration for . public sealed class LlmCallbackOptions { /// Header carrying the batch id; default "X-Batch-Id". public string BatchIdHeader { get; init; } = "X-Batch-Id"; /// Query-string / generic header fallback for the batch id; default "batchId". public string BatchIdQueryParam { get; init; } = "batchId"; /// Dotted JSON paths consulted in order when no header / query value is present. public IReadOnlyList BatchIdJsonFields { get; init; } = ["id", "batch_id", "data.id", "batch.id"]; /// Header carrying the lifecycle status; default "X-Batch-Status". public string StatusHeader { get; init; } = "X-Batch-Status"; /// Dotted JSON paths consulted in order when no status header is present. public IReadOnlyList StatusJsonFields { get; init; } = ["status", "processing_status", "state"]; /// Header carrying an error message; default "X-Batch-Error". public string ErrorHeader { get; init; } = "X-Batch-Error"; /// Dotted JSON paths consulted in order when no error header is present. public IReadOnlyList ErrorJsonFields { get; init; } = ["error", "error.message", "failure_reason"]; /// /// Dotted JSON paths consulted in order to extract the assistant turn text /// from a successful callback body when /// is true. /// Defaults cover the most common provider shapes (Anthropic / OpenAI / vLLM). /// public IReadOnlyList AssistantContentJsonFields { get; init; } = ["output_text", "choices.0.message.content", "content.0.text", "message.content", "text"]; } Path: redb-route/redb.Route.Llm/LlmComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Llm; /// /// LLM transport component for redb.Route. /// Scheme: llm. /// /// URI format: llm://<connectionFactoryName>?temperature=0.2&maxTokens=1024. /// Producer/consumer behaviour is selected by From/To as in any other /// connector — there is no separate llm-agent:// or llm-stream:// scheme. /// /// public sealed class LlmComponent : ComponentBase { /// public override string Scheme => "llm"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new LlmEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new LlmEndpoint(uri, this, options); } } Path: redb-route/redb.Route.Llm/LlmConnectionFactory.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmConnectionFactory.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Llm.Providers; using redb.Route.Core; namespace redb.Route.Llm; /// /// Connection factory configuration for the LLM connector. Register in the route /// registry and reference by name in endpoint URIs (connectionFactory=myFactory /// or as the URI host: llm://myFactory). /// /// Centralises model identity, version, credentials and per-provider tuning so /// they are kept out of the URI. /// /// public sealed class LlmConnectionFactory { /// /// Logical name of this factory (the registry key, e.g. "claude"). /// Set by when the factory is registered. /// Surfaced as the llm.factory tag on metrics and traces. /// public string Name { get; set; } = string.Empty; /// Provider identifier: "anthropic", "openai", "azure-openai", "ollama", "stub". public string Provider { get; set; } = "stub"; /// Model identifier passed to the provider (e.g. "claude-haiku-4.5", "gpt-4o-mini"). public string ModelId { get; set; } = "stub-model"; /// /// Optional Anthropic contract-tier override (legacy/transitional/modern). /// Escape-hatch for self-hosted ids, proxies, or model snapshots the built-in generation /// table does not recognise. When unset, the tier is inferred from /// (unknown ids default to modern — no removed sampling knobs are sent). Anthropic-only; /// ignored by OpenAI-compatible providers. See . /// public string? ModelContractTier { get; set; } /// API key. Prefer for production deployments. [Sensitive] public string? ApiKey { get; set; } /// Reference to a secret store entry — resolved at time. public string? ApiKeySecretRef { get; set; } /// Optional base URL override (Azure OpenAI, OpenAI-compatible servers, local Ollama). public Uri? BaseUrl { get; set; } /// Default sampling temperature. public double? Temperature { get; set; } /// Default max output tokens. public int? MaxTokens { get; set; } /// /// Effort level for models that think by default (Anthropic Claude 4.6+ / Sonnet 5 / Opus 5: /// low, medium, high, xhigh, max; sent as /// output_config.effort). null — the provider's default (high on /// Anthropic). Thinking tokens count against : at the default effort /// a hard question can spend the whole budget on thinking and return NO text (seen /// 2026-09-07 with max_tokens 4096 on Sonnet 5) — medium or low keeps the /// answer inside the budget. Models without the effort ladder (Haiku 4.5) reject the field /// with 400, so set it per factory, not globally. /// public string? Effort { get; set; } /// Default top-p sampling parameter. public double? TopP { get; set; } /// /// Limit of one call to the model, in milliseconds (default: 600 000, ten minutes, like the official Anthropic /// and OpenAI SDKs; at least 1 000). It covers the whole call, waiting for the answer and reading it, on every /// provider and whatever client sends it; running out throws . A /// non-streaming answer from a thinking model is minutes of generation, so set it to the longest answer you /// expect. A streamed call is limited the same way, from the send to the last piece; a stream's silence has a /// limit of its own, . A client passed in by the host keeps its own /// as well. /// public int RequestTimeoutMs { get; set; } = 600_000; /// /// Longest silence of a streamed call, in milliseconds: how long the provider may send nothing at all — no text, /// no thinking, not even a keep-alive comment or ping — before the call fails with /// (). It counts only /// the waits on the provider, not the time the reader spends between pieces. Off by default (null): the /// whole call is still limited by , and some reasoning models stream nothing for /// minutes before their first token. Must be positive when set. /// public int? StreamIdleTimeoutMs { get => _streamIdleTimeoutMs; set { if (value is <= 0) throw new ArgumentOutOfRangeException(nameof(value), value, "StreamIdleTimeoutMs must be positive; leave it unset (null) to turn the silence limit off."); _streamIdleTimeoutMs = value; } } private int? _streamIdleTimeoutMs; // Retries was removed: it was never read, and the Llm engine's resilience // policy is deliberately fallback-to-another-factory, not retry-the-same-provider. /// /// Optional pre-built provider instance. When set, returns it /// without attempting to construct one — useful for tests and custom providers. /// public ILlmProvider? PrebuiltProvider { get; set; } /// /// Logger factory used by built providers for diagnostics (e.g. Anthropic sampling-knob /// drops). Set automatically at registration by AddLlmConnectionFactory from DI; /// null in bare test setups (providers then fall back to activity events only). /// public ILoggerFactory? LoggerFactory { get; set; } /// /// Builds an from this configuration. Resolution order: /// /// if set; /// built-in provider matching ; /// for unknown providers. /// /// public ILlmProvider Build() { if (PrebuiltProvider is not null) return PrebuiltProvider; if (_cached is not null) return _cached; // Cache the built provider so its HttpClient is reused, not minted (and leaked) per call. Providers are // stateless per request and HttpClient is thread-safe, so one instance per factory is correct. lock (_buildLock) return _cached ??= BuildCore(); } private ILlmProvider? _cached; private readonly object _buildLock = new(); private ILlmProvider BuildCore() { return Provider?.ToLowerInvariant() switch { "stub" => new StubProvider(this), "anthropic" => new AnthropicProvider(this), // All providers below speak the OpenAI Chat Completions protocol. // Default base URLs are resolved by OpenAiProvider.ResolveDefaultBaseUrl; // override LlmConnectionFactory.BaseUrl for self-hosted/proxy setups. "openai" or "groq" or "cerebras" or "openrouter" or "gemini" or "google" or "github-models" or "github" or "mistral" or "together" or "togetherai" or "huggingface" or "hf" or "deepseek" or "ollama" or "lmstudio" => OpenAiProvider.Create(this), _ => throw new NotSupportedException( $"Unknown LLM provider '{Provider}'. Built-in providers: stub, anthropic, " + $"openai, groq, cerebras, openrouter, gemini, github-models, mistral, together, " + $"huggingface, deepseek, ollama, lmstudio. " + $"Use {nameof(PrebuiltProvider)} to plug a custom provider.") }; } } Path: redb-route/redb.Route.Llm/LlmConsumer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmConsumer.cs ---- using System.Diagnostics; using System.Text.RegularExpressions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Telemetry; using redb.Route.Llm.Tools; using redb.Route.Telemetry; namespace redb.Route.Llm; /// /// LLM consumer. Fires the connection factory on a fixed interval and pushes /// the agent response into the route pipeline as a normal exchange. /// /// Supported schedule formats: /// /// 30s / 5m / 1h — fixed interval via . /// A cron expression — rejected with a redirect to From("quartz://...") /// which already handles cron scheduling. /// /// /// The initial user message comes from . /// A leading # turns the value into a registry reference: ?initialBodyRef=#daily-brief /// resolves daily-brief first via (latest version), /// then via 's named-object registry. Any other route can /// rewrite the same key at runtime, giving the scheduled agent a fresh prompt every tick /// without touching the route definition. Plain values are used verbatim. /// public sealed class LlmConsumer : IConsumer { private static readonly Regex IntervalPattern = new(@"^\s*(\d+)\s*(ms|s|m|h)\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private readonly LlmEndpoint _endpoint; private readonly LlmEndpointOptions _options; private readonly IProcessor _processor; private CancellationTokenSource? _cts; private Task? _loop; // Single-threaded scheduler loop: marks a tick whose failure the core already counted. private bool _tickFailedInPipeline; /// Creates a consumer. public LlmConsumer(LlmEndpoint endpoint, LlmEndpointOptions options, IProcessor processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); } /// public IEndpoint? Endpoint => _endpoint; /// public Task Start(CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(_options.Schedule)) throw new InvalidOperationException( "Consumer mode for 'llm://' requires '?schedule=' (e.g. '30s', '5m', '1h'). " + "For cron expressions use From(\"quartz://...\").To(\"llm://factory\"); " + "for event-driven agents use From(\"\").To(\"llm://factory\")."); var interval = ParseInterval(_options.Schedule) ?? throw new InvalidOperationException( $"Schedule '{_options.Schedule}' is not a valid interval. " + "Accepted formats: '500ms', '30s', '5m', '1h'. " + "Cron expressions are not supported by the inline consumer — use From(\"quartz://...\")."); _cts = CancellationTokenSource.CreateLinkedTokenSource(ct); _loop = RunLoopAsync(interval, _cts.Token); return Task.CompletedTask; } /// public async Task Stop(CancellationToken ct = default) { if (_cts is null) return; try { await _cts.CancelAsync().ConfigureAwait(false); } catch { /* idempotent */ } if (_loop is { } loop) { try { await loop.ConfigureAwait(false); } catch (OperationCanceledException) { /* expected */ } } _cts.Dispose(); _cts = null; _loop = null; } private async Task RunLoopAsync(TimeSpan interval, CancellationToken ct) { using var timer = new PeriodicTimer(interval); while (!ct.IsCancellationRequested) { try { if (!await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) return; } catch (OperationCanceledException) { return; } // A tick has no sender: its span is a root, never a child of the activity that started the routes. The // model call and the route run under it. using var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"llm {_endpoint.ConnectionFactoryName} receive", ActivityKind.Consumer, "messaging.system", "llm", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, operation: "receive"); try { await FireOnceAsync(span.Activity, ct).ConfigureAwait(false); } // Only real shutdown stops the loop. An HttpClient timeout also throws OperationCanceledException // (TaskCanceledException) but on a different token — that must fall through to the transient catch, // not silently terminate the scheduled consumer forever. catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } catch (Exception ex) { // Ownership audit: a pipeline failure was already counted by the core's // StatisticsProcessor; the consumer records only a tick that died BEFORE the // exchange reached the pipeline (factory/engine/prompt resolution, the LLM call). if (!_tickFailedInPipeline) _endpoint.RecordError(ex); span.Activity.RecordFailure(ex); // Continue — one failed tick must not kill the consumer. } } } private Task FireOnceAsync(Activity? span, CancellationToken ct) { // No RecordMessageOut / RecordProcessingTime: the pipeline leg is wrapped by the core's // StatisticsProcessor (MessagesIn, Errors, time), and MessagesOut is a producer-side // counter a scheduler tick never is - self-recording doubled both (ownership audit). _tickFailedInPipeline = false; return FireOnceCoreAsync(span, ct); } private async Task FireOnceCoreAsync(Activity? span, CancellationToken ct) { var ctx = (_endpoint.Component as ComponentBase)?.Context; var factory = _endpoint.ResolvedFactory ?? ctx?.GetFromRegistry(_endpoint.ConnectionFactoryName) ?? throw new InvalidOperationException( $"LLM connection factory '{_endpoint.ConnectionFactoryName}' is not registered."); var services = ctx?.GetServiceProvider(); var engine = _endpoint.ResolvedEngine ?? (ctx is null ? null : AgentEngine.FindRegistered(ctx)) ?? throw new InvalidOperationException( "No IAgentEngine is registered. Call services.AddRedbRouteLlm() — it registers the engine with " + "the producer template, claims source and cache — or register one via " + "AgentEngine.FromContext(context)."); var templateRegistry = services?.GetService() ?? ctx?.GetService(); // The exchange comes first, with an empty body: the prompt references resolve with it, so a redb-backed // template registry works on this tick's scope instead of the one instance every concurrent tick shares. var scopeFactory = services?.GetService(); var exchange = Exchange.Create(new Message(string.Empty), scopeFactory); // The scheduler owns this exchange for the whole tick: dispose it in finally so its // per-exchange DI scope (and any redb connection resolved downstream) is released every // tick — otherwise each scheduled fire would leak a scope and drain the connection pool. // The prompt lookups run inside, so a failing template releases the exchange as well. try { // Make the configured named-redb visible to every downstream store, the template registry included. if (!string.IsNullOrEmpty(_options.Redb)) exchange.Properties[LlmKeys.RedbName] = _options.Redb; var initialBody = await PromptRef.ResolveAsync(_options.InitialBodyRef, templateRegistry, ctx, exchange, ct).ConfigureAwait(false) ?? string.Empty; var systemPrompt = await PromptRef.ResolveAsync(_options.SystemPromptRef, templateRegistry, ctx, exchange, ct).ConfigureAwait(false); exchange.In.Body = initialBody; var registry = services?.GetService() ?? ctx?.GetService(); var tools = ToolFilter.Resolve(registry, _options.Tools); var conversationId = _options.Conversation switch { "header" => null, // no header on a scheduler-born exchange "property" => exchange.RouteId, _ => null }; var request = new AgentRequest { Factory = factory, Exchange = exchange, UserContent = [new LlmTextBlock(initialBody)], SystemPrompt = systemPrompt, Tools = tools, ConversationId = conversationId, MaxIterations = _options.MaxIterations, Budget = AgentBudgetFactory.From( _options.BudgetInputTokens, _options.BudgetOutputTokens, _options.BudgetCostUsd), Temperature = _options.Temperature, MaxTokens = _options.MaxTokens, PropagateToolHeaders = ToolHeaderPolicy.ParseCsv(_options.PropagateToolHeaders) }; var response = await engine.RunAsync(request, ct).ConfigureAwait(false); exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = response.Text; exchange.Out.Headers[LlmHeaders.ProviderId] = factory.Provider; exchange.Out.Headers[LlmHeaders.ModelId] = factory.ModelId; exchange.Out.Headers[LlmHeaders.TokensIn] = response.Usage.InputTokens; exchange.Out.Headers[LlmHeaders.TokensOut] = response.Usage.OutputTokens; exchange.Out.Headers[LlmHeaders.CacheWriteTokens] = response.Usage.CacheCreationInputTokens; exchange.Out.Headers[LlmHeaders.CacheReadTokens] = response.Usage.CacheReadInputTokens; exchange.Out.Headers[LlmHeaders.ToolIterations] = response.Iterations; exchange.Out.Headers[LlmHeaders.StopReason] = response.StopReason.ToString(); try { await _processor.Process(exchange, ct).ConfigureAwait(false); } catch { // The core's StatisticsProcessor counted this one; the RunLoop catch must not. _tickFailedInPipeline = true; throw; } // A failed route need not throw: the failure stays on the exchange. Our own stop is not a failure. if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !ct.IsCancellationRequested)) span.RecordFailure(failure); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } private static TimeSpan? ParseInterval(string schedule) { var m = IntervalPattern.Match(schedule); if (!m.Success) return null; if (!long.TryParse(m.Groups[1].Value, out var n) || n <= 0) return null; return m.Groups[2].Value.ToLowerInvariant() switch { "ms" => TimeSpan.FromMilliseconds(n), "s" => TimeSpan.FromSeconds(n), "m" => TimeSpan.FromMinutes(n), "h" => TimeSpan.FromHours(n), _ => null }; } } Path: redb-route/redb.Route.Llm/LlmEndpoint.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmEndpoint.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Engine; namespace redb.Route.Llm; /// /// LLM endpoint. The URI host is interpreted as the connection-factory name. /// public sealed class LlmEndpoint : EndpointBase { /// Connection factory name (from URI host or connectionFactory query). public string ConnectionFactoryName { get; } /// Resolved connection factory from the registry (null if not registered yet). internal LlmConnectionFactory? ResolvedFactory { get; } /// /// Agent engine resolved from the route context. Created lazily on first producer/consumer /// instantiation so that engine wiring can happen after the endpoint is created. /// internal IAgentEngine? ResolvedEngine { get; } /// Creates an LLM endpoint. public LlmEndpoint(EndpointUri uri, LlmComponent component, LlmEndpointOptions options) : base(uri, component, options) { // Path wins; fall back to query parameter ConnectionFactoryName = !string.IsNullOrWhiteSpace(uri.Path) ? uri.Path : (options.ConnectionFactory ?? string.Empty); if (string.IsNullOrWhiteSpace(ConnectionFactoryName)) throw new InvalidOperationException( "LLM endpoint requires a connection factory name. " + "Use 'llm://' or '?connectionFactory='."); if (component.Context is not null) { ResolvedFactory = component.Context.GetFromRegistry(ConnectionFactoryName); ResolvedEngine = AgentEngine.FindRegistered(component.Context); } } /// public override IProducer CreateProducer() => new LlmProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => new LlmConsumer(this, Options, processor); } Path: redb-route/redb.Route.Llm/LlmEndpointOptions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmEndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.Llm; /// /// Typed options for . Bound from URI query parameters via reflection. /// /// The set of accepted parameters is intentionally narrow — model, provider, version /// and credentials must come from , not the URI. /// /// public sealed class LlmEndpointOptions : EndpointOptions { /// Name of the registered in the route registry. /// /// May also come from the URI host (llm://myFactory); the host wins when both are set. /// [RegistryReference(typeof(LlmConnectionFactory))] public string? ConnectionFactory { get; set; } /// Optional per-call temperature override. public double? Temperature { get; set; } /// Optional per-call max-tokens override. public int? MaxTokens { get; set; } /// Optional per-call top-p override. public double? TopP { get; set; } /// /// Reference to a system-prompt template stored in the prompt registry /// (or a literal prompt — applied when no registry entry matches). /// public string? SystemPromptRef { get; set; } /// /// Conversation identifier strategy. Recognised values: /// "none" — no conversation tracking (default); /// "header" — read from llm.conversation.id header; /// "property" — read from exchange.RouteId as conversation key. /// public string Conversation { get; set; } = "none"; /// /// Streaming mode (): stream=calls or stream=body; absent means no /// streaming. Any other value, stream=true included, is refused when the endpoint is created. /// public LlmStreamMode Stream { get; set; } /// /// cacheSystemPrompt=true — ask the provider to cache the system prompt so repeated /// turns re-read it instead of re-paying for it. /// /// Set it only when the system prompt is the same bytes every time. Caching matches on /// the rendered prefix, so a prompt carrying a timestamp or a per-user name is written to the /// cache and never read back: cost, no benefit. Verify with /// LlmUsage.CacheReadInputTokens — zero across repeated calls means the prefix moves. /// public bool CacheSystemPrompt { get; set; } /// /// Schedule expression for consumer mode (cron or fixed interval). When set on /// a From("llm://...") route, the consumer wakes up on this schedule and /// invokes the agent with an empty user message (or with body resolved from /// ). /// public string? Schedule { get; set; } /// Optional reference to a body template used by scheduled consumers. public string? InitialBodyRef { get; set; } /// Maximum tool-loop iterations the agent engine may consume for one call. public int MaxIterations { get; set; } = 8; /// /// Per-run input-token budget (summed across iterations). Null = no ceiling; 0 also means no /// ceiling (the enforcer only enforces positive limits). Distinct from , which /// caps what the provider may generate in a single call. /// URI form: llm://factory?budgetInputTokens=20000. /// public int? BudgetInputTokens { get; set; } /// /// Per-run output-token budget (summed across iterations). Null or 0 = no ceiling. /// URI form: llm://factory?budgetOutputTokens=4000. /// public int? BudgetOutputTokens { get; set; } /// /// Per-run cost ceiling in USD. Null or 0 = no ceiling. A positive value requires an /// that can price the model — the run fails fast /// before the first provider call when the registered calculator cannot. /// URI form: llm://factory?budgetCostUsd=0.5. /// public decimal? BudgetCostUsd { get; set; } /// /// Tool exposure filter. Recognised values: /// null/empty — no tools exposed (default; explicit opt-in required); /// "*" — every descriptor in the registry; /// CSV of names (e.g. "get_order,refund") — only those names from the registry. /// public string? Tools { get; set; } /// /// Optional name of the the LLM stores /// (conversation, approval, batch, idempotency, knowledge, ...) should target /// for this endpoint. The producer/consumer publishes the value into /// exchange.Properties[LlmKeys.RedbName]; storage implementations resolve /// the redb instance via context.GetRedbService(name, exchange), which /// already takes care of per-exchange scoping and disposal. /// /// When null or empty the default unnamed IRedbService registered in the /// route context is used — typically the host-wide instance from /// services.AddRedb(). /// /// URI form: llm://factory?redb=my-llm-db. /// public string? Redb { get; set; } /// /// Principal identifier expression for audit. Either a literal value /// ("system") or a header reference ("${header.X-User-Id}"); /// resolves it pre-call against the inbound /// exchange and stamps the value on every persisted row of the run as /// MessageProps.UserId. Falls back to the llm.user.id /// header when this is null. /// public string? User { get; set; } /// /// Comma-separated audit tags expressed as key=value pairs (each /// value may be a literal or a ${header.X} expression). /// Example: tier=${header.X-Tier},bucket=A. Builders normally /// populate this through repeated .Audit(k, v) calls — values are /// URL-encoded before joining so commas / equals signs in literal values /// are safe. Header-driven tags (llm.audit.<name>) merge on /// top of these; headers win on collision. /// public string? Audit { get; set; } /// /// Prompt-template name persisted alongside every row of the run as /// MessageProps.PromptTemplateName. Pairs with /// so auditors can lock down which /// exact prompt drove an answer. Independent of : /// you can carry name/version even when the prompt body comes from elsewhere. /// public string? PromptTemplateName { get; set; } /// Prompt-template version paired with . public string? PromptTemplateVersion { get; set; } /// /// Comma-separated extra header names propagated from the agent exchange to /// every tool call of the run. A trailing * makes an entry a prefix /// match. Example: x-tenant-id,accept-language,x-app-*. /// /// Propagation is default-deny: without this option a tool route sees /// only the conversation / correlation ids, the resolved principal /// (llm.user.id) and the resolved audit tags (llm.audit.*) — /// never the inbound transport's header set. Add names here only for headers /// the route itself controls. /// /// URI form: llm://factory?propagateToolHeaders=x-tenant-id,x-app-*. /// public string? PropagateToolHeaders { get; set; } /// public override void Validate() { if (MaxIterations < 1) throw new ArgumentException("MaxIterations must be >= 1.", nameof(MaxIterations)); if (Temperature is < 0 or > 2) throw new ArgumentException("Temperature must be between 0 and 2.", nameof(Temperature)); // An unknown parameter and a value that does not convert — 'stream=true', the old switch, among them — are // refused by the core while binding, before this method runs (EndpointOptions.BindFromUri); what the // streaming modes mean is added to that refusal by OptionValueHint below. if (BudgetInputTokens is < 0) throw new ArgumentException("BudgetInputTokens must be >= 0.", nameof(BudgetInputTokens)); if (BudgetOutputTokens is < 0) throw new ArgumentException("BudgetOutputTokens must be >= 0.", nameof(BudgetOutputTokens)); if (BudgetCostUsd is < 0m) throw new ArgumentException("BudgetCostUsd must be >= 0.", nameof(BudgetCostUsd)); } /// What each streaming mode does, added to the core refusal of a value that names none. protected override string? OptionValueHint(string optionName) => optionName == nameof(Stream) ? "'stream=calls': the agent engine streams every model call inside the route; tools, the conversation and the " + "route's transaction work as without streaming, the pieces go to IAgentObserver.OnDeltaAsync and Out.Body is " + "the final text. 'stream=body': the agent run happens when the body is read, and its text streams into " + "Out.Body while the model writes it." : null; } Path: redb-route/redb.Route.Llm/LlmHeaders.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmHeaders.cs ---- namespace redb.Route.Llm; /// /// Header keys used by the LLM connector. All keys are lowercase to match /// existing transport conventions (Kafka, RabbitMQ, Http). /// public static class LlmHeaders { /// Conversation identifier — links a message to a multi-turn dialog. public const string ConversationId = "llm.conversation.id"; /// /// Marks the outbound message as a streaming response so transports /// (HttpConsumer in redb.Route.Http, WebSocket) switch to /// chunked / SSE / per-frame wire encoding instead of buffering the body. /// Set by for stream=body; stream=calls returns the final text and /// does not set it. /// public const string Streaming = "llm.streaming"; /// System prompt override for a single call. public const string SystemPrompt = "llm.system"; /// /// Fixed opening messages placed before the loaded conversation history on this call — the /// value is an of , first one a /// user turn. Rides into : sent on every /// iteration, never persisted, survives a branch rebuild. Mark the last message with /// to extend the cached prefix past the /// system prompt. /// public const string Preamble = "llm.preamble"; /// Logical role of the message: "user", "assistant", "system", "tool". public const string Role = "llm.role"; /// Model identifier resolved from the connection factory. public const string ModelId = "llm.model.id"; /// Provider identifier resolved from the connection factory ("anthropic", "openai", ...). public const string ProviderId = "llm.provider.id"; /// Token usage written by the producer after a call (input). public const string TokensIn = "llm.tokens.in"; /// Token usage written by the producer after a call (output). public const string TokensOut = "llm.tokens.out"; /// /// Prompt tokens WRITTEN to the provider's cache on this exchange, billed at a premium over /// normal input. Zero while is on usually /// means the prefix is below the provider's length floor. /// public const string CacheWriteTokens = "llm.tokens.cache.write"; /// /// Prompt tokens SERVED FROM the provider's cache on this exchange, billed at a fraction of /// normal input. /// /// This is the header that says caching works. Zero across repeated calls with an /// unchanged prefix means something in that prefix is not byte-stable — and nothing else /// reports it: is the uncached remainder, so a broken cache looks /// exactly like an expensive prompt. /// public const string CacheReadTokens = "llm.tokens.cache.read"; /// Estimated cost in USD written by the producer (optional). public const string CostUsd = "llm.cost.usd"; // ── Transcription (stt://) ──────────────────────────────────────────────── /// /// ISO-639-1 language hint for stt://, overriding the endpoint option. Written /// back after the call when the provider reports which language it heard. /// public const string TranscriptionLanguage = "llm.transcription.language"; /// Per-exchange decoding hint for stt://, overriding the endpoint option. public const string TranscriptionPrompt = "llm.transcription.prompt"; /// /// Name to upload the recording under, overriding the endpoint option. Decides which /// demuxer the speech endpoint picks, so it is the difference between a decoded voice /// note and a rejected upload. /// public const string TranscriptionFileName = "llm.transcription.fileName"; /// Speech model that produced the transcription. public const string TranscriptionModel = "llm.transcription.model"; /// Provider that produced the transcription. public const string TranscriptionProvider = "llm.transcription.provider"; /// /// Number of characters recognised (int). Deliberately the length and not the /// text: a header travels into logs and dead letters, and a transcription is the /// speaker's own words. Zero says the recording held no speech. /// public const string TranscriptionChars = "llm.transcription.chars"; /// /// Length of the recording in seconds (double), when the provider reports it — /// the unit speech APIs bill in. Absent on providers that answer with the plain /// {"text": ...} shape, which is most local servers; a caller that must have the /// number should take it from the transport that delivered the audio. /// public const string TranscriptionDuration = "llm.transcription.duration"; /// Stop reason returned by the provider: "end_turn", "tool_use", "max_tokens", "stop_sequence". public const string StopReason = "llm.stop_reason"; /// Number of tool-loop iterations consumed by the agent for this exchange. public const string ToolIterations = "llm.tool.iterations"; /// Name of the tool currently being executed (set on the child exchange forwarded by the bridge). public const string ToolName = "llm.tool.name"; /// Target endpoint URI invoked by a . public const string ToolBridgeEndpoint = "llm.tool.bridge.endpoint"; /// Tool-use identifier from the model — propagated to audit/idempotency stores. public const string ToolUseId = "llm.tool.use_id"; /// Approval identifier when a tool call awaits or has received approval. public const string ApprovalId = "llm.approval.id"; /// Async-batch identifier set by LlmCallbackProcessor when a webhook arrives. public const string BatchId = "llm.batch.id"; /// Async-batch lifecycle status ("completed" / "failed" / "cancelled"). public const string BatchStatus = "llm.batch.status"; /// True when the callback was a duplicate (already-processed batch); routes can short-circuit on this. public const string BatchDuplicate = "llm.batch.duplicate"; /// /// Conversation message id assigned by /// when appends an assistant turn from a completed batch callback /// (set only when the originating is true). /// public const string ConversationMessageId = "llm.conversation.message.id"; /// /// Stable identifier of the principal that initiated this call. Read by /// when the fluent builder declares /// .User("${header.X-User-Id}") (or any literal expression) and /// stamped on every persisted row of the run as /// MessageProps.UserId / ConversationMessageMeta.UserId. /// public const string UserId = "llm.user.id"; /// /// Header-name prefix for free-form audit tags. Any inbound exchange /// header named llm.audit.<tag> is captured by /// and stamped on every persisted row of the /// run as MessageProps.AuditTags entry { Key=<tag>, Value=<header value> }. /// Tags also accumulate from the fluent .Audit(k, v) builder; both /// sources merge (header overrides builder). /// public const string AuditTagPrefix = "llm.audit."; } Path: redb-route/redb.Route.Llm/LlmKeys.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmKeys.cs ---- namespace redb.Route.Llm; /// /// Property keys placed on IExchange.Properties by the LLM connector /// (vs. , which is the wire-format header surface). /// Properties live for the lifetime of one exchange and are not serialised to /// transport headers; they are the right place for cross-cutting per-exchange /// configuration that storage layers / engine plumbing read on the way through. /// public static class LlmKeys { /// /// Name of the named instance the LLM /// stores should write to for this exchange. Set by /// from (i.e. ?redb=my-llm-db on the URI). /// When null/empty, stores fall back to the default (unnamed) IRedbService /// from the route context — typically the host-wide instance Tsak/your app /// already registered via services.AddRedb(). /// public const string RedbName = "llm.redb.name"; } Path: redb-route/redb.Route.Llm/LlmProducer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmProducer.cs ---- using System.Diagnostics; using System.Text; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Telemetry; using redb.Route.Llm.Tools; using redb.Route.Telemetry; using redb.Route.Transactions; namespace redb.Route.Llm; /// /// LLM producer. Treats the inbound exchange as a single user turn, runs the /// agent engine to completion, and writes the assistant text into exchange.Out.Body. /// public sealed class LlmProducer : ConnectableProducer { private readonly LlmEndpoint _endpoint; private readonly LlmEndpointOptions _options; /// Creates a producer. public LlmProducer(LlmEndpoint endpoint, LlmEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"llm:{_endpoint.ConnectionFactoryName}"; /// protected override Task ConnectAsync(CancellationToken ct) => Task.CompletedTask; /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); // MessagesIn stays with the connector: it means "a user turn arrived at this llm // endpoint", which no core wrapper counts for a producer. MessagesOut/Errors/Time are // the core's (ToProcessor for a routed .To(), the ProducerTemplate for template sends) - // recording them here as well double-counted every turn (the ownership audit). _endpoint.RecordMessageIn(); await ProcessCoreAsync(exchange, ct).ConfigureAwait(false); } private async Task ProcessCoreAsync(IExchange exchange, CancellationToken ct) { // Make the configured named-redb visible to every downstream store. Read // by RedbConversationStore / RedbApprovalStore / ... via // context.GetRedbService(name, exchange), which already handles // per-exchange scoping and disposal. if (!string.IsNullOrEmpty(_options.Redb)) exchange.Properties[LlmKeys.RedbName] = _options.Redb; var factory = ResolveFactory(exchange) ?? throw new InvalidOperationException( $"LLM connection factory '{_endpoint.ConnectionFactoryName}' " + $"is not registered in the route context."); var engine = ResolveEngine(exchange) ?? throw new InvalidOperationException( "No IAgentEngine is registered. Call services.AddRedbRouteLlm() — it registers the engine " + "together with the producer template, claims source and cache the tool loop needs. A host that " + "registers one itself should use context.AddService(typeof(IAgentEngine), " + "AgentEngine.FromContext(context)), which wires the same seams: a bare new AgentEngine() " + "answers no claims and cannot dispatch a tool."); // stream=body runs the agent when the body is read, after the route. A .Transacted() block around this step // would commit before the answer exists, and the run's tools would not join it: the run is a unit of work of // its own, like any exchange that outlives its block. Refused here rather than leaving tools silently outside // the transaction the route declared, as a transacted send outside a block is refused. if (_options.Stream == LlmStreamMode.Body && (TransactedActions.IsActive(exchange) || System.Transactions.Transaction.Current is not null)) throw new InvalidOperationException( "'stream=body' runs the agent after the route, when the body is read, so inside .Transacted() its tools " + "would not join the transaction and the block would commit before the answer exists. Use " + "'stream=calls' inside a transaction: it streams every model call inside the route. Or move this " + "step out of the .Transacted() block."); // stream=body starts its span when the body is read, where the run is; the other modes run here. using var activity = _options.Stream == LlmStreamMode.Body ? null : StartActivity(factory, "complete"); var userContent = BuildUserContent(exchange); var systemPrompt = await ResolveSystemPromptAsync(exchange, ct).ConfigureAwait(false); var preamble = ResolvePreamble(exchange); var conversationId = ResolveConversationId(exchange); var tools = ResolveTools(exchange); var userId = ResolveUserId(exchange); var auditTags = ResolveAuditTags(exchange); // Endpoint-level statistics (consumed by tsak / tsak.web dashboard). // MessagesOut + Errors are tracked by ToProcessor; here we add bytes and timing. // The prompt LEAVES the endpoint. It used to be recorded as BytesIn because earlier // RecordBytesOut did not exist. Counted in UTF-8 bytes, not UTF-16 chars. var promptBytes = userContent.OfType() .Sum(b => b.Text is null ? 0 : Encoding.UTF8.GetByteCount(b.Text)); if (promptBytes > 0) _endpoint.RecordBytesOut(promptBytes); AgentRequest Request(Func? onDelta) => new() { Factory = factory, Exchange = exchange, UserContent = userContent, SystemPrompt = systemPrompt, CacheSystemPrompt = _options.CacheSystemPrompt, Preamble = preamble, Tools = tools, ConversationId = conversationId, MaxIterations = _options.MaxIterations, Budget = AgentBudgetFactory.From( _options.BudgetInputTokens, _options.BudgetOutputTokens, _options.BudgetCostUsd), Temperature = _options.Temperature, MaxTokens = _options.MaxTokens, PromptTemplateName = _options.PromptTemplateName, PromptTemplateVersion = _options.PromptTemplateVersion, UserId = userId, AuditTags = auditTags, PropagateToolHeaders = ToolHeaderPolicy.ParseCsv(_options.PropagateToolHeaders), StreamModelCalls = _options.Stream != LlmStreamMode.Off, OnDelta = onDelta }; if (_options.Stream == LlmStreamMode.Body) { StreamIntoBody(exchange, factory, engine, Request); return; } var sw = Stopwatch.StartNew(); AgentResponse response; try { response = await engine.RunAsync(Request(null), ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only our own token cancelling the run is a stop; any other failure marks the span. activity.RecordFailure(ex); throw; } sw.Stop(); WriteResponse(exchange, response, factory); RecordRun(factory, response, sw.Elapsed, activity); } /// /// stream=body: Out.Body becomes a , and the agent run happens when the body /// is read. The summary headers are written after the run, as late-bound headers; the body is released with the /// exchange. /// private void StreamIntoBody( IExchange exchange, LlmConnectionFactory factory, IAgentEngine engine, Func?, AgentRequest> request) { var body = new LazyAgentBody(async (onDelta, ct) => { using var activity = StartActivity(factory, "stream"); var textPieces = 0; var bytesIn = 0; var sw = Stopwatch.StartNew(); AgentResponse response; try { response = await engine.RunAsync(request((delta, token) => { if (delta.Kind == AgentDeltaKind.Text) { textPieces++; bytesIn += Encoding.UTF8.GetByteCount(delta.Text); } return onDelta(delta, token); }), ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only the reader's own token cancelling the run is a stop; any other failure marks the span. activity.RecordFailure(ex); // The body is read outside Producer.Process, so nothing else counts this failure for the endpoint. _endpoint.RecordError(ex); LlmMetrics.AgentRuns.Add(1, ProviderTag(factory), ModelTag(factory), FactoryTag(factory), new KeyValuePair("llm.stop_reason", "error")); throw; } // An engine that ignores AgentRequest.OnDelta would leave the body empty and report success. if (textPieces == 0 && !string.IsNullOrEmpty(response.Text)) throw new InvalidOperationException( $"The registered IAgentEngine ({engine.GetType().Name}) answered without streaming a piece of its text: " + "stream=body needs an engine that calls AgentRequest.OnDelta, as AgentEngine does."); WriteSummaryHeaders(exchange.Out!, response, factory); if (bytesIn > 0) _endpoint.RecordBytesIn(bytesIn); RecordRun(factory, response, sw.Elapsed, activity); }); ExchangeResources.ReleaseWithExchange(exchange, body.Release); exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = body; // A stream of events whatever type the request carried: Out starts as a copy of In, and a request's // text/plain would make the HTTP consumer drop the SSE framing and the summary event. exchange.Out.ContentType = "text/event-stream"; exchange.Out.Headers[LlmHeaders.Streaming] = true; exchange.Out.Headers[LlmHeaders.ProviderId] = factory.Provider; exchange.Out.Headers[LlmHeaders.ModelId] = factory.ModelId; } private Activity? StartActivity(LlmConnectionFactory factory, string operation) { // A transport span of this endpoint: redb.route.endpoint, and nothing when the context has tracing off. var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, operation == "stream" ? $"llm {factory.Provider}:{factory.ModelId} stream" : $"llm {factory.Provider}:{factory.ModelId}", ActivityKind.Client, "messaging.system", "llm", _endpoint.Uri.NormalizedKey, operation: operation); if (activity is { IsAllDataRequested: true }) { activity.SetTag("llm.provider", factory.Provider); activity.SetTag("llm.model.id", factory.ModelId); if (operation == "stream") activity.SetTag("llm.streaming", true); } return activity; } private static KeyValuePair ProviderTag(LlmConnectionFactory factory) => new("llm.provider", factory.Provider); private static KeyValuePair ModelTag(LlmConnectionFactory factory) => new("llm.model.id", factory.ModelId); private static KeyValuePair FactoryTag(LlmConnectionFactory factory) => new("llm.factory", factory.Name); private static void RecordRun(LlmConnectionFactory factory, AgentResponse response, TimeSpan elapsed, Activity? activity) { var stopTag = new KeyValuePair("llm.stop_reason", response.StopReason.ToString()); LlmMetrics.AgentRuns.Add(1, ProviderTag(factory), ModelTag(factory), FactoryTag(factory), stopTag); LlmMetrics.AgentIterations.Record(response.Iterations, ProviderTag(factory), ModelTag(factory), FactoryTag(factory)); if (activity is { IsAllDataRequested: true }) { activity.SetTag("llm.tokens.in", response.Usage.InputTokens); activity.SetTag("llm.tokens.out", response.Usage.OutputTokens); activity.SetTag("llm.tool.iterations", response.Iterations); activity.SetTag("llm.stop_reason", response.StopReason.ToString()); activity.SetTag("llm.duration.ms", elapsed.TotalMilliseconds); } } private LlmConnectionFactory? ResolveFactory(IExchange exchange) { if (_endpoint.ResolvedFactory is not null) return _endpoint.ResolvedFactory; // Late resolution — useful when the factory is registered after the endpoint is built. var ctx = (_endpoint.Component as ComponentBase)?.Context; return ctx?.GetFromRegistry(_endpoint.ConnectionFactoryName); } private IAgentEngine? ResolveEngine(IExchange exchange) { if (_endpoint.ResolvedEngine is not null) return _endpoint.ResolvedEngine; var ctx = (_endpoint.Component as ComponentBase)?.Context; return ctx is null ? null : AgentEngine.FindRegistered(ctx); } private static IReadOnlyList BuildUserContent(IExchange exchange) { var body = exchange.In.Body; var text = body switch { null => string.Empty, string s => s, _ => BodyText.Of(body) }; return [new LlmTextBlock(text)]; } private async ValueTask ResolveSystemPromptAsync(IExchange exchange, CancellationToken ct) { // Header wins, then endpoint option. Endpoint option supports the framework-wide // "#name" registry-ref convention: ?systemPromptRef=#watchdog resolves to the latest // PromptTemplate named "watchdog", falling back to a string in the route-context registry. if (exchange.In.Headers.TryGetValue(LlmHeaders.SystemPrompt, out var hdr) && hdr is string s && s.Length > 0) return s; var ctx = (_endpoint.Component as ComponentBase)?.Context; var sp = ctx?.GetServiceProvider(); var templates = sp?.GetService() ?? ctx?.GetService(); return await PromptRef.ResolveAsync(_options.SystemPromptRef, templates, ctx, exchange, ct).ConfigureAwait(false); } /// /// Fixed opening messages from the header. Header only — /// there is no endpoint option: a preamble is assembled per call by whoever assembles the /// system prompt (it is the same kind of thing), and a URI has nowhere to carry a list of /// typed messages. Anything but a sequence of is treated as absent. /// private static IReadOnlyList ResolvePreamble(IExchange exchange) => exchange.In.Headers.TryGetValue(LlmHeaders.Preamble, out var hdr) && hdr is IEnumerable messages ? [.. messages] : []; private string? ResolveConversationId(IExchange exchange) => _options.Conversation switch { "header" => exchange.In.GetHeader(LlmHeaders.ConversationId), "property" => exchange.RouteId, _ => null }; private IReadOnlyList ResolveTools(IExchange exchange) { var ctx = (_endpoint.Component as ComponentBase)?.Context; var registry = ctx?.GetService(); return ToolFilter.Resolve(registry, _options.Tools); } /// /// Resolves the principal id stamped on every persisted row of this run. /// Order: ?user= option (literal or ${header.X} expression), /// then the llm.user.id header. Returns null when neither is set — /// callers downstream record the row with a null UserId rather than fail. /// private string? ResolveUserId(IExchange exchange) { var resolved = ResolveExpression(_options.User, exchange); if (!string.IsNullOrEmpty(resolved)) return resolved; return exchange.In.GetHeader(LlmHeaders.UserId); } /// /// Resolves audit tags from two sources: the ?audit= CSV option and /// any inbound header named llm.audit.<name>. Headers merge on /// top of option values (header wins on collision). Returns null when no /// tags are configured so the persistence layer can skip the column. /// private IReadOnlyDictionary? ResolveAuditTags(IExchange exchange) { Dictionary? tags = null; // 1. Builder-side CSV (key=value,key=${header.X}). if (!string.IsNullOrEmpty(_options.Audit)) { foreach (var pair in _options.Audit.Split(',', StringSplitOptions.RemoveEmptyEntries)) { var eq = pair.IndexOf('='); if (eq <= 0) continue; var key = System.Web.HttpUtility.UrlDecode(pair[..eq]); var rawValue = System.Web.HttpUtility.UrlDecode(pair[(eq + 1)..]); var resolved = ResolveExpression(rawValue, exchange) ?? string.Empty; if (string.IsNullOrEmpty(key)) continue; tags ??= new Dictionary(StringComparer.Ordinal); tags[key] = resolved; } } // 2. Header-driven tags (llm.audit.) — header wins on collision. foreach (var kv in exchange.In.Headers) { if (kv.Key.Length <= LlmHeaders.AuditTagPrefix.Length) continue; if (!kv.Key.StartsWith(LlmHeaders.AuditTagPrefix, StringComparison.Ordinal)) continue; var key = kv.Key[LlmHeaders.AuditTagPrefix.Length..]; if (string.IsNullOrEmpty(key)) continue; var value = kv.Value switch { null => string.Empty, string s => s, _ => kv.Value.ToString() ?? string.Empty }; tags ??= new Dictionary(StringComparer.Ordinal); tags[key] = value; } return tags; } /// /// Lightweight resolver for ${header.NAME} / ${property.NAME} /// expressions. Anything else is returned as a literal so callers can use /// fixed values ("system") just as easily as references. /// private static string? ResolveExpression(string? expression, IExchange exchange) { if (string.IsNullOrEmpty(expression)) return expression; if (!expression.StartsWith("${", StringComparison.Ordinal) || !expression.EndsWith("}", StringComparison.Ordinal)) return expression; var inner = expression[2..^1]; if (inner.StartsWith("header.", StringComparison.Ordinal)) { var name = inner[7..]; return exchange.In.Headers.TryGetValue(name, out var v) && v is not null ? v.ToString() : null; } if (inner.StartsWith("property.", StringComparison.Ordinal)) { var name = inner[9..]; return exchange.Properties.TryGetValue(name, out var v) && v is not null ? v.ToString() : null; } // Unknown prefix — keep the original expression so producers / observers // can detect the misconfiguration instead of silently dropping it. return expression; } private static void WriteResponse(IExchange exchange, AgentResponse response, LlmConnectionFactory factory) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = response.Text; WriteSummaryHeaders(exchange.Out, response, factory); } /// The summary of a run: on the reply of an in-route run, late-bound on a stream=body reply. private static void WriteSummaryHeaders(IMessage message, AgentResponse response, LlmConnectionFactory factory) { message.Headers[LlmHeaders.ProviderId] = factory.Provider; message.Headers[LlmHeaders.ModelId] = factory.ModelId; message.Headers[LlmHeaders.TokensIn] = response.Usage.InputTokens; message.Headers[LlmHeaders.TokensOut] = response.Usage.OutputTokens; // Written unconditionally, zeros included: a caller that reads "cache read = 0" learns // something (the cache is not being hit), while a missing header is indistinguishable // from an older engine that never reported it. message.Headers[LlmHeaders.CacheWriteTokens] = response.Usage.CacheCreationInputTokens; message.Headers[LlmHeaders.CacheReadTokens] = response.Usage.CacheReadInputTokens; message.Headers[LlmHeaders.ToolIterations] = response.Iterations; message.Headers[LlmHeaders.StopReason] = response.StopReason.ToString(); } } Path: redb-route/redb.Route.Llm/LlmStreamMode.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/LlmStreamMode.cs ---- namespace redb.Route.Llm; /// How an llm: step streams (stream=). public enum LlmStreamMode { /// No streaming (the option is absent): every model call waits for the whole answer. Off, /// /// stream=calls: the agent engine makes every model call as a stream, inside the route. Tools, the /// conversation, the budget and the route's transaction work as without streaming; the pieces go to /// , and Out.Body is the final text. The /// connection carries data while the model writes, which keeps long calls alive through tunnels and proxies. /// Calls, /// /// stream=body: Out.Body is an of strings, and the agent run — /// tools, conversation, budget — happens when the body is read, after the route, the way a streamed SQL result is /// read. The visible text of every model call streams as the model writes it, for HTTP (SSE), WebSocket and gRPC /// consumers to forward; the summary headers arrive after the run. The body belongs to its exchange: it is read /// once, released with the exchange, and refused by RequestBody. Refused inside .Transacted(): the /// block would commit before the answer exists; use there. /// Body } Path: redb-route/redb.Route.Llm/Providers/AnthropicModelProfile.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/AnthropicModelProfile.cs ---- namespace redb.Route.Llm.Providers; /// /// Contract generation of an Anthropic model, as it affects how a Messages-API /// request must be shaped. The Anthropic wire contract changed across generations: /// current-generation models reject the sampling knobs /// (temperature/top_p/top_k) with HTTP 400, whereas older /// generations accept them. The tier drives request building so the provider never /// sends a field the target model will reject. /// public enum AnthropicModelTier { /// /// Older generation (Sonnet 4.5 / Haiku 4.5 and earlier, Claude 3.x). /// Accepts temperature/top_p/top_k. /// Legacy, /// /// Transitional generation (Opus 4.6 / Sonnet 4.6). Still accepts sampling knobs. /// Transitional, /// /// Current generation (Opus 4.7 / 4.8 / 5, Sonnet 5, Fable 5, and — by the /// fail-forward default — any unrecognised newer id). Rejects sampling /// knobs with HTTP 400. /// Modern } /// /// How the target model accepts the sampling knobs (temperature/top_p). /// The contract is not binary — it has three states across generations: /// public enum AnthropicSamplingPolicy { /// Claude 3.x — temperature and top_p may both be sent. Both, /// /// Claude 4.0–4.6 (incl. Sonnet/Haiku 4.5 and Opus/Sonnet 4.6) — at most one /// of temperature/top_p; sending both returns HTTP 400. /// AtMostOne, /// /// Claude 4.7+ / 5 — non-default sampling is rejected with HTTP 400 (omitting the /// field, or passing its default, is accepted). The connector omits them entirely. /// None } /// /// Capability descriptor for an Anthropic model: which request fields the target /// model accepts. Resolved from the model id by using a static /// generation table plus a fail-forward default — an unrecognised id is /// treated as so a future model release does /// not get sent a now-removed field and 400. /// /// This is Anthropic-scoped on purpose (the OpenAI-compatible providers accept /// sampling and need no such gating). Generalise to an IModelProfile only if a /// second provider ever needs per-model request shaping. /// /// public readonly record struct AnthropicModelProfile(AnthropicModelTier Tier, AnthropicSamplingPolicy Sampling) { /// /// Whether any sampling knob may be sent at all. only for /// (current-generation models — sending /// temperature/top_p yields HTTP 400). Note that /// still allows one knob; /// consult directly to shape the request. /// public bool SamplingSupported => Sampling != AnthropicSamplingPolicy.None; /// /// Resolves the profile for . When /// is a recognised tier name /// (legacy/transitional/modern, case-insensitive) it wins — /// the escape-hatch for self-hosted ids, proxies, or snapshots the table does not /// know. Otherwise the id is classified by generation, defaulting to /// when no version can be read. /// public static AnthropicModelProfile Resolve(string? modelId, string? tierOverride = null) { if (TryParseTier(tierOverride, out var forced)) // An explicit tier override maps to the safe sampling policy for that tier: // any sampling-accepting model tolerates a single knob, so AtMostOne is the // safe superset for legacy/transitional; modern omits sampling. return new AnthropicModelProfile( forced, forced == AnthropicModelTier.Modern ? AnthropicSamplingPolicy.None : AnthropicSamplingPolicy.AtMostOne); TryReadVersion(modelId, out var major, out var minor); return new AnthropicModelProfile( ClassifyByGeneration(major, minor), ClassifySampling(major, minor)); } /// Parses an explicit tier-name override; returns false when unset/unknown. public static bool TryParseTier(string? name, out AnthropicModelTier tier) { switch (name?.Trim().ToLowerInvariant()) { case "legacy": tier = AnthropicModelTier.Legacy; return true; case "transitional": tier = AnthropicModelTier.Transitional; return true; case "modern": tier = AnthropicModelTier.Modern; return true; default: tier = AnthropicModelTier.Modern; return false; } } /// /// Classifies a (major, minor) version into a contract tier. Rules: /// /// major ≥ 5 → Modern (Opus/Sonnet/Fable 5); /// major 4, minor ≥ 7 → Modern (Opus 4.7 / 4.8); /// major 4, minor == 6 → Transitional (Opus/Sonnet 4.6); /// major 4, minor ≤ 5 → Legacy (Sonnet 4.5 / Haiku 4.5); /// major ≤ 3 → Legacy (Claude 3.x); /// no version (major < 0) → Modern (fail-forward for future ids). /// /// private static AnthropicModelTier ClassifyByGeneration(int major, int minor) { if (major < 0) return AnthropicModelTier.Modern; // unknown/future id — assume current contract if (major >= 5) return AnthropicModelTier.Modern; if (major == 4) { if (minor >= 7) return AnthropicModelTier.Modern; // 4.7, 4.8 if (minor == 6) return AnthropicModelTier.Transitional; // 4.6 return AnthropicModelTier.Legacy; // 4.5 and lower, or none } return AnthropicModelTier.Legacy; // 3.x and older } /// /// Classifies a (major, minor) version into a sampling policy — the state that /// actually shapes the wire request: /// /// major ≤ 3 → (Claude 3.x accepts both knobs); /// major 4, minor ≤ 6 → (Claude 4.0–4.6: both → 400); /// major 4, minor ≥ 7 or major ≥ 5 → (4.7+/5 reject non-default sampling); /// no version (major < 0) → (fail-forward). /// /// private static AnthropicSamplingPolicy ClassifySampling(int major, int minor) { if (major < 0) return AnthropicSamplingPolicy.None; // unknown/future id if (major <= 3) return AnthropicSamplingPolicy.Both; // Claude 3.x if (major == 4 && minor <= 6) return AnthropicSamplingPolicy.AtMostOne; // 4.0–4.6 return AnthropicSamplingPolicy.None; // 4.7+ / 5 } /// /// Extracts (major, minor) from a model id. Normalises '.'→'-', lowercases, and /// treats the first two short numeric tokens (1–2 digits) as major/minor — /// skipping long tokens such as an 8-digit date snapshot. /// is -1 when absent. Returns false when no version token is present. /// private static bool TryReadVersion(string? modelId, out int major, out int minor) { major = -1; minor = -1; if (string.IsNullOrWhiteSpace(modelId)) return false; var normalized = modelId.Replace('.', '-'); foreach (var token in normalized.Split('-', StringSplitOptions.RemoveEmptyEntries)) { // Version components are 1–2 digits; longer all-digit tokens are dates (e.g. 20251001). if (token.Length is < 1 or > 2) continue; if (!int.TryParse(token, out var n)) continue; if (major < 0) { major = n; continue; } minor = n; break; } return major >= 0; } } Path: redb-route/redb.Route.Llm/Providers/AnthropicProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/AnthropicProvider.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Runtime.CompilerServices; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using Microsoft.Extensions.Logging; using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Providers; /// /// Transport for Anthropic's Messages API (POST {baseUrl}/v1/messages). /// Maps to Anthropic's messages/tools/ /// tool_use/tool_result content-block model and parses /// from the standard response envelope. /// /// Streaming is true SSE — content blocks are reassembled from /// content_block_start/content_block_delta/content_block_stop /// events; tool-use blocks accumulate partial JSON in input_json_delta /// and surface as a single complete at the end /// of their block. /// /// /// Error mapping: HTTP 429 → (honours /// retry-after); HTTP 529 ("overloaded") and HTTP 5xx → /// . Other failures surface as /// . /// /// public sealed class AnthropicProvider : ILlmProvider { private const string AnthropicVersion = "2023-06-01"; private static readonly Uri DefaultBaseUrl = new("https://api.anthropic.com/"); private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web) { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, WriteIndented = false, // Match JsonMessageSerializer.DefaultOptions: emit Cyrillic/emoji/&/>/< as UTF-8, // not \uXXXX. Affects request body to Anthropic (safe — it accepts both) and the // re-encoded tool_use input string surfaced as LlmToolUseBlock.InputJson, which is // what shows up in `[SHELL-TOOL] ▶ in=…` logs. Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private readonly LlmConnectionFactory _factory; private readonly HttpClient _http; private readonly Uri _endpoint; private readonly ILogger? _logger; // The factory's model id and contract tier are fixed for this provider, so its profile is // resolved once; only a per-request ModelId override triggers a fresh resolve (see BuildRequestBody). private readonly AnthropicModelProfile _factoryProfile; /// Creates the provider with a connection factory (builds an internal HttpClient). public AnthropicProvider(LlmConnectionFactory factory) : this(factory, BuildDefaultClient(factory)) { } /// Creates the provider with an externally owned HttpClient. public AnthropicProvider(LlmConnectionFactory factory, HttpClient http) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _http = http ?? throw new ArgumentNullException(nameof(http)); _logger = factory.LoggerFactory?.CreateLogger("redb.Route.Llm.AnthropicProvider"); _factoryProfile = AnthropicModelProfile.Resolve(factory.ModelId, factory.ModelContractTier); var baseUrl = factory.BaseUrl ?? DefaultBaseUrl; _endpoint = new Uri(EnsureTrailingSlash(baseUrl), "v1/messages"); } /// public string ProviderId => "anthropic"; /// public string ModelId => _factory.ModelId; /// /// Limited as a whole by . public Task CompleteAsync(LlmRequest request, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); return LlmHttpTransport.WithinCallLimitAsync(_factory, ProviderId, t => CompleteCoreAsync(request, t), ct); } private async Task CompleteCoreAsync(LlmRequest request, CancellationToken ct) { var body = BuildRequestBody(request, stream: false); using var http = new HttpRequestMessage(HttpMethod.Post, _endpoint) { Content = JsonContent.Create(body, options: JsonOpts), // HttpClient's DefaultRequestVersion applies only to messages the client creates // itself; a hand-built message starts at HTTP/1.1. Carry the client's defaults over, // otherwise the HTTP/2 keep-alive pings of BuildDefaultHandler never happen. Version = _http.DefaultRequestVersion, VersionPolicy = _http.DefaultVersionPolicy, }; ApplyHeaders(http); using var resp = await _http.SendAsync(http, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) await ThrowMappedAsync(resp, ct).ConfigureAwait(false); var json = await resp.Content.ReadFromJsonAsync(JsonOpts, ct).ConfigureAwait(false) ?? throw new InvalidOperationException("anthropic: empty response body."); return ParseResponse(json); } /// /// Anthropic SSE streaming. Pieces are yielded as they arrive: visible text as , the /// model's thinking as . The last chunk carries the completed tool calls and /// : the stream assembled into the message a plain call returns and read by /// the same parser, so thinking keeps its signature and the streamed answer cannot differ from the plain one. /// public async IAsyncEnumerable StreamAsync( LlmRequest request, [EnumeratorCancellation] CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); var body = BuildRequestBody(request, stream: true); using var http = new HttpRequestMessage(HttpMethod.Post, _endpoint) { Content = JsonContent.Create(body, options: JsonOpts), // HttpClient's DefaultRequestVersion applies only to messages the client creates // itself; a hand-built message starts at HTTP/1.1. Carry the client's defaults over, // otherwise the HTTP/2 keep-alive pings of BuildDefaultHandler never happen. Version = _http.DefaultRequestVersion, VersionPolicy = _http.DefaultVersionPolicy, }; http.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); ApplyHeaders(http); // RequestTimeoutMs covers the whole call, the stream included; StreamIdleTimeoutMs the waits on the provider. using var call = new LlmStreamCall(_factory, ProviderId, ct); using var resp = await call.SendAsync(_http, http).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) await ThrowMappedAsync(resp, ct).ConfigureAwait(false); using var stream = await call.OpenAsync(resp).ConfigureAwait(false); using var reader = new StreamReader(stream); // The stream is assembled into the message a plain call returns and read by the same parser, so the streamed // answer cannot differ from the plain one: blocks in their order, thinking with its signature, redacted // thinking, tool input, usage, the stop reason and the message id. JsonObject? message = null; var blocks = new SortedDictionary(); var toolInputs = new Dictionary(); var usage = new JsonObject(); string? rawStop = null; JsonNode? stopSequence = null; string? currentEvent = null; while (await call.ReadLineAsync(reader).ConfigureAwait(false) is { } line) { if (line.Length == 0) { currentEvent = null; continue; } if (line.StartsWith("event:", StringComparison.Ordinal)) { currentEvent = line.AsSpan(6).Trim().ToString(); continue; } if (!line.StartsWith("data:", StringComparison.Ordinal)) continue; var payload = line.AsSpan(5).Trim().ToString(); if (payload.Length == 0) continue; var frame = LlmStreamFrames.Read(ProviderId, payload); var evt = currentEvent ?? LlmStreamFrames.Text(frame["type"]); switch (evt) { case "message_start": message = frame["message"] is JsonObject started ? (JsonObject)started.DeepClone() : throw new InvalidOperationException( $"anthropic: message_start without a message: {LlmStreamFrames.Shown(payload)}"); if (message["usage"] is JsonObject startUsage) Overlay(usage, startUsage); break; case "content_block_start": { var index = BlockIndex(frame, payload); var block = frame["content_block"] is JsonObject startedBlock ? (JsonObject)startedBlock.DeepClone() : throw new InvalidOperationException( $"anthropic: content_block_start without a block: {LlmStreamFrames.Shown(payload)}"); blocks[index] = block; if (LlmStreamFrames.Text(block["type"]) == "tool_use") toolInputs[index] = new StringBuilder(); break; } case "content_block_delta": { var index = BlockIndex(frame, payload); if (!blocks.TryGetValue(index, out var block)) throw new InvalidOperationException( $"anthropic: a delta for block {index}, which never started: {LlmStreamFrames.Shown(payload)}"); var delta = frame["delta"] as JsonObject; switch (LlmStreamFrames.Text(delta?["type"])) { case "text_delta" when LlmStreamFrames.Text(delta!["text"]) is { Length: > 0 } piece: block["text"] = LlmStreamFrames.Text(block["text"]) + piece; yield return new LlmStreamChunk([new LlmTextBlock(piece)], StopReason: null, Usage: null); break; case "thinking_delta" when LlmStreamFrames.Text(delta!["thinking"]) is { Length: > 0 } piece: block["thinking"] = LlmStreamFrames.Text(block["thinking"]) + piece; yield return new LlmStreamChunk([new LlmThinkingBlock(piece)], StopReason: null, Usage: null); break; case "signature_delta": block["signature"] = LlmStreamFrames.Text(block["signature"]) + LlmStreamFrames.Text(delta!["signature"]); break; case "input_json_delta": if (!toolInputs.TryGetValue(index, out var input)) throw new InvalidOperationException( $"anthropic: tool input for block {index}, which is not a tool call: {LlmStreamFrames.Shown(payload)}"); input.Append(LlmStreamFrames.Text(delta!["partial_json"])); break; // Other deltas (citations_delta and the like) carry what the plain parser does not read either. } break; } case "content_block_stop": FinishToolInput(blocks, toolInputs, BlockIndex(frame, payload)); break; case "message_delta": if (frame["delta"] is JsonObject messageDelta) { if (LlmStreamFrames.Text(messageDelta["stop_reason"]) is { Length: > 0 } stopReason) rawStop = stopReason; stopSequence = messageDelta["stop_sequence"]?.DeepClone(); } // Running counts: what message_delta reports replaces what message_start did. if (frame["usage"] is JsonObject deltaUsage) Overlay(usage, deltaUsage); break; case "error": { var err = frame["error"] as JsonObject; var type = err?["type"]?.GetValue() ?? "unknown"; var errorMessage = err?["message"]?.GetValue() ?? "stream error"; if (type == "overloaded_error") throw new LlmTransientException(ProviderId, $"anthropic SSE overloaded: {errorMessage}"); if (type == "rate_limit_error") throw new LlmRateLimitException(ProviderId, $"anthropic SSE rate limit: {errorMessage}"); throw new HttpRequestException($"anthropic SSE error ({type}): {errorMessage}"); } // message_stop and ping carry nothing to take. Event types this reader does not know are skipped: // Anthropic adds new ones and documents that clients ignore those they do not know. } } foreach (var index in toolInputs.Keys.ToList()) FinishToolInput(blocks, toolInputs, index); // Without a stop_reason the model never said it was done: the connection ended mid-answer, and handing the // pieces on as a finished answer would store a cut one. if (message is null || rawStop is null) throw new InvalidOperationException( "anthropic: the stream ended before the model said why it stopped (no stop_reason); the answer is cut."); var content = new JsonArray(); foreach (var block in blocks.Values) content.Add(block); message["content"] = content; message["stop_reason"] = rawStop; message["stop_sequence"] = stopSequence; message["usage"] = usage; var response = ParseResponse(message); yield return new LlmStreamChunk( [.. response.Content.OfType()], response.StopReason, response.Usage) { Response = response }; } private static int BlockIndex(JsonObject frame, string payload) => frame["index"] is JsonValue value && value.TryGetValue(out var index) ? index : throw new InvalidOperationException( $"anthropic: a block event without an index: {LlmStreamFrames.Shown(payload)}"); /// Puts the streamed input of a finished tool block in place of the start block's empty one. private static void FinishToolInput( SortedDictionary blocks, Dictionary inputs, int index) { if (!inputs.Remove(index, out var input) || input.Length == 0) return; JsonNode? parsed; try { parsed = JsonNode.Parse(input.ToString()); } catch (JsonException ex) { throw new InvalidOperationException( $"anthropic: the streamed input of tool block {index} is not JSON: {LlmStreamFrames.Shown(input.ToString())}", ex); } blocks[index]["input"] = parsed; } private static void Overlay(JsonObject target, JsonObject source) { foreach (var (key, value) in source) target[key] = value?.DeepClone(); } /// The package's default client for model calls: HTTP/2 with keep-alive pings (). internal static HttpClient BuildDefaultClient(LlmConnectionFactory factory) => LlmHttpTransport.BuildClient(factory); /// Transport of the default client (). internal static SocketsHttpHandler BuildDefaultHandler() => LlmHttpTransport.BuildHandler(); private void ApplyHeaders(HttpRequestMessage http) { var key = _factory.ApiKey; if (!string.IsNullOrWhiteSpace(key)) http.Headers.TryAddWithoutValidation("x-api-key", key); http.Headers.TryAddWithoutValidation("anthropic-version", AnthropicVersion); } private JsonObject BuildRequestBody(LlmRequest request, bool stream) { var model = request.ModelId ?? _factory.ModelId; var body = new JsonObject { ["model"] = model, // Anthropic requires max_tokens; default conservatively when caller omits it. ["max_tokens"] = request.MaxTokens ?? _factory.MaxTokens ?? 1024, ["messages"] = BuildMessages(request) }; if (!string.IsNullOrWhiteSpace(request.SystemPrompt)) { // A plain string is the ordinary shape. Caching needs the block form, because // cache_control is a property OF a content block — there is nowhere to hang it on a // bare string. One block, marked: the provider caches everything rendered up to that // point, which is tools + system, and later turns re-read it instead of re-paying. body["system"] = request.CacheSystemPrompt ? new JsonArray(new JsonObject { ["type"] = "text", ["text"] = request.SystemPrompt, ["cache_control"] = new JsonObject { ["type"] = "ephemeral" }, }) : request.SystemPrompt; } // The sampling knobs (temperature/top_p) changed contract across Anthropic // generations: Claude 3.x accepts both, Claude 4.0–4.6 accepts at most one (both // → 400), Claude 4.7+/5 reject non-default sampling entirely (→ 400). Shape the // request by the target model's policy so we never send a field it will reject; // unknown ids default to the modern (no-sampling) contract — see AnthropicModelProfile. // Reuse the factory profile unless the request overrides the model id. var profile = (request.ModelId is null || request.ModelId == _factory.ModelId) ? _factoryProfile : AnthropicModelProfile.Resolve(model, _factory.ModelContractTier); ApplySampling(body, request, model, profile); // Effort ladder (Claude 4.6+ / Sonnet 5 / Opus 5): output_config.effort. Only when the // factory asks for it — the field is unknown to older models and to Haiku 4.5. if (!string.IsNullOrWhiteSpace(_factory.Effort)) body["output_config"] = new JsonObject { ["effort"] = _factory.Effort.Trim() }; if (request.StopSequences is { Count: > 0 } stops) { var arr = new JsonArray(); foreach (var s in stops) arr.Add(s); body["stop_sequences"] = arr; } if (request.Tools.Count > 0) { var tools = new JsonArray(); foreach (var cap in request.Tools) tools.Add(MapTool(cap)); body["tools"] = tools; } if (stream) body["stream"] = true; return body; } /// /// Writes temperature/top_p onto the request body according to the model's /// : both when allowed, a single preferred knob on /// 4.0–4.6 (temperature wins), or neither on 4.7+/5. Anything dropped that the caller set /// leaves an llm.sampling.dropped breadcrumb on the current activity so /// "why is temperature ignored?" is answerable. /// private void ApplySampling(JsonObject body, LlmRequest request, string model, AnthropicModelProfile profile) { switch (profile.Sampling) { case AnthropicSamplingPolicy.Both: if (request.Temperature is { } t0) body["temperature"] = t0; if (request.TopP is { } p0) body["top_p"] = p0; break; case AnthropicSamplingPolicy.AtMostOne: // Both knobs together 400 on Claude 4.0–4.6; prefer temperature and drop top_p. if (request.Temperature is { } t1) { body["temperature"] = t1; if (request.TopP is not null) NoteDropped(model, profile, "top_p", "accepts at most one sampling knob"); } else if (request.TopP is { } p1) { body["top_p"] = p1; } break; case AnthropicSamplingPolicy.None: if (request.Temperature is not null && request.TopP is not null) NoteDropped(model, profile, "temperature,top_p", "sampling removed on this model"); else if (request.Temperature is not null) NoteDropped(model, profile, "temperature", "sampling removed on this model"); else if (request.TopP is not null) NoteDropped(model, profile, "top_p", "sampling removed on this model"); break; } } private void NoteDropped(string model, AnthropicModelProfile profile, string dropped, string reason) { // Warn on the logger (when wired) and leave a span event either way, so a dropped knob // is answerable via logs and traces — never silent. _logger?.LogWarning( "anthropic: model '{Model}' ({Tier}) {Reason}; dropped {Dropped}. " + "Steer via the system prompt, or set LlmConnectionFactory.ModelContractTier to override.", model, profile.Tier, reason, dropped); System.Diagnostics.Activity.Current?.AddEvent(new System.Diagnostics.ActivityEvent( "llm.sampling.dropped", tags: new System.Diagnostics.ActivityTagsCollection { ["llm.model.id"] = model, ["llm.model.tier"] = profile.Tier.ToString(), ["llm.sampling.policy"] = profile.Sampling.ToString(), ["llm.sampling.dropped_params"] = dropped, ["llm.sampling.reason"] = reason })); } /// True for a request block of kind thinking or redacted_thinking. private static bool IsThinkingBlock(JsonNode? block) => block?["type"]?.GetValue() is "thinking" or "redacted_thinking"; private static JsonArray BuildMessages(LlmRequest request) { var arr = new JsonArray(); foreach (var m in request.Messages) { // Anthropic accepts only "user" and "assistant". Tool results are // user-role messages containing tool_result blocks (Anthropic's own // convention — no normalisation needed here). var role = m.Role == "assistant" ? "assistant" : "user"; var content = new JsonArray(); foreach (var b in m.Content) { switch (b) { // Whitespace-only text is rejected by the API the same way as empty text // ("text content blocks must be non-empty"), so it is dropped here too. case LlmTextBlock tb when !string.IsNullOrWhiteSpace(tb.Text): content.Add(new JsonObject { ["type"] = "text", ["text"] = tb.Text }); break; // A thinking block goes back exactly as it arrived: redacted thinking as its data // payload, plain thinking as text plus the signature. The wire has no form for an // unsigned block (another provider's reasoning after a provider switch): a thinking // block without a signature is rejected, so it is not written into the request. case LlmThinkingBlock th when th.IsRedacted: content.Add(new JsonObject { ["type"] = "redacted_thinking", ["data"] = th.RedactedData }); break; case LlmThinkingBlock th when !string.IsNullOrEmpty(th.Signature): content.Add(new JsonObject { ["type"] = "thinking", ["thinking"] = th.Text, ["signature"] = th.Signature }); break; case LlmToolUseBlock tu: content.Add(new JsonObject { ["type"] = "tool_use", ["id"] = tu.ToolUseId, ["name"] = tu.Name, ["input"] = ParseJsonOrEmpty(tu.InputJson) }); break; case LlmToolResultBlock tr: var trBlock = new JsonObject { ["type"] = "tool_result", ["tool_use_id"] = tr.ToolUseId, ["content"] = tr.OutputJson }; if (tr.IsError) trBlock["is_error"] = true; content.Add(trBlock); break; } } // A message with nothing to continue from is not sent at all: no block left, or nothing // but thinking (a turn the model spent entirely on thinking, kept in the record). An // empty reply used to become an empty text block, and the API rejects those with 400 // "text content blocks must be non-empty" — so ONE empty assistant reply persisted in a // conversation made every later call of that conversation fail until the history was // edited by hand (2026-09-07). A lone thinking block is not put in front of the API // either. Skipping is safe: the API merges consecutive same-role turns. if (content.All(IsThinkingBlock)) continue; // A message-level breakpoint lands on the message's LAST block: cache_control is a // property of a content block, and the cache prefix runs up to the marked block // inclusive. if (m.CacheBreakpoint) content[^1]!.AsObject()["cache_control"] = new JsonObject { ["type"] = "ephemeral" }; arr.Add(new JsonObject { ["role"] = role, ["content"] = content }); } // The API also rejects an empty messages array; that can only happen when every // message was empty, and then the honest request is a single empty-handed user turn. if (arr.Count == 0) { arr.Add(new JsonObject { ["role"] = "user", ["content"] = new JsonArray(new JsonObject { ["type"] = "text", ["text"] = "…" }) }); } return arr; } /// /// Projects a capability into the provider's tools[] entry. Only the name, the description /// and the input schema travel: is server-side metadata and never /// appears on the wire. /// private static JsonObject MapTool(LlmToolCapability cap) { var schema = ParseJsonOrEmpty(cap.InputSchema) as JsonObject ?? new JsonObject { ["type"] = "object" }; return new JsonObject { ["name"] = cap.Name, ["description"] = cap.Description, ["input_schema"] = schema }; } private static JsonNode ParseJsonOrEmpty(string json) { if (string.IsNullOrWhiteSpace(json)) return new JsonObject(); try { return JsonNode.Parse(json) ?? new JsonObject(); } catch (JsonException) { return new JsonObject(); } } private static LlmResponse ParseResponse(JsonObject json) { var blocks = new List(); if (json["content"] is JsonArray content) { foreach (var node in content) { if (node is not JsonObject block) continue; var type = block["type"]?.GetValue(); switch (type) { case "text": var text = block["text"]?.GetValue() ?? string.Empty; blocks.Add(new LlmTextBlock(text)); break; // The model's thinking comes back signed, and the signature is what the API // verifies on the way in — so the block travels on untouched, text and signature // together, into the next request of the same run. case "thinking": var thinkingText = block["thinking"]?.GetValue() ?? string.Empty; var signature = block["signature"]?.GetValue(); blocks.Add(new LlmThinkingBlock(thinkingText, signature)); break; // redacted_thinking: the model reasoned, the API withheld the text and returned an // opaque payload instead. There is nothing to read — only something to hand back. case "redacted_thinking": blocks.Add(new LlmThinkingBlock( string.Empty, RedactedData: block["data"]?.GetValue())); break; case "tool_use": var id = block["id"]?.GetValue() ?? Guid.NewGuid().ToString("N"); var name = block["name"]?.GetValue() ?? string.Empty; var input = block["input"]?.ToJsonString(JsonOpts) ?? "{}"; blocks.Add(new LlmToolUseBlock(id, name, input)); break; } } } if (blocks.Count == 0) blocks.Add(new LlmTextBlock(string.Empty)); var rawStop = json["stop_reason"]?.GetValue(); var stop = MapStopReason(rawStop); var usage = LlmUsage.Empty; if (json["usage"] is JsonObject u) { var inT = u["input_tokens"]?.GetValue() ?? 0; var outT = u["output_tokens"]?.GetValue() ?? 0; usage = new LlmUsage( inT, outT, u["cache_creation_input_tokens"]?.GetValue() ?? 0, u["cache_read_input_tokens"]?.GetValue() ?? 0); } return new LlmResponse { Content = blocks, StopReason = stop, Usage = usage, RawStopReason = rawStop, ProviderResponseId = json["id"]?.GetValue() }; } private static LlmStopReason MapStopReason(string? raw) => raw switch { "end_turn" => LlmStopReason.EndTurn, "tool_use" => LlmStopReason.ToolUse, "max_tokens" => LlmStopReason.MaxTokens, "stop_sequence" => LlmStopReason.StopSequence, _ => LlmStopReason.Other }; private async Task ThrowMappedAsync(HttpResponseMessage resp, CancellationToken ct) { var raw = await SafeReadAsync(resp, ct).ConfigureAwait(false); var summary = $"anthropic: {(int)resp.StatusCode} {resp.ReasonPhrase} from {_endpoint}"; // The mapping itself moved to LlmHttpErrors so the OpenAI family can share it — two // copies of "which status means retry" drift apart, and the drift is invisible until // production. Behaviour here is unchanged, including the soft "overloaded" 529. throw LlmHttpErrors.FromResponse(ProviderId, resp, $"{summary}. Body: {raw}", raw); } private static Uri EnsureTrailingSlash(Uri uri) { var s = uri.ToString(); return s.EndsWith('/') ? uri : new Uri(s + "/"); } private static async Task SafeReadAsync(HttpResponseMessage resp, CancellationToken ct) { try { return await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); } catch { return ""; } } } Path: redb-route/redb.Route.Llm/Providers/IEmbeddingProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/IEmbeddingProvider.cs ---- namespace redb.Route.Llm.Providers; /// /// Pure transport over an embeddings API — turns text into vectors. The sibling /// of for the retrieval half of RAG: chunks are /// embedded on ingest, the query is embedded on search, and /// ranks by cosine /// similarity. Implementations do protocol work only (serialise, HTTP, /// deserialise); chunking, storage and ranking live elsewhere. /// public interface IEmbeddingProvider { /// Provider identifier ("openai", "mistral", "together", ...). string ProviderId { get; } /// Embedding model id this provider was configured with. string ModelId { get; } /// /// Embeds each input text and returns one vector per input, in the same order. /// An empty returns an empty list. /// Task> EmbedAsync(IReadOnlyList inputs, CancellationToken ct = default); /// Convenience single-text embed. Returns an empty array when the provider returns nothing. async Task EmbedOneAsync(string input, CancellationToken ct = default) { var vectors = await EmbedAsync(new[] { input }, ct).ConfigureAwait(false); return vectors.Count > 0 ? vectors[0] : Array.Empty(); } } Path: redb-route/redb.Route.Llm/Providers/ILlmProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/ILlmProvider.cs ---- namespace redb.Route.Llm.Providers; /// /// Pure transport abstraction over an LLM API. Implementations are responsible /// for protocol-level work only: serialise , call the /// provider's HTTP/SDK, deserialise . /// /// Tool dispatch, conversation persistence, budget enforcement and shadow-mode /// belong to , not here. /// /// public interface ILlmProvider { /// Provider identifier ("anthropic", "openai", "stub", ...). string ProviderId { get; } /// Model identifier this provider was configured with. string ModelId { get; } /// Performs a single non-streaming completion call. Task CompleteAsync(LlmRequest request, CancellationToken ct = default); /// /// Performs a streaming completion. Yields the pieces as they arrive (visible text as /// , thinking as ) and ends with a chunk that /// carries the stop reason, the usage and : the whole answer, /// exactly what returns for it. A stream that ends before the model said /// why it stopped is a cut answer and fails. Default implementation buffers /// as a single chunk — override for true token-streaming. /// async IAsyncEnumerable StreamAsync( LlmRequest request, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct = default) { var response = await CompleteAsync(request, ct).ConfigureAwait(false); yield return new LlmStreamChunk(response.Content, response.StopReason, response.Usage) { Response = response }; } } Path: redb-route/redb.Route.Llm/Providers/ITranscriptionProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/ITranscriptionProvider.cs ---- namespace redb.Route.Llm.Providers; /// /// Pure transport over a speech-to-text API — turns recorded audio into text. The /// third sibling of and : /// implementations do protocol work only (encode the upload, HTTP, decode the /// answer). Deciding whether a recording is worth transcribing, what to do with an /// empty result and who pays for it belongs to the route, not here. /// public interface ITranscriptionProvider { /// Provider identifier ("openai", "groq", "local", ...). string ProviderId { get; } /// Speech model id this provider was configured with. string ModelId { get; } /// Transcribes one recording. Task TranscribeAsync(TranscriptionRequest request, CancellationToken ct = default); } /// /// One recording to transcribe. /// /// The encoded audio, exactly as it arrived from its transport. /// /// Name to upload the audio under, e.g. voice.oga. Not cosmetic: speech /// endpoints pick the demuxer by extension, and an .ogg/opus recording sent as /// file is a decode error on most servers rather than a transcription. /// /// /// ISO-639-1 hint ("ru"). Null lets the model detect it — more forgiving on /// mixed speech, measurably worse on short recordings, where a couple of words in one /// language are routinely detected as another. /// /// /// Optional decoding hint, in the model's own words: names and terms it would not /// otherwise spell right. Hints can also displace what was actually said, so this is /// deliberately something a caller opts into. /// public readonly record struct TranscriptionRequest( ReadOnlyMemory Audio, string FileName, string? Language = null, string? Prompt = null); /// /// What came back. /// /// /// The recognised text, trimmed. Empty when the recording holds no speech — silence /// and music transcribe to nothing, and that is an answer, not a failure. /// /// Language the provider reports it heard, when it reports one. /// /// Length of the recording, when the provider reports it. The unit speech APIs bill in, /// so it is the number to record against a run — but it is optional in the response, /// which is why a caller that must have it should take it from its own transport instead. /// public readonly record struct TranscriptionResult( string Text, string? Language = null, double? DurationSeconds = null); Path: redb-route/redb.Route.Llm/Providers/LlmExceptions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/LlmExceptions.cs ---- using System; using System.Net.Http; namespace redb.Route.Llm.Providers; /// /// Turns a failed HTTP response into the right provider exception. One place, because the /// mapping is the same for every OpenAI-shaped API and getting it wrong is invisible: a caller /// that cannot tell 429 from 401 either retries a dead key forever or gives up on a queue that /// would have cleared in a second. /// public static class LlmHttpErrors { /// /// Builds the exception for a non-2xx response: 429 → /// (honouring Retry-After in both its delta and date forms), 5xx and the soft /// "overloaded" 529 → , anything else → /// carrying the status. /// /// Provider identifier, for the exception payload. /// The failed response; only status and headers are read. /// Ready-made message — providers word their own summaries. /// Response body already read by the caller, for diagnostics. public static Exception FromResponse( string providerId, HttpResponseMessage response, string message, string? rawBody) { ArgumentNullException.ThrowIfNull(response); var status = (int)response.StatusCode; if (status == 429) { TimeSpan? retryAfter = null; if (response.Headers.RetryAfter is { } header) { if (header.Delta is { } delta) retryAfter = delta; else if (header.Date is { } when) retryAfter = when - DateTimeOffset.UtcNow; } return new LlmRateLimitException(providerId, message, retryAfter, rawBody); } // 529 is Anthropic's soft "overloaded"; it is not a standard code, and treating it as // transient is right for anyone who ever returns it. if (status == 529 || status is >= 500 and <= 599) return new LlmTransientException(providerId, message, status, rawBody); return new HttpRequestException(message, inner: null, statusCode: response.StatusCode); } } /// /// Provider signalled rate limiting (HTTP 429). Distinct from /// because the caller should respect /// rather than retry immediately. /// public sealed class LlmRateLimitException : Exception { /// Provider identifier ("anthropic", "openai", ...). public string ProviderId { get; } /// Suggested wait time before retry, if the provider sent one. public TimeSpan? RetryAfter { get; } /// Raw response body for diagnostics. public string? RawBody { get; } /// Creates a rate-limit exception. public LlmRateLimitException(string providerId, string message, TimeSpan? retryAfter = null, string? rawBody = null, Exception? inner = null) : base(message, inner) { ProviderId = providerId; RetryAfter = retryAfter; RawBody = rawBody; } } /// /// Transient provider failure that is safe to retry (HTTP 5xx, Anthropic's /// overloaded 529, network resets). The caller is expected /// to apply its own back-off / circuit-breaker policy. A call that ran out of /// its time limit is , not this. /// public sealed class LlmTransientException : Exception { /// Provider identifier. public string ProviderId { get; } /// HTTP status code, when known. public int? StatusCode { get; } /// Raw response body for diagnostics. public string? RawBody { get; } /// Creates a transient-failure exception. public LlmTransientException(string providerId, string message, int? statusCode = null, string? rawBody = null, Exception? inner = null) : base(message, inner) { ProviderId = providerId; StatusCode = statusCode; RawBody = rawBody; } } /// Which limit of a model call ran out. public enum LlmTimeoutKind { /// : the whole call, streamed or not. Call, /// : the provider sent nothing for too long. StreamIdle } /// /// A limit of the call to the model ran out (). /// covers the whole call, waiting for the response and reading it, streamed or not, whatever client sends it; /// covers a stream's silence. A cancellation by the caller is /// not this: it stays an . Retrying the same call with the same limit usually /// runs out again; a long generation needs a larger . /// public sealed class LlmTimeoutException : TimeoutException { /// Provider identifier. public string ProviderId { get; } /// Name of the connection factory whose limit ran out, when it has one. public string? FactoryName { get; } /// The limit that ran out. public TimeSpan Limit { get; } /// Which limit ran out. public LlmTimeoutKind Kind { get; } /// Creates a timeout exception. public LlmTimeoutException( string providerId, string? factoryName, TimeSpan limit, LlmTimeoutKind kind, string message, Exception? inner = null) : base(message, inner) { ProviderId = providerId; FactoryName = factoryName; Limit = limit; Kind = kind; } } Path: redb-route/redb.Route.Llm/Providers/LlmHttpTransport.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/LlmHttpTransport.cs ---- using System.Net; namespace redb.Route.Llm.Providers; /// /// The HTTP client every model call of this package goes through when the caller does not bring its own. /// /// A non-streaming call is one request whose answer arrives only when the model has finished: tens of seconds, /// minutes for a thinking model or a long recording, with nothing crossing the wire. VPN tunnels, NAT and proxies /// drop a TLS connection that stays silent for about 50 seconds, and the caller then sees "The response ended /// prematurely" at that mark; a retry is just as long. The client asks for HTTP/2 (HTTP/1.1 stays the fallback) and /// sends a PING frame every 15 seconds while a request is in flight, which keeps the connection visibly alive /// without touching the request. Over HTTP/1.1, and on a plain http:// endpoint, no pings are sent and nothing /// changes. Measured 2026-09-04 through a VPN tunnel: 45 s of silence survived, 55 s was cut; with a ping every /// 15 s four consecutive 50-second waits all completed. /// /// /// The MCP transport keeps a copy of : that package does not reference this one. /// /// internal static class LlmHttpTransport { /// The handler: HTTP/2 keep-alive pings every 15 seconds while a request is in flight. internal static SocketsHttpHandler BuildHandler() => new() { PooledConnectionLifetime = TimeSpan.FromMinutes(5), KeepAlivePingDelay = TimeSpan.FromSeconds(15), KeepAlivePingTimeout = TimeSpan.FromSeconds(20), KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests, }; /// /// A client on that asks for HTTP/2. It has no timeout of its own: the factory's /// is applied per call (). /// internal static HttpClient BuildClient(LlmConnectionFactory factory) { ArgumentNullException.ThrowIfNull(factory); return new HttpClient(BuildHandler()) { // HttpClient.Timeout stops at the response headers under ResponseHeadersRead, which every provider // uses; it cannot be the limit of a call whose body arrives minutes after the headers. Timeout = System.Threading.Timeout.InfiniteTimeSpan, // HTTP/2 when the server offers it, so the keep-alive pings have a frame to ride on. DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower, }; } /// The factory's limit on one call: , at least a second. internal static TimeSpan CallLimit(LlmConnectionFactory factory) => TimeSpan.FromMilliseconds(Math.Max(1000, factory.RequestTimeoutMs)); /// /// Runs one non-streaming call within the factory's limit: waiting for the response and reading it, whatever /// client sends it. The client's own cannot do this: with /// it stops at the headers, and a server that sends them at /// once and holds the body until the model has finished (DeepSeek does) was never limited at all. Running out /// throws ; a cancellation by the caller stays an /// . /// internal static async Task WithinCallLimitAsync( LlmConnectionFactory factory, string providerId, Func> call, CancellationToken ct) { var limit = CallLimit(factory); using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(limit); try { return await call(cts.Token).ConfigureAwait(false); } catch (OperationCanceledException ex) when (cts.IsCancellationRequested && !ct.IsCancellationRequested) { throw new LlmTimeoutException(providerId, factory.Name, limit, LlmTimeoutKind.Call, $"{providerId}: the call did not finish within RequestTimeoutMs = {limit.TotalMilliseconds:0} ms" + $"{OfFactory(factory)}. The limit covers waiting for the answer and reading it; a long generation " + "needs a larger RequestTimeoutMs.", ex); } } private static string OfFactory(LlmConnectionFactory factory) => string.IsNullOrEmpty(factory.Name) ? string.Empty : $" (factory '{factory.Name}')"; /// /// A request that carries the client's HTTP version. applies only to /// messages the client creates itself; a hand-built message starts at HTTP/1.1, and then the pings never happen. /// internal static HttpRequestMessage NewRequest(HttpClient client, HttpMethod method, Uri uri) => new(method, uri) { Version = client.DefaultRequestVersion, VersionPolicy = client.DefaultVersionPolicy, }; } Path: redb-route/redb.Route.Llm/Providers/LlmRequest.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/LlmRequest.cs ---- using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Providers; /// Single message in the conversation transcript sent to the provider. public sealed class LlmMessage { /// "user", "assistant", "system", or "tool". public required string Role { get; init; } /// Ordered content blocks for this message. public IReadOnlyList Content { get; init; } = []; /// /// Ask the provider to place a prompt-cache breakpoint after this message: everything /// rendered up to and including it (tools, system, the messages before it, this one) becomes a /// cacheable prefix that later requests re-read instead of re-paying. /// /// Meant for a byte-stable preamble that opens every conversation — a fixed opening /// exchange, a few-shot block — placed via . The /// system-prompt breakpoint () stops at the system /// block; without a second one, a preamble sitting in messages is billed in full on /// every turn. Same rules as the system-prompt cache: the prefix must not change a byte, there /// is a model-dependent length floor, and providers without a cache concept ignore the flag. /// Anthropic allows four breakpoints per request; the system one, when asked for, is the /// first. /// public bool CacheBreakpoint { get; init; } /// Convenience constructor for plain-text user messages. public static LlmMessage User(string text) => new() { Role = "user", Content = [new LlmTextBlock(text)] }; /// Convenience constructor for plain-text assistant messages. public static LlmMessage Assistant(string text) => new() { Role = "assistant", Content = [new LlmTextBlock(text)] }; } /// Base type for content blocks (text, tool-use, tool-result, thinking). public abstract record LlmContentBlock; /// Plain text block. public sealed record LlmTextBlock(string Text) : LlmContentBlock; /// /// Tool-use block emitted by the assistant — engine must dispatch the tool and /// reply with a matching . /// public sealed record LlmToolUseBlock(string ToolUseId, string Name, string InputJson) : LlmContentBlock; /// Tool-result block sent back to the assistant on the next turn. public sealed record LlmToolResultBlock(string ToolUseId, string OutputJson, bool IsError = false) : LlmContentBlock; /// /// Token usage reported by the provider. /// /// is the UNCACHED remainder, not the whole prompt. /// The prompt is the sum of all three: what was billed at full price, what was written to cache /// this turn, and what was read back from it. A long agentic run that reports four thousand input /// tokens has not shrunk — the rest came from cache. /// /// Prompt tokens billed at full price. /// Generated tokens. /// /// Tokens written to the cache this turn, billed at a premium over normal input. Staying at zero /// while caching is requested usually means the prefix is below the provider's length floor. /// /// /// Tokens served from cache, billed at a fraction of normal input. **This is the number that says /// caching works.** Zero across repeated calls with an unchanged prefix means something in that /// prefix is not byte-stable. /// public sealed record LlmUsage( int InputTokens, int OutputTokens, int CacheCreationInputTokens = 0, int CacheReadInputTokens = 0) { /// Empty usage record. public static LlmUsage Empty { get; } = new(0, 0); } /// Reason the provider stopped generating. public enum LlmStopReason { /// End of assistant turn. EndTurn, /// Assistant requested one or more tool calls. ToolUse, /// Hit the max-tokens limit. MaxTokens, /// Hit a stop sequence configured on the request. StopSequence, /// Other / unknown reason — see provider-specific raw value. Other } /// Single completion request sent to a provider. public sealed class LlmRequest { /// Model identifier (overrides the factory default when set). public string? ModelId { get; init; } /// Optional system prompt. public string? SystemPrompt { get; init; } /// Conversation history including the current user turn. public IReadOnlyList Messages { get; init; } = []; /// Tool capabilities exposed to the model. Empty = no tools. public IReadOnlyList Tools { get; init; } = []; /// Sampling temperature. public double? Temperature { get; init; } /// Maximum output tokens. public int? MaxTokens { get; init; } /// Top-p sampling parameter. public double? TopP { get; init; } /// Optional stop sequences. public IReadOnlyList? StopSequences { get; init; } /// /// Ask the provider to mark the system prompt as cacheable, so repeated turns re-read it /// instead of paying for it again. /// /// Only worth setting when the system prompt is byte-stable across requests. /// Caching is a prefix match: the provider renders tools, then system, then messages, and any /// byte change invalidates everything after it. A system prompt carrying a timestamp, a user /// name, or anything else that varies per request will simply never be read back — you pay /// the write premium for nothing. /// /// There is a length floor and it is model-dependent (roughly 1–4k tokens on /// current Anthropic models). A shorter prefix silently does not cache: no error, and /// cache_creation_input_tokens stays at zero. That, and cache_read_input_tokens /// staying at zero across repeated calls, are the two things to look at when it seems not to /// work. /// /// Providers that have no cache concept ignore this flag. /// public bool CacheSystemPrompt { get; init; } } /// Single completion response from a provider. public sealed class LlmResponse { /// Content blocks produced by the assistant in this turn. public required IReadOnlyList Content { get; init; } /// Reason the provider stopped generating. public required LlmStopReason StopReason { get; init; } /// Token usage for this turn. public LlmUsage Usage { get; init; } = LlmUsage.Empty; /// Provider-native raw stop reason for diagnostics. public string? RawStopReason { get; init; } /// /// Opaque backend-configuration fingerprint surfaced by some providers /// (OpenAI's system_fingerprint; xAI / Together echo it; Anthropic /// does not). When two otherwise identical calls return different /// fingerprints, the model was re-released under the same id — the only /// signal an auditor has to detect silent provider drift. /// public string? ProviderSystemFingerprint { get; init; } /// /// Provider-issued response identifier (OpenAI / xAI / Together: top-level /// id; Anthropic: top-level id). Used by auditors to /// cross-reference a persisted row with the provider's own usage / billing /// logs. Null when the provider does not surface one. /// public string? ProviderResponseId { get; init; } } /// /// Single chunk yielded by . Non-final chunks have = /// null and carry the pieces as they arrive: visible text as , the model's thinking as /// without a signature. A piece is partial; the assembled blocks are in /// of the last chunk, which also carries the completed tool calls in . /// public sealed record LlmStreamChunk( IReadOnlyList Content, LlmStopReason? StopReason, LlmUsage? Usage) { /// /// The whole answer assembled from the stream, exactly what returns for /// the same answer: blocks in the order they arrived, thinking with its signature, tool calls, usage, the stop /// reason and its raw value, the response id. Set on the last chunk only. /// public LlmResponse? Response { get; init; } } Path: redb-route/redb.Route.Llm/Providers/LlmStreamCall.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/LlmStreamCall.cs ---- namespace redb.Route.Llm.Providers; /// /// The limits of one streamed call to the model. runs from the /// send to the last line, the stream included, as it does for a plain call. , /// when set, runs only while the reader waits on the provider for a line and stops as soon as the line is in, so a /// reader that takes its time between pieces is not taken for a silent provider. Running out throws /// naming the limit; a cancellation by the caller stays an /// . /// internal sealed class LlmStreamCall : IDisposable { private readonly LlmConnectionFactory _factory; private readonly string _providerId; private readonly CancellationToken _caller; private readonly TimeSpan _callLimit; private readonly TimeSpan? _idleLimit; private readonly CancellationTokenSource _call; private readonly CancellationTokenSource _idle; internal LlmStreamCall(LlmConnectionFactory factory, string providerId, CancellationToken ct) { _factory = factory; _providerId = providerId; _caller = ct; _callLimit = LlmHttpTransport.CallLimit(factory); _idleLimit = factory.StreamIdleTimeoutMs is { } idleMs ? TimeSpan.FromMilliseconds(idleMs) : null; _call = CancellationTokenSource.CreateLinkedTokenSource(ct); _call.CancelAfter(_callLimit); _idle = CancellationTokenSource.CreateLinkedTokenSource(_call.Token); } /// Sends the request and opens the response within the whole-call limit. internal async Task SendAsync(HttpClient client, HttpRequestMessage request) { try { return await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _call.Token).ConfigureAwait(false); } catch (OperationCanceledException ex) when (TimedOut(ex) is { } timeout) { throw timeout; } } /// The body of a successful response, within the whole-call limit. internal async Task OpenAsync(HttpResponseMessage response) { try { return await response.Content.ReadAsStreamAsync(_call.Token).ConfigureAwait(false); } catch (OperationCanceledException ex) when (TimedOut(ex) is { } timeout) { throw timeout; } } /// The next line from the provider, within both limits; null at the end of the stream. internal async Task ReadLineAsync(StreamReader reader) { if (_idleLimit is { } idle) _idle.CancelAfter(idle); try { return await reader.ReadLineAsync(_idle.Token).ConfigureAwait(false); } catch (OperationCanceledException ex) when (TimedOut(ex) is { } timeout) { throw timeout; } finally { // The silence clock stops while the reader is busy with the line: that time is the reader's, not the // provider's. if (_idleLimit is not null && !_idle.IsCancellationRequested) _idle.CancelAfter(System.Threading.Timeout.InfiniteTimeSpan); } } /// The timeout a cancellation stands for, or null when the caller cancelled. private LlmTimeoutException? TimedOut(OperationCanceledException ex) { if (_caller.IsCancellationRequested) return null; var ofFactory = string.IsNullOrEmpty(_factory.Name) ? string.Empty : $" (factory '{_factory.Name}')"; if (_call.IsCancellationRequested) return new LlmTimeoutException(_providerId, _factory.Name, _callLimit, LlmTimeoutKind.Call, $"{_providerId}: the streamed call did not finish within RequestTimeoutMs = {_callLimit.TotalMilliseconds:0} ms" + $"{ofFactory}. The limit covers the whole call, the stream included; a long generation needs a larger " + "RequestTimeoutMs.", ex); if (_idle.IsCancellationRequested && _idleLimit is { } idle) return new LlmTimeoutException(_providerId, _factory.Name, idle, LlmTimeoutKind.StreamIdle, $"{_providerId}: the stream sent nothing for StreamIdleTimeoutMs = {idle.TotalMilliseconds:0} ms{ofFactory}: " + "no text, no thinking, not even a keep-alive.", ex); return null; } /// public void Dispose() { _idle.Dispose(); _call.Dispose(); } } Path: redb-route/redb.Route.Llm/Providers/LlmStreamFrames.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/LlmStreamFrames.cs ---- using System.Text.Json; using System.Text.Json.Nodes; namespace redb.Route.Llm.Providers; /// /// Reading the data: frames of a provider's SSE stream. A frame that cannot be read is lost text or a lost tool /// call: skipping it would hand on a shorter answer as a whole one, so it fails, and the message shows the frame. /// internal static class LlmStreamFrames { private const int MaxShown = 500; /// The frame as a JSON object; anything else fails with the frame in the message. internal static JsonObject Read(string providerId, string payload) { JsonNode? node; try { node = JsonNode.Parse(payload); } catch (JsonException ex) { throw new InvalidOperationException($"{providerId}: a stream frame is not JSON: {Shown(payload)}", ex); } return node as JsonObject ?? throw new InvalidOperationException($"{providerId}: a stream frame is not a JSON object: {Shown(payload)}"); } /// The string value of , or null when it is absent or not a string. internal static string? Text(JsonNode? node) => node is JsonValue value && value.TryGetValue(out var text) ? text : null; /// cut to a length a log line can carry. internal static string Shown(string text) => text.Length <= MaxShown ? text : string.Concat(text.AsSpan(0, MaxShown), "…"); } Path: redb-route/redb.Route.Llm/Providers/LlmThinkingBlock.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/LlmThinkingBlock.cs ---- namespace redb.Route.Llm.Providers; /// /// Thinking / reasoning block returned by a provider that exposes its chain of thought — /// Anthropic thinking and redacted_thinking, DeepSeek reasoning_content. /// /// The block is opaque unless the provider returns text. It belongs to the assistant /// turn that produced it and travels with that turn, unchanged and in the original order: on the /// next request of the same run and, when a conversation store is configured, on a later run of the /// same conversation, whichever provider that run asks. It is not an answer: it never reaches /// AgentResponse.Text or Out.Body. /// /// Each request path writes what its wire can express. Anthropic verifies /// , so that path sends a signed block or a redacted one exactly as received /// and has no form for an unsigned block. is the redacted_thinking /// variant: an encrypted payload with no readable text. DeepSeek signs nothing; the OpenAI-compatible /// path sends back as reasoning_content when the request declares tools. /// The provider and model that produced a stored block are recorded on its message, not on the /// block. /// /// Readable reasoning text; empty for a redacted block, and empty when the provider omits the text but still signs the block. /// Provider signature that authenticates ; null when the provider does not sign. /// Encrypted payload of a redacted_thinking block; null otherwise. public sealed record LlmThinkingBlock( string Text, string? Signature = null, string? RedactedData = null) : LlmContentBlock { /// True for a redacted_thinking block: data without visible text. public bool IsRedacted => !string.IsNullOrEmpty(RedactedData); } Path: redb-route/redb.Route.Llm/Providers/OpenAiEmbeddingProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/OpenAiEmbeddingProvider.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; namespace redb.Route.Llm.Providers; /// /// Transport for any OpenAI-compatible embeddings endpoint /// (POST {baseUrl}/embeddings, body {"model":..,"input":[..]}, /// response {"data":[{"index":i,"embedding":[..]}]}). /// /// One implementation, many providers — same /// (Provider / BaseUrl / ApiKey / ModelId) as , so it /// talks to OpenAI, Mistral, Together, DeepSeek, Gemini (compat), vLLM, /// llama.cpp, Ollama, LM Studio, … Set /// to the embedding model (e.g. text-embedding-3-small), not the chat model. /// /// public sealed class OpenAiEmbeddingProvider : IEmbeddingProvider { private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web) { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, WriteIndented = false, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private readonly LlmConnectionFactory _factory; private readonly HttpClient _http; private readonly Uri _endpoint; private readonly string _providerId; /// Creates the provider with an externally owned . public OpenAiEmbeddingProvider(LlmConnectionFactory factory, HttpClient http) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _http = http ?? throw new ArgumentNullException(nameof(http)); var baseUrl = factory.BaseUrl ?? OpenAiProvider.ResolveDefaultBaseUrl(factory.Provider); _endpoint = new Uri(EnsureTrailingSlash(baseUrl), "embeddings"); _providerId = string.IsNullOrWhiteSpace(factory.Provider) ? "openai" : factory.Provider!.ToLowerInvariant(); } /// /// Convenience constructor that builds an internal HttpClient. The factory's timeout is applied per call /// ( covers the whole call), not by the client. /// public static OpenAiEmbeddingProvider Create(LlmConnectionFactory factory) { ArgumentNullException.ThrowIfNull(factory); var http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan }; return new OpenAiEmbeddingProvider(factory, http); } /// public string ProviderId => _providerId; /// public string ModelId => _factory.ModelId; /// /// Limited as a whole by . public Task> EmbedAsync(IReadOnlyList inputs, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(inputs); if (inputs.Count == 0) return Task.FromResult>(Array.Empty()); return LlmHttpTransport.WithinCallLimitAsync(_factory, _providerId, t => EmbedCoreAsync(inputs, t), ct); } private async Task> EmbedCoreAsync(IReadOnlyList inputs, CancellationToken ct) { var inputArray = new JsonArray(); foreach (var s in inputs) inputArray.Add(JsonValue.Create(s ?? string.Empty)); var body = new JsonObject { ["model"] = _factory.ModelId, ["input"] = inputArray }; using var http = new HttpRequestMessage(HttpMethod.Post, _endpoint) { Content = JsonContent.Create(body, options: JsonOpts) }; ApplyAuthHeaders(http); using var resp = await _http.SendAsync(http, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) { var raw = await SafeReadAsync(resp, ct).ConfigureAwait(false); // Typed, like the chat providers: a caller that cannot tell "wait and retry" from // "your key is wrong" can only degrade blindly. Retrieval degrades to keyword on // ANY failure, so an expired key would look exactly like a busy server. throw LlmHttpErrors.FromResponse( _providerId, resp, $"{_providerId} embeddings: {(int)resp.StatusCode} {resp.ReasonPhrase} from {_endpoint}. Body: {raw}", raw); } var json = await resp.Content.ReadFromJsonAsync(JsonOpts, ct).ConfigureAwait(false) ?? throw new InvalidOperationException($"{_providerId} embeddings: empty response body."); return ParseEmbeddings(json); } private static IReadOnlyList ParseEmbeddings(JsonObject json) { if (json["data"] is not JsonArray data) throw new InvalidOperationException("embeddings response is missing the 'data' array."); var result = new float[data.Count][]; for (var i = 0; i < data.Count; i++) { var item = data[i] as JsonObject ?? throw new InvalidOperationException("embeddings 'data' item is not an object."); var vecArr = item["embedding"] as JsonArray ?? throw new InvalidOperationException("embeddings item is missing the 'embedding' array."); var vec = new float[vecArr.Count]; for (var j = 0; j < vecArr.Count; j++) vec[j] = vecArr[j]!.GetValue(); // Honour the provider-reported index so the order matches the inputs. var index = item["index"]?.GetValue() ?? i; if (index >= 0 && index < result.Length) result[index] = vec; else result[i] = vec; } for (var i = 0; i < result.Length; i++) result[i] ??= Array.Empty(); return result; } private void ApplyAuthHeaders(HttpRequestMessage http) { var key = _factory.ApiKey; if (string.IsNullOrWhiteSpace(key)) return; http.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key); if (_providerId == "openrouter") { http.Headers.TryAddWithoutValidation("HTTP-Referer", "https://github.com/redb-stack/redb.Route"); http.Headers.TryAddWithoutValidation("X-Title", "redb.Route.Llm"); } } private static async Task SafeReadAsync(HttpResponseMessage resp, CancellationToken ct) { try { return await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); } catch { return ""; } } private static Uri EnsureTrailingSlash(Uri uri) { var s = uri.ToString(); return s.EndsWith('/') ? uri : new Uri(s + "/"); } } Path: redb-route/redb.Route.Llm/Providers/OpenAiProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/OpenAiProvider.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Runtime.CompilerServices; using System.Text.Json; using System.Text.Json.Nodes; using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Providers; /// /// Transport for any OpenAI-compatible Chat Completions endpoint /// (POST {baseUrl}/chat/completions). /// /// One implementation, many providers. By switching /// + + /// the same provider talks to OpenAI, Groq, Cerebras, OpenRouter, Google Gemini /// (compat mode), GitHub Models, Mistral, Together, HuggingFace router, DeepSeek, /// xAI Grok, LM Studio, vLLM, llama.cpp server and Ollama. /// /// /// Maps ↔ OpenAI messages/tools/tool_calls /// and ↔ choices[0].message + finish_reason /// + usage. Streaming falls back to the buffered default of /// . /// /// public sealed class OpenAiProvider : ILlmProvider { private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web) { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, WriteIndented = false, // Send prompts as UTF-8, not \uXXXX (matches AnthropicProvider) — smaller // request body and no needless escaping of non-ASCII content. Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private readonly LlmConnectionFactory _factory; private readonly HttpClient _http; private readonly Uri _endpoint; private readonly string _providerId; /// Creates the provider with an externally owned . public OpenAiProvider(LlmConnectionFactory factory, HttpClient http) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _http = http ?? throw new ArgumentNullException(nameof(http)); var baseUrl = factory.BaseUrl ?? ResolveDefaultBaseUrl(factory.Provider); _endpoint = new Uri(EnsureTrailingSlash(baseUrl), "chat/completions"); _providerId = string.IsNullOrWhiteSpace(factory.Provider) ? "openai" : factory.Provider!.ToLowerInvariant(); } /// /// Convenience constructor that builds the package's default client: the factory timeout, HTTP/2 with keep-alive /// pings while a request is in flight (a thinking model's call is minutes of silence on the wire). /// public static OpenAiProvider Create(LlmConnectionFactory factory) { ArgumentNullException.ThrowIfNull(factory); return new OpenAiProvider(factory, LlmHttpTransport.BuildClient(factory)); } /// public string ProviderId => _providerId; /// The client this provider sends through (tests read its transport defaults). internal HttpClient Http => _http; /// public string ModelId => _factory.ModelId; /// Default base URL applied when is null. public static Uri ResolveDefaultBaseUrl(string? providerKey) => (providerKey ?? "openai").ToLowerInvariant() switch { "openai" => new("https://api.openai.com/v1/"), "anthropic" or "claude" => new("https://api.anthropic.com/v1/"), "groq" => new("https://api.groq.com/openai/v1/"), "cerebras" => new("https://api.cerebras.ai/v1/"), "openrouter" => new("https://openrouter.ai/api/v1/"), "gemini" or "google" => new("https://generativelanguage.googleapis.com/v1beta/openai/"), "github-models" or "github" => new("https://models.inference.ai.azure.com/"), "mistral" => new("https://api.mistral.ai/v1/"), "together" or "togetherai" => new("https://api.together.xyz/v1/"), "huggingface" or "hf" => new("https://router.huggingface.co/v1/"), // DeepSeek's documented base is the ROOT, unlike everyone else's /v1 (checked 2026-09-10 // against api-docs.deepseek.com after the V4.1-Flash release; /v1 still answers as a // legacy alias but vanished from the docs, so the canonical form is the durable one). "deepseek" => new("https://api.deepseek.com/"), "grok" or "xai" => new("https://api.x.ai/v1/"), "ollama" => new("http://localhost:11434/v1/"), "lmstudio" => new("http://localhost:1234/v1/"), _ => new("https://api.openai.com/v1/") }; /// /// Limited as a whole by . public Task CompleteAsync(LlmRequest request, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); return LlmHttpTransport.WithinCallLimitAsync(_factory, _providerId, t => CompleteCoreAsync(request, t), ct); } private async Task CompleteCoreAsync(LlmRequest request, CancellationToken ct) { var body = BuildRequestBody(request, stream: false); using var http = LlmHttpTransport.NewRequest(_http, HttpMethod.Post, _endpoint); http.Content = JsonContent.Create(body, options: JsonOpts); ApplyAuthHeaders(http); using var resp = await _http.SendAsync(http, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) { var raw = await SafeReadAsync(resp, ct).ConfigureAwait(false); throw LlmHttpErrors.FromResponse( _providerId, resp, $"{_providerId}: {(int)resp.StatusCode} {resp.ReasonPhrase} from {_endpoint}. Body: {raw}", raw); } var json = await resp.Content.ReadFromJsonAsync(JsonOpts, ct).ConfigureAwait(false) ?? throw new InvalidOperationException($"{_providerId}: empty response body."); return ParseResponse(json); } /// /// True OpenAI SSE streaming. Pieces are yielded as they arrive: visible text as , the /// model's reasoning (reasoning_content, reasoning) as . The last chunk /// carries the completed tool calls and : the stream assembled into the JSON a /// plain call returns and read by the same parser, so the streamed answer cannot differ from the plain one. /// public async IAsyncEnumerable StreamAsync( LlmRequest request, [EnumeratorCancellation] CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); var body = BuildRequestBody(request, stream: true); body["stream_options"] = new JsonObject { ["include_usage"] = true }; using var http = LlmHttpTransport.NewRequest(_http, HttpMethod.Post, _endpoint); http.Content = JsonContent.Create(body, options: JsonOpts); http.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); ApplyAuthHeaders(http); // RequestTimeoutMs covers the whole call, the stream included; StreamIdleTimeoutMs the waits on the provider. using var call = new LlmStreamCall(_factory, _providerId, ct); using var resp = await call.SendAsync(_http, http).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) { var raw = await SafeReadAsync(resp, ct).ConfigureAwait(false); throw LlmHttpErrors.FromResponse( _providerId, resp, $"{_providerId}: {(int)resp.StatusCode} {resp.ReasonPhrase} from {_endpoint}. Body: {raw}", raw); } using var stream = await call.OpenAsync(resp).ConfigureAwait(false); using var reader = new StreamReader(stream); var content = new System.Text.StringBuilder(); var reasoningContent = new System.Text.StringBuilder(); var reasoning = new System.Text.StringBuilder(); var toolCalls = new SortedDictionary(); string? responseId = null; string? fingerprint = null; string? rawStop = null; JsonObject? usage = null; while (await call.ReadLineAsync(reader).ConfigureAwait(false) is { } line) { // Blank lines end an event, ':' lines are comments (keep-alives), 'event:' / 'id:' carry nothing here. if (!line.StartsWith("data:", StringComparison.Ordinal)) continue; var payload = line.AsSpan(5).Trim().ToString(); if (payload.Length == 0) continue; if (payload == "[DONE]") break; var frame = LlmStreamFrames.Read(_providerId, payload); if (frame["error"] is JsonObject error) throw new HttpRequestException( $"{_providerId}: the stream reported an error: {LlmStreamFrames.Shown(error.ToJsonString())}"); responseId ??= LlmStreamFrames.Text(frame["id"]); fingerprint ??= LlmStreamFrames.Text(frame["system_fingerprint"]); // Usage comes on a terminal usage-only frame (no choices); kept whole, so the plain parser reads it. if (frame["usage"] is JsonObject frameUsage) usage = (JsonObject)frameUsage.DeepClone(); if (frame["choices"] is not JsonArray { Count: > 0 } choices || choices[0] is not JsonObject choice) continue; var delta = choice["delta"] as JsonObject; var emitted = new List(); if (delta is not null) { // Reasoning before text, the order a plain answer lists them in. if (LlmStreamFrames.Text(delta["reasoning_content"]) is { Length: > 0 } reasoningPiece) { reasoningContent.Append(reasoningPiece); emitted.Add(new LlmThinkingBlock(reasoningPiece)); } if (LlmStreamFrames.Text(delta["reasoning"]) is { Length: > 0 } otherReasoningPiece) { reasoning.Append(otherReasoningPiece); emitted.Add(new LlmThinkingBlock(otherReasoningPiece)); } if (LlmStreamFrames.Text(delta["content"]) is { Length: > 0 } deltaText) { content.Append(deltaText); emitted.Add(new LlmTextBlock(deltaText)); } if (delta["tool_calls"] is JsonArray tcArr) { foreach (var tc in tcArr) { if (tc is not JsonObject tcObj) continue; var idx = tcObj["index"]?.GetValue() ?? 0; if (!toolCalls.TryGetValue(idx, out var acc)) toolCalls[idx] = acc = new ToolCallAccumulator(); if (tcObj["id"]?.GetValue() is { Length: > 0 } id) acc.Id = id; var fn = tcObj["function"]?.AsObject(); if (fn is not null) { if (fn["name"]?.GetValue() is { Length: > 0 } name) acc.Name = name; if (fn["arguments"]?.GetValue() is { } args) acc.ArgsBuffer.Append(args); } } } } if (LlmStreamFrames.Text(choice["finish_reason"]) is { Length: > 0 } finishReason) rawStop = finishReason; if (emitted.Count > 0) yield return new LlmStreamChunk(emitted, StopReason: null, Usage: null); } // Without a finish_reason the model never said it was done: the connection ended mid-answer, and handing the // pieces on as a finished answer would store a cut one. if (rawStop is null) throw new InvalidOperationException( $"{_providerId}: the stream ended before the model said why it stopped (no finish_reason); the answer is cut."); var response = ParseResponse(AssemblePlainJson( responseId, fingerprint, content, reasoningContent, reasoning, toolCalls, rawStop, usage)); yield return new LlmStreamChunk( [.. response.Content.OfType()], response.StopReason, response.Usage) { Response = response }; } /// The JSON a plain call returns for the answer a stream delivered in pieces. private static JsonObject AssemblePlainJson( string? responseId, string? fingerprint, System.Text.StringBuilder content, System.Text.StringBuilder reasoningContent, System.Text.StringBuilder reasoning, SortedDictionary toolCalls, string rawStop, JsonObject? usage) { var message = new JsonObject { ["role"] = "assistant" }; if (content.Length > 0) message["content"] = content.ToString(); if (reasoningContent.Length > 0) message["reasoning_content"] = reasoningContent.ToString(); if (reasoning.Length > 0) message["reasoning"] = reasoning.ToString(); if (toolCalls.Count > 0) { var calls = new JsonArray(); foreach (var call in toolCalls.Values) { calls.Add(new JsonObject { ["id"] = call.Id, ["type"] = "function", ["function"] = new JsonObject { ["name"] = call.Name, ["arguments"] = call.ArgsBuffer.Length == 0 ? "{}" : call.ArgsBuffer.ToString() } }); } message["tool_calls"] = calls; } return new JsonObject { ["id"] = responseId, ["system_fingerprint"] = fingerprint, ["choices"] = new JsonArray(new JsonObject { ["index"] = 0, ["message"] = message, ["finish_reason"] = rawStop }), ["usage"] = usage }; } private sealed class ToolCallAccumulator { public string? Id { get; set; } public string? Name { get; set; } public System.Text.StringBuilder ArgsBuffer { get; } = new(); } private void ApplyAuthHeaders(HttpRequestMessage http) { var key = _factory.ApiKey; if (string.IsNullOrWhiteSpace(key)) return; http.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key); // OpenRouter recommends a Referer/Title header for free-tier identification. if (_providerId == "openrouter") { http.Headers.TryAddWithoutValidation("HTTP-Referer", "https://github.com/redb-stack/redb.Route"); http.Headers.TryAddWithoutValidation("X-Title", "redb.Route.Llm"); } } private JsonObject BuildRequestBody(LlmRequest request, bool stream) { var messages = new JsonArray(); if (!string.IsNullOrWhiteSpace(request.SystemPrompt)) { messages.Add(new JsonObject { ["role"] = "system", ["content"] = request.SystemPrompt }); } // Reasoning goes back on the assistant messages of a request that declares tools: the tool // loop is where a thinking model needs its earlier reasoning. A request without tools does // not carry the field, so a deployment that runs no tool loop never sends it. var includeReasoning = request.Tools.Count > 0; foreach (var m in request.Messages) { // Any message containing tool_result blocks must be split into one // role="tool" entry per result. Some engines emit them as role="user" // (Anthropic style) — we normalise here. Plain text/tool_use blocks // in the same message still emit a regular assistant/user entry. var hasToolResults = false; foreach (var b in m.Content) { if (b is LlmToolResultBlock tr) { hasToolResults = true; messages.Add(new JsonObject { ["role"] = "tool", ["tool_call_id"] = tr.ToolUseId, ["content"] = tr.OutputJson }); } } // If the message had ONLY tool results, skip the wrapping message. if (hasToolResults && m.Content.All(b => b is LlmToolResultBlock)) continue; // Otherwise emit a normal assistant/user message (without tool_result blocks), unless it has // nothing to say. Content may be null only beside tool_calls, so a message with no text and // no tool call is refused, and one refused message in the history breaks every later call of // the conversation. The turn stays in the record; it is not sent. if (MapAssistantOrUser(m, includeReasoning) is { } mapped) messages.Add(mapped); } var body = new JsonObject { ["model"] = request.ModelId ?? _factory.ModelId, ["messages"] = messages }; if (request.Temperature is { } t) body["temperature"] = t; if (request.MaxTokens is { } mt) body["max_tokens"] = mt; if (request.TopP is { } tp) body["top_p"] = tp; if (request.StopSequences is { Count: > 0 } stops) { var arr = new JsonArray(); foreach (var s in stops) arr.Add(s); body["stop"] = arr; } if (request.Tools.Count > 0) { var tools = new JsonArray(); foreach (var cap in request.Tools) tools.Add(MapTool(cap)); body["tools"] = tools; } if (stream) body["stream"] = true; return body; } private static JsonObject? MapAssistantOrUser(LlmMessage m, bool includeReasoning) { var toolUses = new List(); var text = new System.Text.StringBuilder(); LlmThinkingBlock? thinking = null; foreach (var block in m.Content) { switch (block) { case LlmTextBlock tb: text.Append(tb.Text); break; case LlmToolUseBlock tu: toolUses.Add(tu); break; // The wire's only place for thinking is reasoning_content, and its payload is the text. case LlmThinkingBlock th when !string.IsNullOrEmpty(th.Text): thinking ??= th; break; } } if (text.Length == 0 && toolUses.Count == 0) return null; var msg = new JsonObject { ["role"] = m.Role }; msg["content"] = text.Length > 0 ? text.ToString() : null; if (toolUses.Count > 0) { var calls = new JsonArray(); foreach (var tu in toolUses) { calls.Add(new JsonObject { ["id"] = tu.ToolUseId, ["type"] = "function", ["function"] = new JsonObject { ["name"] = tu.Name, ["arguments"] = tu.InputJson } }); } msg["tool_calls"] = calls; } if (includeReasoning && thinking is not null) msg["reasoning_content"] = thinking.Text; return msg; } /// /// Projects a capability into the provider's tools[] entry. Only the name, the description /// and the input schema travel: is server-side metadata and never /// appears on the wire. /// private static JsonObject MapTool(LlmToolCapability cap) { JsonNode parameters; try { parameters = JsonNode.Parse(cap.InputSchema) ?? new JsonObject { ["type"] = "object" }; } catch (JsonException) { parameters = new JsonObject { ["type"] = "object" }; } return new JsonObject { ["type"] = "function", ["function"] = new JsonObject { ["name"] = cap.Name, ["description"] = cap.Description, ["parameters"] = parameters } }; } private static LlmResponse ParseResponse(JsonObject json) { var choices = json["choices"] as JsonArray; if (choices is null || choices.Count == 0) throw new InvalidOperationException("OpenAI response: no choices."); var first = choices[0]!.AsObject(); var message = first["message"]?.AsObject() ?? throw new InvalidOperationException("OpenAI response: no message in choice."); var blocks = new List(); // DeepSeek's thinking models answer with the chain of thought in reasoning_content beside // the visible content. It is a block, not text: callers asked for the answer, and the // reasoning belongs to the round trip back to the provider. if (message["reasoning_content"] is JsonValue rc && rc.TryGetValue(out var reasoningContent) && !string.IsNullOrEmpty(reasoningContent)) { blocks.Add(new LlmThinkingBlock(reasoningContent)); } if (message["content"] is JsonValue v && v.TryGetValue(out var textContent) && !string.IsNullOrEmpty(textContent)) blocks.Add(new LlmTextBlock(textContent)); else if (message["reasoning"] is JsonValue rv && rv.TryGetValue(out var reasoningText) && !string.IsNullOrEmpty(reasoningText)) { // Reasoning models (gpt-oss-*, zai-glm-*, etc.) put their stream into // "reasoning" instead of "content" when max_tokens cuts the visible answer. // We surface it as text so callers still see something useful. blocks.Add(new LlmTextBlock(reasoningText)); } if (message["tool_calls"] is JsonArray toolCalls) { foreach (var call in toolCalls) { if (call is not JsonObject callObj) continue; var fn = callObj["function"]?.AsObject(); if (fn is null) continue; var id = callObj["id"]?.GetValue() ?? Guid.NewGuid().ToString("N"); var name = fn["name"]?.GetValue() ?? ""; var args = fn["arguments"]?.GetValue() ?? "{}"; blocks.Add(new LlmToolUseBlock(id, name, args)); } } if (blocks.Count == 0) blocks.Add(new LlmTextBlock(string.Empty)); var rawStop = first["finish_reason"]?.GetValue(); var stop = rawStop switch { "stop" => LlmStopReason.EndTurn, "tool_calls" => LlmStopReason.ToolUse, "length" => LlmStopReason.MaxTokens, "content_filter" => LlmStopReason.Other, _ => LlmStopReason.Other }; var usage = LlmUsage.Empty; if (json["usage"] is JsonObject u) { // A prompt served from the provider's cache: OpenAI reports it in prompt_tokens_details.cached_tokens, // DeepSeek in prompt_cache_hit_tokens (and fills the OpenAI-shaped one with zero), a gateway may fill // either — they name the same quantity, so the one that reports a number wins. LlmUsage.InputTokens is // the remainder billed at full price, not the whole prompt, so the cached part comes out of // prompt_tokens; DeepSeek names that remainder itself. The write side has no field on this path: // DeepSeek does not bill cache creation separately and OpenAI's cache is implicit. var prompt = u["prompt_tokens"]?.GetValue() ?? 0; var cacheRead = Math.Max( (u["prompt_tokens_details"] as JsonObject)?["cached_tokens"]?.GetValue() ?? 0, u["prompt_cache_hit_tokens"]?.GetValue() ?? 0); var fullPrice = u["prompt_cache_miss_tokens"]?.GetValue() ?? Math.Max(0, prompt - cacheRead); var outT = u["completion_tokens"]?.GetValue() ?? 0; usage = new LlmUsage(fullPrice, outT, CacheReadInputTokens: cacheRead); } // OpenAI exposes system_fingerprint at the response root; xAI / Together // echo it on most models; Anthropic-compat / Gemini-compat / Ollama // typically leave it null. Auditors compare the value across otherwise // identical calls to detect silent backend re-releases. var fingerprint = json["system_fingerprint"]?.GetValue(); var responseId = json["id"]?.GetValue(); return new LlmResponse { Content = blocks, StopReason = stop, Usage = usage, RawStopReason = rawStop, ProviderSystemFingerprint = fingerprint, ProviderResponseId = responseId }; } private static Uri EnsureTrailingSlash(Uri uri) { var s = uri.ToString(); return s.EndsWith('/') ? uri : new Uri(s + "/"); } private static async Task SafeReadAsync(HttpResponseMessage resp, CancellationToken ct) { try { return await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); } catch { return ""; } } } Path: redb-route/redb.Route.Llm/Providers/OpenAiTranscriptionProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/OpenAiTranscriptionProvider.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; namespace redb.Route.Llm.Providers; /// /// Transport for any OpenAI-compatible speech endpoint /// (POST {baseUrl}/audio/transcriptions, multipart/form-data with a /// file and a model, response {"text": ".."}). /// /// One implementation, many providers — the same /// (Provider / BaseUrl / ApiKey / ModelId) as and /// , so it talks to OpenAI and Groq as readily /// as to whisper.cpp's server, Speaches / faster-whisper-server or LM Studio on /// 127.0.0.1. Local and paid recognition differ by a base URL, which is the /// point: a product can develop against its own GPU and move to a paid endpoint /// without a line of route code changing. Set /// to the speech model /// (e.g. whisper-1, large-v3), not the chat model. /// /// public sealed class OpenAiTranscriptionProvider : ITranscriptionProvider { private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web); private readonly LlmConnectionFactory _factory; private readonly HttpClient _http; private readonly Uri _endpoint; private readonly string _providerId; /// Creates the provider with an externally owned . public OpenAiTranscriptionProvider(LlmConnectionFactory factory, HttpClient http) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _http = http ?? throw new ArgumentNullException(nameof(http)); var baseUrl = factory.BaseUrl ?? OpenAiProvider.ResolveDefaultBaseUrl(factory.Provider); _endpoint = new Uri(EnsureTrailingSlash(baseUrl), "audio/transcriptions"); _providerId = string.IsNullOrWhiteSpace(factory.Provider) ? "openai" : factory.Provider!.ToLowerInvariant(); } /// Convenience constructor that builds an internal HttpClient with the factory timeout. public static OpenAiTranscriptionProvider Create(LlmConnectionFactory factory) { ArgumentNullException.ThrowIfNull(factory); // Recognition is slower than a chat completion on the same hardware — a minute of // speech is minutes of compute on a modest local model — so the factory timeout is // the ceiling that matters here, not a formality, and those minutes are silent on the // wire: the package's default client keeps the connection alive with HTTP/2 pings. return new OpenAiTranscriptionProvider(factory, LlmHttpTransport.BuildClient(factory)); } /// public string ProviderId => _providerId; /// The client this provider sends through (tests read its transport defaults). internal HttpClient Http => _http; /// public string ModelId => _factory.ModelId; /// public Task TranscribeAsync( TranscriptionRequest request, CancellationToken ct = default) { if (request.Audio.IsEmpty) throw new ArgumentException( "Transcription: the audio is empty. A zero-byte upload is a bug upstream, not silence — " + "silence is a recording that transcribes to an empty string.", nameof(request)); // Limited as a whole by RequestTimeoutMs: a recording is minutes of compute before the answer. return LlmHttpTransport.WithinCallLimitAsync(_factory, _providerId, t => TranscribeCoreAsync(request, t), ct); } private async Task TranscribeCoreAsync(TranscriptionRequest request, CancellationToken ct) { var fileName = string.IsNullOrWhiteSpace(request.FileName) ? "audio.ogg" : request.FileName; using var form = new MultipartFormDataContent(); var audio = new ByteArrayContent(request.Audio.ToArray()); audio.Headers.ContentType = new MediaTypeHeaderValue(GuessMediaType(fileName)); form.Add(audio, "file", fileName); form.Add(new StringContent(_factory.ModelId), "model"); // "json" and not "verbose_json": the verbose shape carries duration and segments, but it // is the format local servers are likeliest not to implement, and a 400 from asking for // extras would cost the transcription itself. Duration is better taken from the transport // that delivered the recording anyway — it knows it before the upload. form.Add(new StringContent("json"), "response_format"); if (!string.IsNullOrWhiteSpace(request.Language)) form.Add(new StringContent(request.Language!), "language"); if (!string.IsNullOrWhiteSpace(request.Prompt)) form.Add(new StringContent(request.Prompt!), "prompt"); using var http = LlmHttpTransport.NewRequest(_http, HttpMethod.Post, _endpoint); http.Content = form; ApplyAuthHeaders(http); using var resp = await _http.SendAsync(http, HttpCompletionOption.ResponseHeadersRead, ct) .ConfigureAwait(false); if (!resp.IsSuccessStatusCode) { var raw = await SafeReadAsync(resp, ct).ConfigureAwait(false); // Typed, like the chat and embedding providers: a route that degrades a failed // transcription into "please repeat, I did not catch that" must not say it to a // person whose recording was fine and whose server was merely busy. throw LlmHttpErrors.FromResponse( _providerId, resp, $"{_providerId} transcription: {(int)resp.StatusCode} {resp.ReasonPhrase} from {_endpoint}. Body: {raw}", raw); } return await ParseAsync(resp, ct).ConfigureAwait(false); } /// /// Reads the answer. JSON is the contract, but plain text is what several local /// servers return when they ignore response_format — and a transcription that /// arrived is not worth discarding over its envelope. /// private static async Task ParseAsync(HttpResponseMessage resp, CancellationToken ct) { var isJson = resp.Content.Headers.ContentType?.MediaType?.Contains("json", StringComparison.OrdinalIgnoreCase) == true; if (!isJson) { var text = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); return new TranscriptionResult(text.Trim()); } var json = await resp.Content.ReadFromJsonAsync(JsonOpts, ct).ConfigureAwait(false) ?? throw new InvalidOperationException("transcription: empty response body."); var recognised = json["text"]?.GetValue() ?? throw new InvalidOperationException("transcription response is missing the 'text' field."); return new TranscriptionResult( recognised.Trim(), Language: json["language"]?.GetValue(), DurationSeconds: ReadDouble(json["duration"])); } private static double? ReadDouble(JsonNode? node) { if (node is null) return null; try { return node.GetValue(); } catch (FormatException) { return null; } catch (InvalidOperationException) { return null; } } /// /// Content type for the upload, by extension. Speech endpoints choose a demuxer from /// what they are handed, so a Telegram voice note (.oga, Ogg/Opus) announced as /// generic bytes is a decode failure on servers that would otherwise read it fine. /// private static string GuessMediaType(string fileName) => Path.GetExtension(fileName).ToLowerInvariant() switch { ".oga" or ".ogg" or ".opus" => "audio/ogg", ".mp3" => "audio/mpeg", ".m4a" => "audio/mp4", ".wav" => "audio/wav", ".flac" => "audio/flac", ".webm" => "audio/webm", ".mp4" => "video/mp4", ".mpeg" or ".mpga" => "audio/mpeg", _ => "application/octet-stream" }; private void ApplyAuthHeaders(HttpRequestMessage http) { var key = _factory.ApiKey; if (string.IsNullOrWhiteSpace(key)) return; http.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key); } private static async Task SafeReadAsync(HttpResponseMessage resp, CancellationToken ct) { try { return await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); } catch { return ""; } } private static Uri EnsureTrailingSlash(Uri uri) { var s = uri.ToString(); return s.EndsWith('/') ? uri : new Uri(s + "/"); } } Path: redb-route/redb.Route.Llm/Providers/ReplayProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/ReplayProvider.cs ---- using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Providers; /// /// Mode for . /// public enum ReplayMode { /// Strictly replay from fixture; missing entries throw. Replay, /// Record every request/response from the inner provider into the fixture. Record, /// /// Replay when a fixture entry exists; otherwise call the inner provider /// and append the response. Useful for filling out a fixture incrementally. /// Auto } /// /// Deterministic backed by a JSON fixture on disk. /// In the provider replays previously recorded /// responses keyed by a stable hash of the request — no network IO. In /// it calls an inner provider and persists /// every response. mixes the two, falling /// through to the inner provider for cache misses and appending the result. /// /// Designed for integration tests, eval-harness fixtures and offline demos — /// keeps reference runs deterministic and free of API spend while still being /// upgradable by re-recording against a real provider. /// /// public sealed class ReplayProvider : ILlmProvider { private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web) { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, Converters = { new JsonStringEnumConverter() } }; private readonly object _gate = new(); private readonly Dictionary _entries; private readonly string _fixturePath; private readonly ReplayMode _mode; private readonly ILlmProvider? _inner; /// Creates a replay provider bound to a fixture file. /// Path to the JSON fixture (created if missing in Record/Auto). /// Replay/record behaviour. /// Inner provider — required for Record / Auto, ignored in Replay. /// Identifier surfaced as (defaults to "replay"). /// Identifier surfaced as (defaults to "replay-model"). public ReplayProvider(string fixturePath, ReplayMode mode, ILlmProvider? inner = null, string providerId = "replay", string modelId = "replay-model") { ArgumentException.ThrowIfNullOrWhiteSpace(fixturePath); if (mode is ReplayMode.Record or ReplayMode.Auto && inner is null) throw new ArgumentNullException(nameof(inner), "Inner provider is required when ReplayProvider is in Record or Auto mode."); _fixturePath = fixturePath; _mode = mode; _inner = inner; ProviderId = providerId; ModelId = modelId; _entries = LoadFixture(fixturePath); } /// public string ProviderId { get; } /// public string ModelId { get; } /// Number of entries currently held in the in-memory fixture. public int EntryCount { get { lock (_gate) return _entries.Count; } } /// public async Task CompleteAsync(LlmRequest request, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); var key = ComputeKey(request); if (_mode != ReplayMode.Record) { ReplayEntry? entry; lock (_gate) _entries.TryGetValue(key, out entry); if (entry is not null) return MaterialiseResponse(entry); if (_mode == ReplayMode.Replay) throw new InvalidOperationException( $"ReplayProvider: no fixture entry for request key '{key}' in '{_fixturePath}'. " + $"Re-record with ReplayMode.Auto / Record or update the fixture."); } // Record / Auto-miss path var response = await _inner!.CompleteAsync(request, ct).ConfigureAwait(false); AppendEntry(key, request, response); return response; } /// public async IAsyncEnumerable StreamAsync( LlmRequest request, [EnumeratorCancellation] CancellationToken ct = default) { // For determinism the recorded shape is always the final non-streaming response. // Streaming consumers receive it as a single terminal chunk — matches the // default fallback in ILlmProvider.StreamAsync. var response = await CompleteAsync(request, ct).ConfigureAwait(false); yield return new LlmStreamChunk(response.Content, response.StopReason, response.Usage) { Response = response }; } /// Manually persists the in-memory fixture to disk. Called automatically on append. public void Flush() { lock (_gate) SaveFixtureLocked(); } private void AppendEntry(string key, LlmRequest request, LlmResponse response) { var entry = new ReplayEntry { Key = key, Request = SnapshotRequest(request), Response = SnapshotResponse(response) }; lock (_gate) { _entries[key] = entry; SaveFixtureLocked(); } } private void SaveFixtureLocked() { var dir = Path.GetDirectoryName(_fixturePath); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) Directory.CreateDirectory(dir); var doc = new FixtureDocument { ProviderId = ProviderId, ModelId = ModelId, Entries = _entries.Values.ToList() }; File.WriteAllText(_fixturePath, JsonSerializer.Serialize(doc, JsonOpts)); } private static Dictionary LoadFixture(string path) { if (!File.Exists(path)) return new Dictionary(); var json = File.ReadAllText(path); if (string.IsNullOrWhiteSpace(json)) return new Dictionary(); var doc = JsonSerializer.Deserialize(json, JsonOpts); var result = new Dictionary(); if (doc?.Entries is null) return result; foreach (var e in doc.Entries) if (!string.IsNullOrEmpty(e.Key)) result[e.Key] = e; return result; } private static string ComputeKey(LlmRequest request) { var snapshot = SnapshotRequest(request); var json = JsonSerializer.Serialize(snapshot, JsonOpts); var bytes = Encoding.UTF8.GetBytes(json); return Convert.ToHexString(SHA256.HashData(bytes)); } private static RequestSnapshot SnapshotRequest(LlmRequest r) => new() { ModelId = r.ModelId, SystemPrompt = r.SystemPrompt, Temperature = r.Temperature, MaxTokens = r.MaxTokens, TopP = r.TopP, StopSequences = r.StopSequences, Tools = r.Tools.Select(c => new ToolSnapshot { Name = c.Name, Description = c.Description, InputSchema = c.InputSchema }).ToList(), Messages = r.Messages.Select(SnapshotMessage).ToList() }; private static MessageSnapshot SnapshotMessage(LlmMessage m) => new() { Role = m.Role, Blocks = m.Content.Select(b => b switch { LlmTextBlock t => new BlockSnapshot { Type = "text", Text = t.Text }, LlmToolUseBlock u => new BlockSnapshot { Type = "tool_use", ToolUseId = u.ToolUseId, Name = u.Name, InputJson = u.InputJson }, LlmToolResultBlock r => new BlockSnapshot { Type = "tool_result", ToolUseId = r.ToolUseId, OutputJson = r.OutputJson, IsError = r.IsError }, LlmThinkingBlock th => new BlockSnapshot { Type = "thinking", Text = th.Text, Signature = th.Signature, RedactedData = th.RedactedData }, _ => throw new NotSupportedException( $"ReplayProvider: content block type '{b.GetType().Name}' has no snapshot form.") }).ToList() }; private static ResponseSnapshot SnapshotResponse(LlmResponse r) => new() { StopReason = r.StopReason, RawStopReason = r.RawStopReason, Usage = new UsageSnapshot { InputTokens = r.Usage.InputTokens, OutputTokens = r.Usage.OutputTokens }, Blocks = r.Content.Select(b => b switch { LlmTextBlock t => new BlockSnapshot { Type = "text", Text = t.Text }, LlmToolUseBlock u => new BlockSnapshot { Type = "tool_use", ToolUseId = u.ToolUseId, Name = u.Name, InputJson = u.InputJson }, LlmToolResultBlock tr => new BlockSnapshot { Type = "tool_result", ToolUseId = tr.ToolUseId, OutputJson = tr.OutputJson, IsError = tr.IsError }, LlmThinkingBlock th => new BlockSnapshot { Type = "thinking", Text = th.Text, Signature = th.Signature, RedactedData = th.RedactedData }, _ => throw new NotSupportedException( $"ReplayProvider: content block type '{b.GetType().Name}' has no snapshot form.") }).ToList() }; private static LlmResponse MaterialiseResponse(ReplayEntry entry) { var snap = entry.Response ?? throw new InvalidOperationException( $"ReplayProvider: fixture entry '{entry.Key}' has no response snapshot."); var blocks = new List(); foreach (var b in snap.Blocks ?? new List()) { switch (b.Type) { case "text": blocks.Add(new LlmTextBlock(b.Text ?? string.Empty)); break; case "tool_use": blocks.Add(new LlmToolUseBlock( b.ToolUseId ?? Guid.NewGuid().ToString("N"), b.Name ?? string.Empty, b.InputJson ?? "{}")); break; case "tool_result": blocks.Add(new LlmToolResultBlock( b.ToolUseId ?? string.Empty, b.OutputJson ?? "{}", b.IsError)); break; // A recorded thinking block comes back whole — text, signature and redacted payload — // so a replay of a tool loop carries the same blocks the provider issued. case "thinking": blocks.Add(new LlmThinkingBlock( b.Text ?? string.Empty, b.Signature, b.RedactedData)); break; default: throw new InvalidOperationException( $"ReplayProvider: fixture entry '{entry.Key}' has a block of unknown type '{b.Type}'."); } } if (blocks.Count == 0) blocks.Add(new LlmTextBlock(string.Empty)); return new LlmResponse { Content = blocks, StopReason = snap.StopReason, Usage = new LlmUsage(snap.Usage?.InputTokens ?? 0, snap.Usage?.OutputTokens ?? 0), RawStopReason = snap.RawStopReason }; } private sealed class FixtureDocument { public string? ProviderId { get; set; } public string? ModelId { get; set; } public List Entries { get; set; } = new(); } private sealed class ReplayEntry { public string Key { get; set; } = string.Empty; public RequestSnapshot? Request { get; set; } public ResponseSnapshot? Response { get; set; } } private sealed class RequestSnapshot { public string? ModelId { get; set; } public string? SystemPrompt { get; set; } public double? Temperature { get; set; } public int? MaxTokens { get; set; } public double? TopP { get; set; } public IReadOnlyList? StopSequences { get; set; } public List? Tools { get; set; } public List? Messages { get; set; } } private sealed class ToolSnapshot { public string? Name { get; set; } public string? Description { get; set; } public string? InputSchema { get; set; } } private sealed class MessageSnapshot { public string? Role { get; set; } public List? Blocks { get; set; } } private sealed class BlockSnapshot { public string? Type { get; set; } public string? Text { get; set; } public string? ToolUseId { get; set; } public string? Name { get; set; } public string? InputJson { get; set; } public string? OutputJson { get; set; } public bool IsError { get; set; } // Thinking-block payload: the signature and the redacted data travel with the text. public string? Signature { get; set; } public string? RedactedData { get; set; } } private sealed class ResponseSnapshot { public LlmStopReason StopReason { get; set; } = LlmStopReason.EndTurn; public string? RawStopReason { get; set; } public UsageSnapshot? Usage { get; set; } public List? Blocks { get; set; } } private sealed class UsageSnapshot { public int InputTokens { get; set; } public int OutputTokens { get; set; } } } Path: redb-route/redb.Route.Llm/Providers/StubProvider.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Providers/StubProvider.cs ---- namespace redb.Route.Llm.Providers; /// /// Deterministic provider for tests, demos, and Phase-0 smoke. Echoes the last /// user message back as an assistant text block, ending the turn without tool calls. /// public sealed class StubProvider : ILlmProvider { private readonly LlmConnectionFactory _factory; /// Optional fixed reply — when set, overrides the echo behaviour. public string? FixedReply { get; init; } /// Creates a stub provider bound to a connection factory. public StubProvider(LlmConnectionFactory factory) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); } /// public string ProviderId => "stub"; /// public string ModelId => _factory.ModelId; /// public Task CompleteAsync(LlmRequest request, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); var reply = FixedReply ?? ExtractEcho(request); var response = new LlmResponse { Content = [new LlmTextBlock(reply)], StopReason = LlmStopReason.EndTurn, Usage = new LlmUsage(EstimateTokens(request), EstimateTokens(reply)), RawStopReason = "stub:end_turn" }; return Task.FromResult(response); } private static string ExtractEcho(LlmRequest request) { for (var i = request.Messages.Count - 1; i >= 0; i--) { var m = request.Messages[i]; if (m.Role != "user") continue; foreach (var block in m.Content) if (block is LlmTextBlock text) return $"[stub] {text.Text}"; } return "[stub] (no user message)"; } private static int EstimateTokens(LlmRequest request) { var total = 0; foreach (var m in request.Messages) foreach (var c in m.Content) if (c is LlmTextBlock t) total += EstimateTokens(t.Text); return total; } private static int EstimateTokens(string text) => Math.Max(1, text.Length / 4); } Path: redb-route/redb.Route.Llm/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/README.md ---- # redb.Route.Llm > Documentation and articles: > Internal package README. The NuGet description is separate. > Long-form docs live under [doc/](doc/). ## What this is A **first-class transport** for the redb.Route engine that turns a Large Language Model into an addressable endpoint, exactly the same way Kafka, RabbitMQ or HTTP are addressable endpoints. ```csharp .From("kafka://orders") .To(Llm.Factory("claude").Temperature(0.2).MaxTokens(1024).AsUri()) .To("kafka://orders.translated"); ``` That single line is a fully wired LLM call: - input message body becomes the user prompt; - the agent runs against the provider configured in factory `claude`; - the assistant text replaces `exchange.Out.Body`; - token usage, model id, stop reason, tool iterations are pushed into headers; - OpenTelemetry traces and metrics light up automatically; - the endpoint is visible in the tsak.web dashboard with messages-per-second, average duration, error rate and last-error info — like every other connector. ## Why a connector and not a "library" Most C# LLM libraries work as direct API clients you call from your code. They own retries, conversation state, tool dispatch and observability — sometimes well, often partially. The redb.Route engine *already has*: | Concern | DSL primitive | |---|---| | Retry / backoff | `RedeliveryPolicy`, `OnException` | | Rate limiting | `Throttle` | | Resilience | `CircuitBreaker` | | Idempotency | `IdempotentConsumer` | | Compensation | `Saga` | | Audit / shadow | `WireTap`, `Multicast` | | Tracing & metrics | `RouteActivitySource`, `RouteMetrics` | | Persistence | `redb` schemes (typed object engine) | Wrapping an LLM as just another connector means *every one of those primitives applies for free*. We do not reinvent retries, breakers, dashboards or audit — we author one connector and the entire engine carries it. ## How it works ```text exchange ──► LlmEndpoint ──► LlmProducer ──► AgentEngine ──► ILlmProvider │ (HTTP) ▼ tool loop (optional) │ ▼ IToolDescriptorRegistry ──► RouteToolBridge │ ▼ IProducerTemplate │ ▼ any redb.Route route mounted with .AsLlmTool("name") ``` Pieces: - **`LlmComponent`** — registers itself for scheme `llm` (one URI scheme, by design — see PLAN.md §3a). - **`LlmEndpoint`** — created from `llm://?...`. Resolves the named `LlmConnectionFactory` from the route registry, owns options, exposes `IEndpointStatistics` (tsak.web reads these). - **`LlmConnectionFactory`** — POCO with provider id, model id, API key (or secret ref), tuning defaults. `Build()` produces an `ILlmProvider`. - **`ILlmProvider`** — the only thing that talks HTTP. Two production providers ship today: - **`OpenAiProvider`** — one universal transport for **14 OpenAI-compatible APIs**: `openai`, `anthropic`/`claude` (via the official OpenAI-compat endpoint at `https://api.anthropic.com/v1/`), `groq`, `cerebras`, `openrouter`, `gemini` (OpenAI-compat endpoint), `github-models`, `mistral`, `together`, `huggingface`, `deepseek`, `ollama`, `lmstudio`, plus a generic `custom` for any self-hosted gateway. - **`StubProvider`** — deterministic echo for unit tests / CI without keys. - **`AnthropicProvider`** — native Anthropic Messages API client. Selected via `Provider = "anthropic"` and ships in parallel to the OpenAI-compat path; reads true Messages-API SSE (`message_start` / `content_block_delta` / `message_stop`) for streaming, and exists so we can land features the OpenAI-compat surface flattens away (prompt caching, computer-use, fine-grained image blocks). - **`IAgentEngine`** — the tool-use loop. One inbound exchange = one agent run = N provider calls. Handles iterations, transcript, tool dispatch, governance hooks. - **`IToolDescriptorRegistry`** + **`RouteToolBridge`** — tools-as-routes machinery (see *Tools* below). - **`IPromptTemplateRegistry`** — versioned prompt store backing the `#`-ref resolver (see *Dynamic prompts* below). - **`Fluent/Llm.cs`** — `Llm.Factory("...")` builder used to compose the URI. - **`Extensions/LlmRouteDefinitionExtensions.cs`** — sugar `route.Llm("factory", b => ...)` for inline LLM steps when you do not want a separate endpoint. ## Quick start ### 1. Register ```csharp services.AddRedbRoute(route => { route.Services.AddRedbRouteLlm(); route.Services.AddLlmConnectionFactory("claude", f => { f.Provider = "anthropic"; // "openai" | "anthropic"/"claude" | "groq" | // "cerebras" | "openrouter" | "gemini" | // "github-models" | "mistral" | "together" | // "huggingface" | "deepseek" | "ollama" | // "lmstudio" | "custom" | "stub" f.ModelId = "claude-haiku-4-5"; f.ApiKeySecretRef = "anthropic.api-key"; f.Temperature = 0.2; f.MaxTokens = 1024; }); route.AddRouteBuilder(); }); ``` `AddRedbRouteLlm()` registers `IAgentEngine`, `IToolDescriptorRegistry`, `InMemoryPromptTemplateRegistry`, `LlmComponent`, and the inline-`.Llm()` extension wiring. The engine itself is built from the route context (`AgentEngine.FromContext`): it takes the registered producer template, claims source, cache, cost calculator and the rest, and falls back to the shipped no-ops for the collaborators a host did not supply. This holds for every shape of an LLM route — `llm://` producers and consumers included, which look the engine up in the context and then in the container. Hosts therefore do not assemble an engine by hand: registering a seam is what replaces it, and a seam added in a future release reaches the engine without an edit to the host. ### 2. `To("llm://...")` — model as a pipeline step This is the most common shape. The producer treats the inbound message as **one user turn**, runs the agent loop to completion, and writes the assistant text into `Out.Body`. ```csharp public sealed class MyRoutes : RouteBuilder { protected override void Configure() { From("kafka://orders") .To("llm://claude?temperature=0.1&maxTokens=512&conversation=header") .To("kafka://orders.translated"); } } ``` What happens, step by step: 1. **Input** — `exchange.In.Body` is wrapped as a single `LlmTextBlock`. Any other type is `.ToString()`'d. 2. **Tools** — `?tools=` is parsed: missing/empty = no tools, `*` = every tool in the registry, CSV = named tools only. 3. **Agent loop** — `AgentEngine.RunAsync` cycles provider call → optional `tool_use` → `RouteToolBridge` dispatch → next call → … until `EndTurn`, `MaxIterations`, or cancellation. 4. **Output** — assistant text in `Out.Body`. Headers populated: | Header | Meaning | |---|---| | `llm.provider.id` | `"anthropic"` / `"openai"` / `"stub"` / … | | `llm.model.id` | the actual model used | | `llm.tokens.in` / `llm.tokens.out` | usage | | `llm.tool.iterations` | how many loop steps | | `llm.stop_reason` | `EndTurn`, `ToolUse`, `MaxTokens`, … | ### 3. `From("llm://...")` — scheduled agent `From("llm://factory?schedule=...")` is **not** "listen for replies" (LLMs are pull, not push). It is a scheduler that fires a fresh agent run every interval and pushes the assistant reply down the rest of the route as a normal exchange. ```csharp From("llm://groq?schedule=5m" + "&systemPromptRef=#watchdog-system" + "&initialBodyRef=#daily-brief" + "&tools=*") .To("rabbitmq://alerts"); ``` Use cases: watchdog agents, scheduled report generation, self-improving agents with conversation memory. `?schedule=` accepts simple intervals only — `500ms`, `30s`, `5m`, `1h`. For cron expressions, prefer `From("quartz://...").To("llm://...")` — Quartz is already a scheduler, no need to duplicate it inside the LLM consumer. The agent's user prompt comes from `?initialBodyRef=`; the system prompt comes from `?systemPromptRef=`. Both honour the `#`-ref pattern (see *Dynamic prompts* below). ### 4. Inline `.Llm("factory", ...)` — C# sugar When the LLM step is just an inline transformation, skip the URI: ```csharp From("seda://drafts") .Llm("claude", x => x .WithSystemPrompt("Rewrite the user's text in formal English. Reply with text only.") .WithTemperature(0.0) .WithMaxTokens(800)) .To("seda://drafts.formal"); ``` `Llm(...)` is a thin extension over `Process(Func)`. It calls `IAgentEngine.RunAsync` directly — same result as `.To("llm://...")`, but compiler-checked parameters, IntelliSense for tuning options, no URI escaping. Trade-off: inline `.Llm(...)` requires `exchange.ServiceProvider` to resolve `IRouteContext` at runtime. Inside a hosted route this is automatic; in unit tests, build the exchange via `Exchange.Create(msg, scopeFactory)` so the service provider flows through. | Use | Pick | |---|---| | Mixed-transport pipeline (kafka → llm → sql) | `To("llm://...")` | | Multiple LLM hops with different prompts | `To("llm://...")` + `Process` for headers | | One-off inline call from C# code | `.Llm(name, b => ...)` | | Periodic agent generating messages | `From("llm://...?schedule=...")` | ### 5. Headers vs URI parameters Per-message headers always win over URI options. This lets a single endpoint URI handle many variations without rewrites: ```csharp .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Reply in French.") .To("llm://claude?systemPromptRef=defaultPrompt") // header wins ``` | URI param | Overriding header | |---|---| | `systemPromptRef` | `LlmHeaders.SystemPrompt` | | `conversation=header` | `LlmHeaders.ConversationId` | ### 6. Sampling knobs and the Anthropic model contract `temperature` and `top_p` are **not** a fixed contract on Anthropic — the Messages API changed what it accepts across model generations, and the native `AnthropicProvider` shapes each request to match the target `ModelId` so you never get an HTTP 400 for sending a knob the model removed: | Generation | `temperature` / `top_p` | What the connector sends | |---|---|---| | Claude 3.x | both accepted | both, if you set them | | Claude 4.0–4.6 (Sonnet/Haiku 4.5, Opus/Sonnet 4.6) | **at most one** — both together → 400 | `temperature` wins; `top_p` is dropped when both are set | | Claude 4.7+ / 5 (Opus 4.7/4.8/5, Sonnet 5, Fable 5) | **rejected** — non-default → 400 | neither — steer with the system prompt instead | | unknown / future id | treated as current-generation | neither (fail-forward — a new model id never 400s on a removed field) | This is automatic. You keep setting `Temperature`/`TopP` the way you always have; the connector emits them only where the model accepts them and drops the rest, leaving a **warning in the logs** and an `llm.sampling.dropped` event on the OpenTelemetry span (with the model id, tier and dropped params) so a dropped knob is visible in both logs and traces, never silent. **Steering current-generation models.** Because `temperature=0` no longer reaches Opus 4.7+/Sonnet 5, put determinism and style in the prompt: *"Reply with the translated text only, no preamble."* rather than a low temperature. **Override for proxies / self-hosted ids.** If you route through a gateway whose model id the built-in generation table can't classify (a proxy alias, a pinned snapshot), set the tier explicitly on the factory: ```csharp route.Services.AddLlmConnectionFactory("claude", f => { f.Provider = "anthropic"; f.ModelId = "my-proxy/claude-latest"; // not a canonical id f.ModelContractTier = "modern"; // legacy | transitional | modern f.ApiKeySecretRef = "anthropic.api-key"; }); ``` `legacy`/`transitional` allow one sampling knob; `modern` omits them. When unset, the tier is inferred from `ModelId` (and an unrecognised id defaults to `modern`). This gate is Anthropic-only — the OpenAI-compatible providers accept sampling and are untouched. ## Tools > **Tools are routes.** A tool is an ordinary `RouteBuilder` route mounted > with one extra DSL aspect: `.AsLlmTool("name")`. This is the architectural decision that makes the connector cross-cutting: **every existing redb.Route component (Kafka, RabbitMQ, HTTP, SQL, file, redb, …) becomes a potential LLM tool with one method call.** No per-connector LLM package — `0 bumps` across all sibling connectors. ### How tool dispatch works 1. `.AsLlmTool("name")` (after `.From(...)`) captures the route's `From()` URI and registers a `RouteToolBridge` against the name in `IToolDescriptorRegistry`. 2. When the model emits a `tool_use` block, `AgentEngine` looks up the bridge, builds an `IMessage` with the input JSON body, and dispatches it on a **linked child of the agent exchange** (`CreateLinkedChild` + `IProducerTemplate.RequestAsync`) — i.e. invokes the route as request/reply. 3. The route runs end-to-end. Whatever lands in `exchange.Out.Body` (or `In.Body` when `Out` is null) at the end of the pipeline is serialized and handed back to the model as the tool result. ### What a tool sees of the caller Because the tool runs on a child of the agent exchange, it inherits the conversation's `Properties` (including the named redb instance from `?redb=`), its `RouteId`, its **DI scope** — the same scoped `IRedbService` / principal / tenant accessor instances the agent route resolved — and its ambient transaction. **Headers are the exception: they are filtered, not inherited.** Propagation is default-deny, so an inbound HTTP consumer's `Authorization` / `Cookie` never rides into a tool by accident. A tool always receives: | Header | Source | |---|---| | `llm.tool.name`, `llm.tool.bridge.endpoint` | stamped by the engine | | `llm.conversation.id`, `X-Correlation-Id`, `CorrelationId` | copied from the agent exchange | | `llm.user.id` | the **resolved** principal of the run (`?user=`, else the header) | | `llm.audit.*` | the **resolved** audit tags of the run (`?audit=`, else the headers) | Anything else is opt-in per name — a trailing `*` makes it a prefix match: ```csharp .To(Llm.Factory("claude") .Tools("profile_state,billing_check") .User("${header.X-User-Id}") // → llm.user.id in the tool .PropagateToolHeaders("x-tenant-id", "x-app-*").AsUri()) ``` > **Trust model.** `llm.user.id` and `llm.audit.*` are read off the inbound > exchange, so a route that forwards client headers verbatim lets the caller set > them. If your tools make access decisions on the principal, strip or overwrite > client-supplied `llm.*` headers before the `llm://` hop. That last point is important: the tool's result is the **final body of the route**, not the body of any specific `.To(...)`. Three patterns work: ```csharp // Pattern A — explicit response in a final .Process (most predictable) r.From("direct:tool-lookup") .AsLlmTool("lookup") .Process(e => { var input = JsonSerializer.Deserialize((string)e.In.Body!); var result = DoLookup(input); e.Out ??= e.In.Clone(); e.Out.Body = JsonSerializer.Serialize(result); // ← returned to the model }); // Pattern B — request/reply .To (HTTP, redb, SQL) populates Out.Body itself r.From("direct:tool-customer") .AsLlmTool("get_customer") .To("redb://customers/getById"); // Out.Body = customer JSON // Pattern C — fire-and-forget .To (Kafka/RabbitMQ) — body untouched r.From("direct:tool-publish") .AsLlmTool("publish_event") .Process(e => e.In.Body = BuildKafkaPayload(e.In.Body)) .To("kafka://events") .Process(e => { e.Out ??= e.In.Clone(); e.Out.Body = "{\"ok\":true}"; }); ``` ### Tools inside a route transaction A tool runs on a child of the agent exchange, in its DI scope and its ambient transaction. An agent step inside `.Transacted()` is therefore one unit of work with its tools: a tool's redb or `sql:` writes go into the route's transaction, and a Kafka or RabbitMQ send with `transacted=true` is deferred into the route's `TRANSACT_ACTION` set and committed with it. When the route rolls back, those writes and sends go with it. With the redb stores (`AddRedbLlmStorage()`) so do the run's conversation turns, tool idempotency reservations and stored outputs, tool cache entries, approval decisions and tool-call audit rows: a retry runs the tools again against a clean state, and the audit shows no trace of the rolled-back attempt. The in-memory defaults are not transactional. With `InMemoryConversationStore` the conversation keeps the rolled-back run's turns, its tool calls and their results included, so the model of a redelivered run reads that the tool was already called and may not call it again. With `InMemoryToolIdempotencyStore` a tool call whose id was seen before is answered from memory. The engine logs a warning, once per route and connection factory, when a run inside a transaction uses either of them. Register `AddRedbLlmStorage()`, or keep `llm:` outside `.Transacted()`. Two things are kept out of that unit: - **External tools.** A tool declared `SideEffect(ToolSideEffect.External)` (mail, payment, deployment) does something no rollback can take back. Inside an ambient transaction the engine does not run it: the model receives `{"error":"external_in_transaction"}` and observers see `SkipReason = "external_in_transaction"`. Call such tools from a route without `.Transacted()`. A send without `transacted=true` leaves at once, so declare that tool `External` as well. - **The budget.** Tokens are paid when the provider answers, so the budget is recorded outside the route's transaction, and a rollback does not un-count them. - **The shadow run.** A shadow comparison runs outside the transaction and its result stays. What the transaction costs: - **Time.** `.Transacted()` times out after 30 seconds by default, and one model call can take longer. Set `TransactionPolicy.Timeout` for the whole agent run, tool calls included. - **Locks.** Rows a tool writes, and the conversation root the store updates on every turn, stay locked until the route commits, across every model call that follows. - **Retries.** A retry after a rollback calls the model again and pays for it again. - **SQLite.** The transaction holds SQLite's single write lock for the whole block. The budget is written outside it, by a second writer, which waits for that lock and fails after the busy timeout (5 seconds). With the redb budget store on SQLite, do not put `llm:` inside `.Transacted()`. ### Examples per connector ```csharp // RabbitMQ-backed tool r.From("rabbitmq://orders.lookup") .AsLlmTool("lookup_order") .Description("Look up an order by id from the orders queue.") .Input("{ \"orderId\": \"string\" }") .Process(e => e.Out!.Body = ResolveOrder(e.In.Body)); // Kafka-backed tool — publish an event r.From("kafka://orders-topic") .AsLlmTool("publish_order_event") .Process(...) .To("kafka://events"); // SQL / redb tool — direct passthrough r.From("direct:tool-customer-by-id") .AsLlmTool("get_customer") .To("redb://customers/getById"); ``` ### Pre-built tool: `HttpFetchTool` Lives in `redb.Route.Llm.Tools` (separate package — homeless tools without a natural connector home). Plugs into a route in one line: ```csharp r.From("direct:agent") .To(Llm.Factory("claude").Tools("http_fetch").AsUri()) .To("mock:done"); context.AddService(typeof(ILlmToolDescriptor), new HttpFetchTool(new HttpFetchOptions { HostAllowlist = new[] { "api.example.com" }, Timeout = TimeSpan.FromSeconds(5) })); ``` ### Tool filter `?tools=` on the LLM URI is the per-call filter: | Value | Meaning | |---|---| | (omitted) | no tools, plain chat | | `*` | every tool in `IToolDescriptorRegistry` | | `lookup_order,publish_event` | explicit allow-list | ## Dynamic prompts — the `#`-registry pattern `?initialBodyRef=` and `?systemPromptRef=` carry the framework-wide **registry-ref convention**: a leading `#` turns the value into a lookup key instead of a literal. This matches how Kafka/S3/Firebase already resolve `#name` connection factories from `IRouteContext.GetFromRegistry`. ### Resolution order For a value `"#daily-brief"`: 1. **`IPromptTemplateRegistry`** — if a template named `daily-brief` exists, the latest version's body wins. Templates are versionable so eval replays bind to a specific revision. 2. **`IRouteContext` registry** — fallback to a plain string registered via `ctx.AddToRegistry("daily-brief", "...")`. 3. If neither resolves, the result is `null` (treated as empty user prompt / no system prompt). Plain values without a `#` prefix are passed through verbatim — backwards compatible with the literal-string usage. ### Why this matters It decouples *who owns the prompt* from *who calls the model*. One route refreshes the value on its own schedule, another route consumes it. They share nothing but a name in the registry. ```csharp // Route A — refreshes the prompt every minute from the database. From("timer://refresh-prompt?period=1m") .Process(async (e, ct) => { var fresh = await _db.LoadDailyBriefAsync(ct); e.Context.AddToRegistry("daily-brief", fresh); }); // Route B — agent ticks every 5 minutes, picks up whatever the latest brief is. From("llm://groq?schedule=5m" + "&initialBodyRef=#daily-brief" + "&systemPromptRef=#watchdog-system" + "&tools=*") .To("rabbitmq://alerts"); ``` Versioned templates use the same syntax but resolve through `IPromptTemplateRegistry`: ```csharp await templates.SetAsync(new PromptTemplate { Name = "watchdog-system", Version = "v3", Body = "You are an SRE watchdog. Reply with PASS or FAIL only." }); // Then the URI ?systemPromptRef=#watchdog-system picks v3 (the latest) at every tick. ``` The same `#`-ref works on `LlmProducer` (the `.To("llm://...")` shape), so non-scheduled pipelines also benefit. ## Persistence — `AddRedbLlmStorage()` The agent loop ships with **in-memory** defaults for its state surfaces (conversation transcripts, tool idempotency, approvals, cost ledgers, audit). The tool idempotency default keeps its keys and stored outputs in this process: a repeated tool call is answered from it for 24 hours after the first one completed, and each node of a cluster has its own. That keeps `AddRedbRouteLlm()` zero-dependency — fine for tests and stateless agents, but loses everything on restart. The connector also ships **REDB-backed implementations of every one of those surfaces** in `Storage/Redb/`. They are opt-in via a single call: ```csharp services.AddRedbRoute(route => { route.Services.AddRedbRouteLlm(); // engine + in-memory defaults route.Services.AddRedbLlmStorage(); // ← swap defaults for REDB stores }); ``` `AddRedbLlmStorage()` replaces the default singletons with: | Interface | Default | REDB store | Schema | |---|---|---|---| | `IConversationStore` | `InMemoryConversationStore` | `RedbConversationStore` | `ConversationProps` (root) + `MessageProps` (child) — tree, parent linkage via native `parent_id`, conversation/message ids on indexed `value_string`, conversation FK on `value_long` | | `IToolIdempotencyStore` | `InMemoryToolIdempotencyStore` (this process only; one per node in a cluster; a completed call is kept 24 h) | `RedbToolIdempotencyStore` | the reservation as a `Route Idempotent Entry` (processor name `llm-tool-idempotency`) + cached-result row, both in the agent's redb | | `IApprovalStore` | `InMemoryApprovalStore` | `RedbApprovalStore` | `ApprovalProps` — one row per decision, approval id on `value_string` | | `ICostBudgetStore` | `InMemoryCostBudgetStore` | `RedbCostBudgetStore` | `CostBudgetProps` — running totals per tenant/window | | `IAgentObserver` (audit) | `NoopAgentObserver` | `RedbAuditObserver` | `ToolAuditProps` — one row per tool call | Design choices worth knowing: - **Indexed by design.** Per-row business identifiers live on `_objects.value_string` (an indexed column), not inside the `Props` JSON. Lookups are O(log n) on a single column, not full-scan-with-JSON-decode. - **Tree integrity for transcripts.** `RedbConversationStore` uses `IRedbService.CreateChildAsync` — parent linkage is the tree's native `parent_id`, not a soft FK in props. The tree primitive enforces integrity. - **Lazy scheme sync.** Each store calls `EnsureSchemes` on first use; nothing to register up-front, no migration step. Fine for tests, fine for prod. - **The exchange's scope, or one of their own.** Given the exchange, a store works in the exchange's redb scope and so in its transaction. Without one it opens a scope of its own for the call and disposes it after, which is safe under concurrent calls. - **Schemas are POCOs in `Storage/Redb/Schemas/`.** Standard `[RedbScheme]` attribute, evolvable like any other redb schema. `AddRedbLlmStorage()` also wires `IPromptTemplateRegistry`, `IToolCacheStore`, `IEvalRunStore`, `IBatchStore` and `IKnowledgeStore` to their redb-backed stores — all ten storage surfaces move to redb in one call. (RAG on `IKnowledgeStore` is covered in [doc/RAG.md](doc/RAG.md).) > **For the long form** — concrete DSL recipes for each store (multi-turn chat, > approvals, budgets, idempotent retries, audit replay, branching, scheduled > agents) and a tour of all 9 schemas — see [`doc/STORAGE.md`](doc/STORAGE.md). > That guide shows *why* each surface matters and how a `.From("kafka://…").To("llm://…")` > route lights up persistence with a single header. ### All of the agent's memory in a separate named database Conversations, tool calls with their input and output, costs and the knowledge base are not business data. To keep them in a database of their own, name a redb instance for them, either per endpoint or once at registration: - `?redb=` on the `llm:` endpoint decides for everything that endpoint writes: transcripts, approvals, prompts, the knowledge base, the tool-call audit and the conversation's accumulated cost. - `AddRedbLlmStorage("")` makes `` the default of every store, the audit and the budget, for endpoints without `?redb=`. An endpoint's `?redb=` still wins. In Tsak the name is a named instance of the context's `Redb` section: ```jsonc "Tsak": { "Contexts": { "agents": { "Redb": { "agent-memory": { "Provider": "postgres", "ConnectionString": "Host=db;Database=agent_memory;Username=app;Password=secret", "UsePro": true } } } } } ``` ```csharp route.Services.AddRedbLlmStorage("agent-memory"); ``` A named instance does not create its schema at start unless it is the context's `RedbInstanceName`; create the database's schema beforehand otherwise, as for any named instance. The **reservation of tool idempotency keys** follows one rule: it is kept next to the stored tool output, in the instance the endpoint's `?redb=` names, else the one `AddRedbLlmStorage("")` names, else the context's default redb. It is an entry of redb.Route's idempotent repository (the `Route Idempotent Entry` scheme, processor name `llm-tool-idempotency`); nothing else needs registering for it. A context that has no redb to open fails at the first reserved tool call with a message naming `AddRedbLlmStorage` and what is missing. ### Calling the stores from your own code Every store method takes an optional `exchange`. Pass it whenever you have one: the call then works in that exchange's redb scope and in whatever transaction it runs in. A call without an exchange opens a redb scope of its own. That scope joins an ambient `System.Transactions` transaction (a `TransactionScope`, a route's `.Transacted()`) as every redb connection does, and is rolled back with it. It does **not** join a transaction begun on the context's shared `IRedbService` (`ExecuteAtomicAsync`, `BeginTransaction`): it commits on its own, and stays when your transaction rolls back. Use a `TransactionScope` around your work, or pass the exchange, when the store's writes must go with yours. Outside any transaction each call commits at once, so on a failure of your own your code undoes what it wrote: conversation turns it appended, tool idempotency reservations it took (release them, or the call stays reserved until the reservation expires), tool cache entries, approval decisions, prompt templates, knowledge documents, batch records, eval runs and cost budget records. The in-memory stores never roll back with any transaction. ## URI reference ``` llm:// ?temperature=0.2 &maxTokens=1024 &topP=0.9 &systemPromptRef= &initialBodyRef= # consumer only &conversation=none|header|property &stream=calls|body # producer only (calls: engine streams each call; body: HTTP→SSE, WS→per-frame) &schedule=500ms|30s|5m|1h # consumer only &maxIterations=8 &tools=*|name1,name2 &connectionFactory= # alternative to the URI host ``` | Param | Producer (`To`) | Consumer (`From`) | |---|---|---| | `temperature`, `maxTokens`, `topP` | yes | yes | | `systemPromptRef` | yes (header beats it) | yes | | `initialBodyRef` | n/a | yes | | `conversation` | yes | yes (`header` resolves to none — consumer-born exchanges have no inbound header) | | `stream` | yes. `calls`: every model call streamed inside the engine; tools, conversation, budget and the route transaction as without streaming; pieces to `IAgentObserver.OnDeltaAsync`; `Out.Body` is the final text. `body`: `Out.Body = IAsyncEnumerable` and the agent run, tools included, happens when the body is read; `HttpConsumer` flushes as SSE, `WsConsumer` as one text frame per token; read once, released with the exchange, refused by `RequestBody` and inside `.Transacted()`. `stream=true` is refused | n/a | | `schedule` | n/a | required | | `maxIterations` | yes | yes | | `tools` | yes | yes | A parameter the endpoint does not know, or a value that does not convert to the option's type, fails the endpoint's creation and is named in the message, with the nearest option for a misspelt name. It used to be ignored, and the endpoint ran with the option's default. ### Sibling schemes Both are producer-only and both name an `LlmConnectionFactory` the same way `llm://` does — set its `ModelId` to the embedding or speech model, not the chat one. ``` embed:// # text → float[] / float[][] stt:// # recorded audio → text ?language=ru # ISO-639-1 hint; empty = let the model detect &prompt= &fileName=voice.oga # decides the demuxer; derived from ContentType when unset ``` `stt://` takes the recording off the body (`byte[]`, `ReadOnlyMemory` or a `Stream`) and writes the text to `Out.Body`, with `llm.transcription.model` / `.provider` / `.chars` / `.language` beside it. It reports the **length** and never the text: a header travels into logs and dead letters, and a transcription is the speaker's own words. An empty result is a result — silence and music transcribe to nothing, and `llm.transcription.chars = 0` says so without turning it into a failure. Failures throw, and they are typed (`LlmRateLimitException` / `LlmTransientException`), so a route that degrades to "sorry, I did not catch that" does not say it to a person whose recording was fine and whose server was merely busy. Local and paid recognition differ by `BaseUrl` alone: OpenAI and Groq on one side, whisper.cpp's server / Speaches / LM Studio on `127.0.0.1` on the other. Same route, same code — which is what lets a product develop against its own GPU and move to a paid endpoint without touching a route. ```csharp From(Tg.Receive(token)) .To(Tg.Download(token)) // Telegram attachment → bytes .To("stt://speech") // bytes → text .To("direct://chat"); // and on as an ordinary message ``` ⚠️ Neither component is registered by `AddRedbRouteLlm()` — add the one you use to the route context yourself (`context.AddComponent(new SttComponent())`), the same as `EmbedComponent`. A missing component fails the whole context at start, not just its own route. ## Failures Every provider maps a failed HTTP response through one rule (`LlmHttpErrors.FromResponse`), so a caller can tell "wait and retry" from "your key is wrong" without parsing a message string. | Status | Exception | What it carries | |---|---|---| | `429` | `LlmRateLimitException` | `RetryAfter`, read from the `Retry-After` header in both its delta and date forms; `null` when the provider sent none | | `5xx`, and the soft `529` "overloaded" | `LlmTransientException` | `StatusCode` | | any other non-2xx (`401`, `403`, `404`, `422`, ...) | `HttpRequestException` | `StatusCode` | Both typed exceptions also carry `ProviderId` and `RawBody`. They derive from `Exception`, **not** from `HttpRequestException`, so a `catch (HttpRequestException)` around a provider call will not see a 429 or a 5xx. That is deliberate: those two are the retryable cases, and catching them in the same clause as a dead key is exactly the mistake the split exists to prevent. A 4xx other than 429 stays untyped on purpose. A wrong key, a missing model and a malformed request are not worth retrying, and a caller that treats every failure alike degrades blindly: retrieval that falls back to keyword search on any embedder failure cannot tell an expired credential from a busy server. The rule covers chat and embeddings alike: `AnthropicProvider`, `OpenAiProvider` (both the buffered and the streaming call site) and `OpenAiEmbeddingProvider`. ### Long silent calls A non-streaming call to a model is silent on the wire until the model has finished: tens of seconds, minutes for a thinking model or a long recording. VPN tunnels, NAT and proxies commonly drop a TLS connection that stays silent for about 50 seconds. The package's default clients (Anthropic, OpenAI-compatible, transcription, and the MCP HTTP+SSE transport) ask for HTTP/2 and send a keep-alive PING every 15 seconds while a request is in flight, which keeps the connection alive without touching the request. Where the server speaks only HTTP/1.1 no pings are sent, and a client you pass in yourself is used as it is. If such a server sits behind a VPN or a proxy, use `stream=calls` for long calls: tokens cross the wire as the model produces them, so the connection is never silent. The pings keep the connection alive; they do not extend the call's time limit. `LlmConnectionFactory.RequestTimeoutMs` limits the whole call, waiting for the answer and reading it, on every provider and whatever client sends it (default ten minutes). Running out throws `LlmTimeoutException`; a cancellation by the caller stays an `OperationCanceledException`. Set it to the longest answer you expect: a thinking model writing tens of thousands of tokens needs minutes. A streamed call is limited the same way, from the send to the last piece. `StreamIdleTimeoutMs` (off by default) limits a stream's silence: how long the provider may send nothing at all, not even a keep-alive. It counts only the waits on the provider, not the time your reader spends between pieces. ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`), with `messaging.system` = `llm` and `redb.route.endpoint`: - **Producer.** One `Client` span per agent run, `llm {provider}:{model}` (`… stream` for `stream=body`, opened when the body is read), with `llm.provider`, `llm.model.id`, the token counts and the stop reason. An error when the run fails, unless our own token cancelled it. - **Scheduled consumer** (`?schedule=`). One root `Consumer` span per tick, `llm {factory} receive`, with the model call and the route under it; never a child of the activity that started the routes. A failed tick — the model call or the route — marks it an error; our own stop does not. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. ## Comparison with Apache Camel `langchain4j-*` Camel's LLM story lives in a family — `camel-langchain4j-chat`, `-embeddings`, `-tokenizer`, `-tools`, `-agent`, `-web-search`, plus `camel-anthropic`, `camel-djl`, `camel-huggingface`. It's the closest analogue to what `redb.Route.Llm` does, so the comparison is worth pinning down. ### What we both ship | Capability | `camel-langchain4j-*` | `redb.Route.Llm` | |---|---|---| | Chat completion endpoint | `langchain4j-chat://chatId?chatModel=#model` | `llm://factory` | | Tool dispatch into a route | `langchain4j-tools://name` (separate component) | `.AsLlmTool("name")` (DSL aspect on any `From(...)`) | | Agent loop (multi-turn tool use) | `langchain4j-agent://...` | built into `IAgentEngine` | | Scheduled invocation | only via `from("timer:...").to("langchain4j-chat:...")` — the LLM is producer-only | **`From("llm://factory?schedule=...")` is a first-class consumer** — the LLM endpoint *is* the scheduler | | Streaming responses | LangChain4j streaming chat model | `stream=body` end-to-end: producer emits `IAsyncEnumerable`; `stream=calls` keeps the agent loop and streams each model call inside it; `redb.Route.Http` flushes per-chunk as SSE (`event: done` trailer carries final `llm.tokens.*` / `llm.cost.usd` / `llm.stop_reason`); `redb.Route.WebSocket` yields one `Text` frame per token | | Registry refs (`#name`) | yes — Camel-wide | yes — framework-wide; works for connection factories **and** prompts | | Conversation memory | LangChain4j `ChatMemoryStore` family | header / property conversation id; full persistence via `AddRedbLlmStorage()` | | Provider matrix | 25+ via LangChain4j (Anthropic, Bedrock, Vertex, Azure OpenAI, OpenAI, Mistral, Ollama, …) | 14 OpenAI-compatible behind one `OpenAiProvider` (incl. Anthropic Claude via the official OpenAI-compat endpoint, live-tested with Haiku 4.5 + Sonnet 4.6) + stub; native Anthropic Messages API on deck | | Embeddings / vector store | yes — `langchain4j-embeddings` + LangChain4j vector stores | **`IEmbeddingProvider` + `OpenAiEmbeddingProvider`** (OpenAI-compat) + **`embed://` scheme** (embed as a route step) + `RedbKnowledgeStore.SearchAsync` cosine; ANN index (pgvector/Qdrant) wraps `IKnowledgeStore` | | RAG primitives (ingest, retrieval, injection) | yes — via LangChain4j family | **`knowledge://` ingest + `knowledge_search` tool + `.Knowledge()` DSL** (keyword + semantic) — see [doc/RAG.md](doc/RAG.md); document loaders BYO | | Endpoint statistics | standard Camel JMX / Micrometer | `IEndpointStatistics` per LLM endpoint, surfaces in tsak.web with no setup | | Versioned prompt registry | not built in | `IPromptTemplateRegistry` + `#name` resolver | | Governance hooks (budget / approval / shadow / redaction) | not built in | hook interfaces inside the agent loop (Noop today, scaffolding ready) | ### Where redb.Route.Llm wins - **`From("llm://...")` is a first-class consumer.** This one has no equivalent in `camel-langchain4j-*` — every LangChain4j component there is producer-only. The Camel pattern for "fire the model on a schedule" is `from("timer:...").to("langchain4j-chat:...")`, which couples *what* fires the agent and *what* the agent says into the same route. We treat the LLM endpoint itself as a scheduler: ```csharp From("llm://groq?schedule=5m" + "&systemPromptRef=#watchdog-system" + "&initialBodyRef=#daily-brief" + "&tools=*") .To("rabbitmq://alerts"); ``` That's a self-driven agent in one declarative line — no auxiliary route, no glue code, no `Process` step to populate the body. And because both prompts use `#name` refs, *another* route can refresh either of them on its own schedule without touching the agent route. We don't know of an ESB connector that combines a scheduled LLM consumer with a registry-resolved prompt as the default shape. - **One scheme.** `llm://` and only `llm://`. Streaming, tools, scheduling and conversation are query options on the same endpoint — not five sibling components with five sets of headers and parameters to learn. - **Tools are routes, not a separate component.** `.AsLlmTool("name")` is a single-line DSL aspect that turns *any existing route* into an LLM tool. No extra NuGet package per connector. RabbitMQ, Kafka, HTTP, SQL, redb — they all become tools the same way: ```csharp r.From("rabbitmq://orders.lookup") .AsLlmTool("lookup_order").Description("Look up an order by id.") .Process(...); ``` The `0 bumps for all sibling connectors` outcome falls out of the architecture — there is nothing to coordinate between the LLM connector and the rest. - **One `OpenAiProvider` for 14 vendors.** OpenAI, Anthropic (Claude via the official OpenAI-compat endpoint), Groq, Cerebras, OpenRouter, Mistral, Together, HuggingFace, Deepseek, Ollama, LM Studio, GitHub Models, Gemini's OpenAI-compat endpoint and a `custom` slot all flow through the same class. Adding a vendor is a base-URL change, not a new package. - **`#`-registry refs apply to prompts — and pair with the LLM consumer.** Versioned prompts, A/B testing of prompts, and "another route refreshes the prompt every minute" all work without modifying the LLM route. `?systemPromptRef=#watchdog` resolves through `IPromptTemplateRegistry` (latest version) with a fallback to the generic route registry. Camel uses `#name` for components and beans; we extended the same convention to prompts. The combination with `From("llm://...?schedule=...")` is what makes a long-running self-driven agent practical: the agent route is declarative and unchanged; *who* refreshes the prompt and *when* is a separate concern that lives in another route. - **Governance hooks live inside the agent loop, not around it.** Budget, approval, shadow runs and redaction are interfaces invoked by `AgentEngine` itself. Today they're Noop, but the cut-points are in the right place — no need to wrap routes in extra `Process` steps to enforce a per-tenant token budget. - **Endpoint statistics for free.** Every `LlmEndpoint` exposes `IEndpointStatistics` (`MessagesIn/Out`, `BytesIn`, throughput, `LastErrorMessage`, `HealthStatus`) the same as Kafka or RabbitMQ — and tsak.web renders it with no extra wiring. - **Small dependency graph.** `redb.Route` + `Microsoft.Extensions.*` + `System.Text.Json`. No LangChain wrapper, no vendor SDKs. ### Where Camel `langchain4j-*` wins today - **Provider matrix is wider** — LangChain4j ships native bindings for vendors we don't cover yet (Bedrock, Vertex, Azure OpenAI with native auth, several local-only model toolkits). - **Document loaders & ANN vector index** — LangChain4j ships PDF/DOCX loaders and pluggable ANN vector stores. We ship the RAG *loop* (`knowledge://` ingest, `IEmbeddingProvider`, keyword + cosine search, `knowledge_search` tool, `.Knowledge()` injection, `embed://` scheme — [doc/RAG.md](doc/RAG.md)) but chunk plain text and cosine-scan in-process; an ANN index (pgvector/Qdrant) wraps `IKnowledgeStore.SearchAsync` for scale. - **Memory shapes** — windowed / token-windowed sliding-window memory comes in the box with LangChain4j. We ship persistent conversation transcripts via `AddRedbLlmStorage()` (`RedbConversationStore`, tree-backed with `parent_id` integrity), but window-by-N-messages and window-by-K-tokens shapes are not yet first-class — a route can implement them today via `Process` + the conversation store, just not as a one-line option. - **Streaming** is production-ready in both: LangChain4j ships its own `StreamingChatModel`, our `LlmProducer` emits `IAsyncEnumerable` into `Out.Body` and the HTTP / WebSocket consumers flush it on the wire (`text/event-stream` with an `event: done` summary trailer / one `WebSocketMessageType.Text` frame per token). For Anthropic Claude the native `AnthropicProvider` reads true SSE deltas; for the 14 OpenAI-compat backends `OpenAiProvider.StreamAsync` is the producer. ### Architectural differences worth knowing - **Wrapper vs. transport.** Camel's `langchain4j-*` is an adapter over LangChain4j — most architectural decisions (memory shape, agent shape, tool registration) are LangChain4j's, not Camel's. `redb.Route.Llm` talks HTTP directly through `ILlmProvider`, owns its own `LlmRequest/Response` types, and keeps the agent loop inside our codebase. Trade-off in plain terms: Camel inherits LangChain4j's whole feature set and its API churn; we own fewer features but every line is ours to evolve. - **One scheme vs. one component per primitive.** Camel mirrors LangChain4j's type system (chat, embeddings, tokenizer, agent, web-search) at the URI layer. We collapse those into options on a single endpoint when the workflow is "one inbound message, one assistant reply", and reserve new schemes only when the *transport semantics* change (embeddings will be `embed://` because they return vectors, not text). - **Tool registration philosophy.** In Camel, a tool is a route exposed through a dedicated `langchain4j-tools://` URI plus JSON-schema metadata configured on that component. In redb.Route.Llm, a tool is a route plus one DSL call (`.AsLlmTool`). Both end up registering a bridge that the agent loop dispatches through; the difference is whether tool-ness lives on the URI (Camel) or as an annotation on the route definition (us). The practical consequence is that we never had to coordinate package versions across `redb.Route.RabbitMQ`, `redb.Route.Kafka`, `redb.Route.Sql` etc. to add LLM-tool support — they each support it the day they ship a route builder, because `.AsLlmTool` operates on the abstraction every connector already implements. - **Prompt-as-data.** Both engines pass prompts as URI params or headers. We additionally route prompts through a registry (`#name`) so a prompt can be a versioned artifact mutated by another route. Camel can do this with custom processors; we made it the default convention to keep the declarative path clean. ### The one-liner summary A redb.Route.Llm route reads top-down like prose, and every step is a familiar redb.Route primitive (`From → Process → To → AsLlmTool → Mock`). That's the design target: one scheme, DSL aspects instead of sibling components, registry refs that work the same way as the rest of the framework. The cost is a younger ecosystem — fewer providers wired, no embeddings/vector store yet, no sliding-window memory shapes. The benefit is that the parts we *do* ship feel like the rest of redb.Route, not like a guest component grafted on. ## Layout ``` Engine/ IAgentEngine + AgentRequest/Response + AgentEngine + PromptRef Engine/Storage/ IPromptTemplateRegistry + InMemoryPromptTemplateRegistry Engine/Governance/ Budget / Approval / Redaction / Shadow stubs Engine/Observability/ Agent observer hooks Extensions/ AddRedbRouteLlm + AddLlmConnectionFactory + .Llm(...) sugar + RouteBuilderToolExtensions (.AsLlmTool) Fluent/ Llm.Factory("...").Temperature(...)...AsUri() Providers/ ILlmProvider, LlmRequest/Response, StubProvider, OpenAiProvider Telemetry/ LlmMetrics (Counter / Histogram on the shared Meter) Tools/ RouteToolBridge, ToolDescriptorRegistry, ToolFilter, LlmToolDsl Storage/Redb/ RedbConversationStore, RedbApprovalStore, RedbCostBudgetStore, RedbToolIdempotencyStore, RedbAuditObserver Storage/Redb/Schemas/ ConversationProps, MessageProps, ApprovalProps, CostBudgetProps, ToolAuditProps, ToolCacheProps, EvalRunProps, KnowledgeChunkProps, PromptTemplateProps LlmComponent.cs scheme "llm" + endpoint factory LlmConnectionFactory.cs POCO config + Build() → ILlmProvider LlmEndpoint.cs parses URI, resolves factory, wires statistics LlmEndpointOptions.cs per-call options bound from query LlmHeaders.cs header constants LlmProducer.cs ConnectableProducer — builds AgentRequest, runs engine, writes response LlmConsumer.cs PeriodicTimer scheduler, fires AgentEngine on each tick ``` ## Status - [x] Skeleton compiles cleanly across every target framework. - [x] StubProvider works end-to-end. - [x] `OpenAiProvider` — production transport covering 14 OpenAI-compatible providers (incl. **Anthropic Claude** via the official OpenAI-compat endpoint, live-tested against Haiku 4.5 and Sonnet 4.6). - [x] OTel + tsak.web statistics in place. - [x] `LlmProducer` (`.To("llm://...")`) — body in / assistant text out. - [x] `LlmConsumer` (`From("llm://...?schedule=...")`) — `PeriodicTimer` driver. - [x] Inline `.Llm("factory", ...)` extension shipped. - [x] Tools-as-routes — `.AsLlmTool` aspect, `RouteToolBridge`, no per-connector packages. - [x] `HttpFetchTool` (homeless tool) shipped in `redb.Route.Llm.Tools`. - [x] **Utility tools** — `JsonPathTool` (Newtonsoft full dialect, aligned with `JsonPathExpression`), `XPathTool` (wraps framework `XPathExpression`), `MathEvalTool` (delegates to `ExpressionResolver`), `RegexExtractTool`, `TavilyWebSearchTool`. All thin wrappers over framework primitives. - [x] **REDB persistence** — `AddRedbLlmStorage()` swaps in-memory defaults for `RedbConversationStore`/`RedbApprovalStore`/`RedbCostBudgetStore`/ `RedbToolIdempotencyStore` + `RedbAuditObserver`. Indexed business ids on `_objects.value_string`, tree integrity for transcripts. - [x] `#`-ref resolver for `systemPromptRef` / `initialBodyRef` (producer + consumer) with `IPromptTemplateRegistry` and `IRouteContext` fallback. - [x] Live integration tests in `tests/redb.Route.Tests.Llm` covering Groq / Mistral / Cerebras / Gemini / OpenRouter / **Anthropic Claude** and a deterministic DSL showcase (`BasicChat`, `InlineLlm`, `ToolRoute`, `ChainedLlm`, `HttpFetchTool`, `RegistryDrivenPrompt`, `ClaudeChat`). - [x] Native `AnthropicProvider` (Messages API) — shipped, runs alongside the OpenAI-compat path. Selected via `Provider = "anthropic"`. Reads true Messages-API SSE (`message_start` / `content_block_delta` / `message_stop`) for streaming; Messages-API-only features (prompt caching, computer-use, fine-grained image blocks) land here as needed. - [x] Governance hooks — enforced in the agent loop, with the boundaries stated: - [x] `IRedactionFilter` — always applied to tool input and output. An output the filter changed is never written to the tool cache. - [x] claims — a tool whose `RequiredClaims` cannot be verified is denied before approval and is never dispatched. The default source (`ExchangePrincipalClaimsSource`) reads the caller's principal from the exchange — a property a transport sets, never a client header — and takes its `scope` / `scp` values; a host with another vocabulary registers its own source. An anonymous caller, an unauthenticated identity and a run with no inbound request (a scheduled one, or one born after a broker hop, where properties do not survive) all fail the check. If a host removes the default source, a claim-declaring tool stops building at all, so a dead requirement cannot ship silently. - [x] approval — `IApprovalGate` is awaited when a tool sets `RequiresApproval` (discovered MCP tools declare it by default). The shipped default gate auto-approves and writes an audit row, so a real control point must be registered. - [x] idempotency — gated on the declared `SideEffect`: a tool that is not `ReadOnly` is reserved before it runs and a replay of the same `tool_use` id returns the stored result. Read-only tools are not reserved at all. - [x] tool-result cache — `Memoize` is answered in-process for the lifetime of the run, `Persist` through `IToolCacheStore` (24 h TTL); a hit is reported to observers as `cache_hit`. Only read-only tools may declare a caching policy. - [x] budgets — `?budgetInputTokens=`, `?budgetOutputTokens=` and `?budgetCostUsd=` (or `.Budget(...)`) reach the engine; cost is priced by `ICostCalculator`, and a cost ceiling nobody can price fails the run before the first call. `AddRedbLlmStorage()` swaps in cross-run accumulation over `ICostBudgetStore`. - [ ] shadow runner — `IShadowRunner` is a no-op. - [x] **Streaming producer surface** end-to-end. `LlmProducer.ProcessStreamingAsync` writes `IAsyncEnumerable` to `Out.Body`, sets `Content-Type: text/event-stream` and the `llm.streaming` header. `redb.Route.Http` (`HttpConsumer`) flushes each yield as one SSE `data:` frame with `Cache-Control: no-cache, no-transform` / `X-Accel-Buffering: no` / `IHttpResponseBodyFeature.DisableBuffering()`, followed by an `event: done` trailer carrying `llm.tokens.in/out`, `llm.stop_reason`, `llm.cost.usd`, `llm.tool.iterations`, `llm.model.id`, `llm.provider.id`. `redb.Route.WebSocket` (`WsConsumer`) yields one `WebSocketMessageType.Text` frame per non-empty chunk with `endOfMessage=true`. Test coverage: `HttpStreamingTests` (4), `WsStreamingTests` (2), env-gated `LiveStreamingTests` against Anthropic Claude (native SSE), Groq, Cerebras, Gemini, Mistral and OpenRouter. - [x] **RAG loop** — `knowledge://` ingest (`KnowledgeComponent`), `embed://` scheme, `IEmbeddingProvider`/`OpenAiEmbeddingProvider`, keyword `SearchTextAsync` + cosine `SearchAsync`, `KnowledgeSearchTool` (`knowledge_search`), `.Knowledge(coll, k)` retrieval DSL. Full guide: [doc/RAG.md](doc/RAG.md). - [ ] More first-party tools (SQL / file / redb scheme). See [doc/USER-GUIDE.md](doc/USER-GUIDE.md) — the full long-form guide covering every DSL shape, the `#`-registry pattern, all 14 providers, the Claude live-test suite, the testing strategy, the Camel comparison and a FAQ. For phase planning: doc/PLAN.md, doc/PHASE-1-MVP.md, doc/PHASE-2.md, doc/STATUS.md. ## Design principles 1. **One scheme.** `llm://` and only that. No `llm-agent://` / `llm-stream://` variants — modes are options. 2. **Three NuGet packages, never more.** `redb.Route.Llm.Abstractions` (provider contract + content blocks + tool-descriptor interface), `redb.Route.Llm` (engine + providers + DSL aspects), and `redb.Route.Llm.Tools` (homeless tools without their own connector). Tools that *do* belong to a connector live in that connector's package, e.g. `SqlTool` in `redb.Route.Sql`. 3. **Tools are routes.** A tool is whatever a route says it is — built from the same DSL primitives. Zero per-connector LLM coupling. 4. **DSL is sugar.** `WithSystemPrompt`/`WithBudget`/`WithShadow`/… are extension methods over `IRouteDefinition.Process(...)`. No new core types. 5. **No `dynamic`.** Capability metadata, requests, responses — strongly typed. 6. **Registry-refs are the framework-wide pattern.** `#name` resolves from the route registry. Already used by Kafka/S3/Firebase connection factories; prompts now follow the same convention. 7. **redb engine for state.** Conversation, idempotency, audit — `[RedbScheme]` POCOs, opt-in via `AddRedbLlmStorage()`. 8. **Stand-alone.** No dependency on Tsak or Identity. Path: redb-route/redb.Route.Llm/Storage/Redb/RedbApprovalStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbApprovalStore.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . One /// row per decision; the approval id lives in _objects.value_string /// (partial index on PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX)) and, /// normalized, in _objects._value_unique — one approval id resolves to /// exactly one recorded decision, first wins. /// /// The store does not own an instance — each call /// resolves one through IRouteContext.GetRedbService(name, exchange), /// which honours the per-exchange scope cache. The redb name is read from /// exchange.Properties[LlmKeys.RedbName] (set by the LLM endpoint URI), /// falling back to the constructor-supplied default name and then to the host's /// default unnamed instance. /// /// public sealed class RedbApprovalStore : IApprovalStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the store. Scheme is synced by the host's redb.InitializeAsync(). public RedbApprovalStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// /// The service a call works on: the exchange's with one; without one a scope of its own, handed back in /// for the caller to dispose, so concurrent calls do not share the context's single /// instance and its one connection. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) name = s; if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = _context.CreateRedbScope(name); return owned.Service; } /// public async Task RecordAsync(ApprovalRequest request, ApprovalDecision decision, IExchange? exchange = null, CancellationToken ct = default) { var id = decision.ApprovalId ?? Guid.NewGuid().ToString("N"); var row = new RedbObject { value_string = id, // A caller-supplied approval id must resolve to ONE decision: the key rides // in _value_unique, and a duplicate record of the same id is dropped — // first wins (a self-generated GUID never collides). ValueUnique = RedbUniqueKey.Normalize(id), Props = new ApprovalProps { ConversationId = request.ConversationId, ToolName = request.Tool.Name, ToolUseId = request.ToolUseId, Approved = decision.Approved, Reason = decision.Reason, ApprovedBy = decision.ApprovalId, DecidedAtUtc = DateTimeOffset.UtcNow, InputJson = request.InputJson } }; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; try { await redb.SaveAsync(row).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // The decision for this approval id is already recorded — first wins. } } /// public async Task FindAsync(string approvalId, IExchange? exchange = null, CancellationToken ct = default) { var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var hit = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(approvalId)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (hit is null) return null; return new ApprovalRecord { ApprovalId = hit.value_string ?? approvalId, ConversationId = hit.Props.ConversationId, ToolName = hit.Props.ToolName, InputJson = hit.Props.InputJson, Approved = hit.Props.Approved, Reason = hit.Props.Reason, CreatedAtUtc = hit.Props.DecidedAtUtc.UtcDateTime }; } } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbAuditObserver.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbAuditObserver.cs ---- using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed that persists one /// row per tool invocation. Non-blocking by /// contract: a failed write never breaks a run, and it is logged as a warning with /// the tool, the tool_use id and the exchange id, so the missing row can be found. /// /// The observer is invoked from inside the agent loop, not from a route /// pipeline, and therefore has no IExchange in scope. Many runs call it at /// once, so every call opens a redb scope of its own with /// IRouteContext.CreateRedbScope(name) and releases it: a shared instance would /// put every run on one connection. The scope uses the constructor-supplied default /// name, or the host's default service when null. A custom observer can be /// substituted to pipe audit rows elsewhere. /// /// /// The row belongs to the route's transaction when there is one: under /// .Transacted() it is written and rolled back together with the tool writes it /// describes. /// /// public sealed class RedbAuditObserver : IAgentObserver { private readonly IRouteContext _context; private readonly string? _defaultRedbName; private ILogger? _logger; /// Creates the observer. Scheme is synced by the host's redb.InitializeAsync(). public RedbAuditObserver(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Task.CompletedTask; /// public async Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) { try { var outcome = context.Exception is not null ? "error" : context.Skipped ? (context.SkipReason?.Contains("denied", StringComparison.OrdinalIgnoreCase) == true ? "denied" : "skipped") : "success"; var row = new RedbObject { // The tool name leads the row name so an operator can slice by tool on a base field // (_objects.name) and read the scheme without joining anything. Filtering by the ToolName // property is also server-side (props-typed Where), just costlier. name = $"audit:{context.Tool.Name}:{context.Run.ExchangeId}:{context.ToolUseId}", Props = new ToolAuditProps { ConversationId = context.Run.ConversationId ?? string.Empty, ToolName = context.Tool.Name, ToolUseId = context.ToolUseId, InvokedAtUtc = DateTimeOffset.UtcNow.Subtract(context.Duration), DurationMs = (int)context.Duration.TotalMilliseconds, Outcome = outcome, SkipReason = context.SkipReason, InputJson = context.InputJson, OutputJson = context.OutputJson, ErrorMessage = context.Exception?.Message } }; // The instance the endpoint chose (?redb=) decides, as it does for every store; else the registration's. await using var scope = _context.CreateRedbScope(context.Run.RedbName ?? _defaultRedbName); await scope.Service.SaveAsync(row).ConfigureAwait(false); } catch (Exception ex) { // A lost audit row never breaks the run, but it must not vanish either: the operator has to be able to // find the gap. That includes a refusal to open the scope, which is a configuration error. Logger()?.LogWarning(ex, "Audit row for tool '{Tool}' (tool_use {ToolUseId}, exchange {ExchangeId}) was not written; the run goes on.", context.Tool.Name, context.ToolUseId, context.Run.ExchangeId); } } /// public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Task.CompletedTask; private ILogger? Logger() => _logger ??= (_context.GetService() ?? _context.GetServiceProvider()?.GetService(typeof(ILoggerFactory)) as ILoggerFactory) ?.CreateLogger(); } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbBatchStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbBatchStore.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . One row /// per submitted batch; the batch id lives in _objects.value_string /// (partial index on PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX)) and, /// normalized, in _objects._value_unique — the per-scheme unique index /// keeps a batch raced between the submit path and a fast webhook callback on /// a single row. /// /// The store does not own an instance — each call /// resolves one through IRouteContext.GetRedbService(name, exchange), /// which honours the per-exchange scope cache. The redb name is read from /// exchange.Properties[LlmKeys.RedbName] (set by the LLM endpoint URI), /// falling back to the constructor-supplied default name and then to the host's /// default unnamed instance. /// /// public sealed class RedbBatchStore : IBatchStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the store. Scheme is synced by the host's redb.InitializeAsync(). public RedbBatchStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// /// The service a call works on: the exchange's with one; without one a scope of its own, handed back in /// for the caller to dispose, so concurrent calls do not share the context's single /// instance and its one connection. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) name = s; if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = _context.CreateRedbScope(name); return owned.Service; } /// public async Task RegisterAsync(BatchJobRecord record, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(record); ArgumentException.ThrowIfNullOrWhiteSpace(record.BatchId); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var existing = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(record.BatchId)) .FirstOrDefaultAsync() .ConfigureAwait(false); var props = ToProps(record); if (existing is null) { // The batch id rides in _value_unique: duplicate submit registrations (a // redelivered exchange, a RegisterManyAsync reconciliation) race to a // single row — the unique index keeps them on one, the loser re-registers // onto the winner. The webhook itself never registers; it only advances // status via UpdateStatusAsync. var row = new RedbObject { value_string = record.BatchId, ValueUnique = RedbUniqueKey.Normalize(record.BatchId), Props = props }; try { await redb.SaveAsync(row).ConfigureAwait(false); } catch (RedbUniqueViolationException) { var winnerKey = row.ValueUnique; var winner = await redb.Query() .WhereRedb(o => o.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (deleted mid-race) // Never regress a terminal status: between our miss and this catch the // webhook may have already marked the winner completed/failed, and the // framework never polls — a redelivered "submitted" overwriting it // would report the batch as pending forever. if (IsTerminal(winner.Props.Status) && !IsTerminal(props.Status)) return; winner.Props = props; winner.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(winner).ConfigureAwait(false); } } else { // Same terminal-status guard as the collision path below used to carry alone. The // unique lookup now finds the winner up front, so a redelivered "submitted" arrives // here — and without the guard this branch could downgrade a completed batch to pending // forever whenever the raw ids matched. The guard belongs to the register, not to // the way the row was found. if (IsTerminal(existing.Props.Status) && !IsTerminal(props.Status)) return; existing.Props = props; existing.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(existing).ConfigureAwait(false); } } /// public async Task RegisterManyAsync(IEnumerable records, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(records); // One record per id even within one call — the last entry wins. Two fresh // records sharing an id would otherwise self-collide on the unique index // inside a single bulk save (the pre-barrier code silently inserted both). var input = records .Where(r => r is not null && !string.IsNullOrWhiteSpace(r.BatchId)) .GroupBy(r => r.BatchId, StringComparer.Ordinal) .Select(g => g.Last()) .ToList(); if (input.Count == 0) return; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; await RegisterManyCoreAsync(redb, input, retryOnRace: true, ct).ConfigureAwait(false); } private static async Task RegisterManyCoreAsync( IRedbService redb, List input, bool retryOnRace, CancellationToken ct) { // ONE IN-clause lookup for all batch ids (partial index on PG/SQLite; a scan // on MSSQL), then ONE bulk SaveAsync — insert/update streams are internal. var keys = input.Select(r => r.BatchId).ToArray(); var existingByKey = (await redb.Query() .WhereRedb(o => keys.Contains(o.ValueString)) .ToListAsync() .ConfigureAwait(false)) .Where(o => o.value_string is not null) .ToDictionary(o => o.value_string!, StringComparer.Ordinal); if (!retryOnRace) { // Retry pass after a lost creation race: the winners hold the unique key — // resolve by it too, so every collided batch id becomes an update. var normByKey = input.ToDictionary(r => r.BatchId, r => RedbUniqueKey.Normalize(r.BatchId), StringComparer.Ordinal); var norms = normByKey.Values.ToArray(); var keyByNorm = normByKey.ToDictionary(kv => kv.Value, kv => kv.Key, StringComparer.Ordinal); var byUnique = await redb.Query() .WhereRedb(o => norms.Contains(o.ValueUnique)) .ToListAsync() .ConfigureAwait(false); foreach (var row in byUnique) if (row.ValueUnique is { } u && keyByNorm.TryGetValue(u, out var k)) existingByKey.TryAdd(k, row); } var rowsToSave = new List(input.Count); var now = DateTimeOffset.UtcNow; foreach (var record in input) { ct.ThrowIfCancellationRequested(); var props = ToProps(record); if (existingByKey.TryGetValue(record.BatchId, out var existing)) { // Hash-pre-check skips no-op upserts so SaveAsync’s change-tracking // doesn't re-read originals from DB for unchanged rows. On the retry // pass it is skipped: the first pass already mutated instances, and a // pre-check comparing a copy to itself would silently drop the update. var hashBefore = existing.ComputeHash(); existing.Props = props; if (retryOnRace && existing.ComputeHash() == hashBefore) continue; existing.date_modify = now; rowsToSave.Add(existing); } else { rowsToSave.Add(new RedbObject { value_string = record.BatchId, ValueUnique = RedbUniqueKey.Normalize(record.BatchId), Props = props }); } } if (rowsToSave.Count == 0) return; try { await redb.SaveAsync(rowsToSave).ConfigureAwait(false); } catch (RedbUniqueViolationException) when (retryOnRace) { // A concurrent writer claimed one of the fresh batch ids after our lookup // and the batch rolled back whole. The winners are visible now: rebuild // from a fresh lookup and retry once — a second violation is a real error. await RegisterManyCoreAsync(redb, input, retryOnRace: false, ct).ConfigureAwait(false); } } /// Lifecycle states the webhook writes once and nothing may undo. private static bool IsTerminal(string status) => status is "completed" or "failed" or "cancelled"; private static LlmBatchProps ToProps(BatchJobRecord record) => new() { ProviderId = record.ProviderId, ModelId = record.ModelId, ConversationId = record.ConversationId, Status = record.Status, SubmittedAtUtc = new DateTimeOffset(DateTime.SpecifyKind(record.SubmittedAtUtc, DateTimeKind.Utc)), CompletedAtUtc = record.CompletedAtUtc is { } c ? new DateTimeOffset(DateTime.SpecifyKind(c, DateTimeKind.Utc)) : null, ResultUrl = record.ResultUrl, MetadataJson = record.MetadataJson, ErrorMessage = record.ErrorMessage, AppendToConversation = record.AppendToConversation }; /// public async Task GetAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(batchId); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var row = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(batchId)) .FirstOrDefaultAsync() .ConfigureAwait(false); return row is null ? null : Materialize(row, batchId); } /// public async Task UpdateStatusAsync( string batchId, string status, DateTimeOffset? completedAtUtc = null, string? errorMessage = null, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(batchId); ArgumentException.ThrowIfNullOrWhiteSpace(status); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var row = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(batchId)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) return; row.Props.Status = status; if (completedAtUtc is { } c) row.Props.CompletedAtUtc = c.ToUniversalTime(); if (errorMessage is not null) row.Props.ErrorMessage = errorMessage; row.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(row).ConfigureAwait(false); } private static BatchJobRecord Materialize(RedbObject row, string batchId) => new() { BatchId = row.value_string ?? batchId, ProviderId = row.Props.ProviderId, ModelId = row.Props.ModelId, ConversationId = row.Props.ConversationId, Status = row.Props.Status, SubmittedAtUtc = row.Props.SubmittedAtUtc.UtcDateTime, CompletedAtUtc = row.Props.CompletedAtUtc?.UtcDateTime, ResultUrl = row.Props.ResultUrl, MetadataJson = row.Props.MetadataJson, ErrorMessage = row.Props.ErrorMessage, AppendToConversation = row.Props.AppendToConversation }; } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbConversationStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbConversationStore.cs ---- using System.Collections.Concurrent; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . Tree integrity is enforced by /// CreateChildAsync; transcript reads use redb's tree primitives /// (TreeQuery<T>(root) for descendants, GetPathToRootAsync /// for breadcrumbs — root → leaf order) — server-side tree traversal, not /// client-side rebuilding. /// Per-row business identifiers live on _objects base columns — /// value_string for the conversation/message id (partial index on /// PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX)) and value_long /// on each message for the conversation FK (== root _objects.id, indexed /// on every provider). The conversation id also rides, normalized, in the /// root's _objects._value_unique: the per-scheme unique index makes /// concurrent creators of one conversation converge on a single root instead /// of splitting the transcript. /// /// Conversation isolation is enforced by the value_long FK, not by tree /// shape. Head detection and message lookup are scoped by it explicitly, so a /// read can never surface — and a write can never attach under — another /// conversation's node, independent of how a provider evaluates tree filters. /// /// Content blocks are stored as a typed nested array, no JSON marshalling /// for our own schema. /// /// The is resolved per call through /// : /// when an is supplied (the engine forwards the route /// pipeline's exchange) the route framework hands out a per-exchange scoped /// instance and disposes it with the exchange. The named instance — /// ?redb=my-llm-db on the URI — is read from /// exchange.Properties[LlmKeys.RedbName]; missing or null falls back to /// the default IRedbService registered in the context (the host's /// instance from services.AddRedb()). /// /// public sealed class RedbConversationStore : IConversationStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; private readonly ConcurrentDictionary _rootIds = new(StringComparer.Ordinal); private static readonly TimeSpan RootCacheTtl = TimeSpan.FromMinutes(10); /// /// Creates a new store backed by the route context's redb instance(s). /// /// Route context that knows how to resolve named/default . /// /// Optional default name. When the runtime exchange does not carry /// in its properties this name is used; when /// it is null/empty the default unnamed instance is used. /// public RedbConversationStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } private readonly record struct CachedRoot(long Id, DateTimeOffset ExpiresAt); /// /// Resolves the redb instance for this call and returns the name it was /// resolved under. The name is part of the root-id cache key: the instance is /// chosen per exchange (?redb= → LlmKeys.RedbName), so a cache /// keyed by conversation id alone would hand back an id resolved in database A /// while the call runs against database B. /// Without an exchange the call gets a scope of its own in , for the caller to dispose, /// so concurrent calls do not share the context's single instance and its one connection. /// private (IRedbService Redb, string Name) Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) { name = s; } var effective = name ?? string.Empty; if (exchange is not null) { owned = null; return (_context.GetRedbService(effective, exchange), effective); } owned = _context.CreateRedbScope(name); return (owned.Service, effective); } // NUL separator: instance name and conversation id are both opaque caller // strings, so any printable separator could be forged into a collision // ("a" + "b:c" vs "a:b" + "c"). private const char CacheKeySeparator = (char)0; private static string CacheKey(string redbName, string conversationId) => string.Concat(redbName, CacheKeySeparator, conversationId); /// public async Task AppendAsync( string conversationId, string? parentMessageId, LlmMessage message, ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default) { var (redb, redbName) = Resolve(exchange, out var owned); await using var ownedScope = owned; var rootId = await GetOrCreateRootIdAsync(redb, redbName, conversationId, ct).ConfigureAwait(false); // The root object itself is needed only as the tree parent of a first-level // message; the counter update below re-reads it under its own lock anyway, // so threaded appends (parent supplied) skip the full root load entirely. IRedbObject parentObj; if (parentMessageId is not null) { // Scoped by rootId on purpose: the lookup is by an opaque caller-supplied // id over the whole schema, so an unscoped resolve would happily attach // this message under another conversation's node — a cross-conversation // write that no later read can undo. parentObj = await FindMessageByValueStringAsync(redb, parentMessageId, rootId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Parent message {parentMessageId} not found in conversation {conversationId}."); } else { parentObj = await redb.LoadAsync(rootId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Conversation root {conversationId} disappeared between lookup and load."); } var newId = Guid.NewGuid().ToString("N"); var child = new TreeRedbObject { value_string = newId, value_long = rootId, Props = new MessageProps { Role = message.Role, Iteration = meta.Iteration, CreatedAtUtc = meta.CreatedAtUtc, ProviderId = meta.ProviderId, ModelId = meta.ModelId, StopReason = meta.StopReason?.ToString(), ToolUseId = meta.ToolUseId, InputTokens = meta.Usage.InputTokens, OutputTokens = meta.Usage.OutputTokens, CacheCreationInputTokens = meta.Usage.CacheCreationInputTokens, CacheReadInputTokens = meta.Usage.CacheReadInputTokens, Temperature = meta.Temperature, MaxTokens = meta.MaxTokens, TopP = meta.TopP, PromptTemplateName = meta.PromptTemplateName, PromptTemplateVersion = meta.PromptTemplateVersion, ToolSetHash = meta.ToolSetHash, ProviderSystemFingerprint = meta.ProviderSystemFingerprint, UserId = meta.UserId, AuditTags = meta.AuditTags is { Count: > 0 } ? new Dictionary(meta.AuditTags, StringComparer.Ordinal) : null, FactoryName = meta.FactoryName, BaseUrl = meta.BaseUrl, ProviderResponseId = meta.ProviderResponseId, LatencyMs = meta.LatencyMs, ApiKeyFingerprint = meta.ApiKeyFingerprint, RetryCount = meta.RetryCount, Content = ToStoredBlocks(message.Content) } }; await redb.CreateChildAsync(child, parentObj).ConfigureAwait(false); // Counter update is a read-modify-write shared by every concurrent append // (parallel tool branches, other nodes) — serialise it on the root row the // same way RedbCostBudgetStore does, or increments get lost. await redb.Context.ExecuteAtomicAsync(async () => { await redb.LockForUpdateAsync(rootId).ConfigureAwait(false); // Re-read BY QUERY after the lock, not redb.LoadAsync. The core has since // stopped serving the zero-DB cache shortcut inside a transaction, but the query path // guarantees a fresh row read regardless of cache mode or core version — // and a stale pre-lock copy here would lose another node's increments, // the exact defect this lock exists to prevent. var fresh = await redb.Query() .WhereRedb(o => o.Id == rootId) .FirstOrDefaultAsync() .ConfigureAwait(false) ?? throw new InvalidOperationException( $"Conversation root {conversationId} disappeared during counter update."); var activityAt = new DateTimeOffset(DateTime.SpecifyKind(meta.CreatedAtUtc, DateTimeKind.Utc)); fresh.Props.LastActivityAtUtc = activityAt; fresh.Props.TotalInputTokens += meta.Usage.InputTokens; fresh.Props.TotalOutputTokens += meta.Usage.OutputTokens; // Framework does not auto-stamp date_modify; mirror LastActivityAtUtc. fresh.date_modify = activityAt; await redb.SaveAsync(fresh).ConfigureAwait(false); }).ConfigureAwait(false); return newId; } /// public async Task> LoadPathAsync( string conversationId, string? leafId = null, IExchange? exchange = null, CancellationToken ct = default) { var (redb, redbName) = Resolve(exchange, out var owned); await using var ownedScope = owned; var rootId = await GetOrCreateRootIdAsync(redb, redbName, conversationId, ct).ConfigureAwait(false); TreeRedbObject? leafObj; if (leafId is not null) { leafObj = await FindMessageByValueStringAsync(redb, leafId, rootId).ConfigureAwait(false); if (leafObj is null) return []; } else { // Head detection scoped by the conversation FK, not by tree traversal. // // The newest message of a conversation is always a leaf — anything that // became a parent has a child created after it — so "newest by // date_create within this conversation" is exactly "the freshest leaf", // without depending on how a provider implements WhereLeaves(). That // matters: a rooted TreeQuery(root).WhereLeaves() used to be evaluated // as "freshest leaf of the whole schema" (fixed for Pro in d88ff9fe, // still open for the Free PVT routing), which returned another // conversation's transcript and then attached the next message under it. // // value_long carries the root's _objects.id and lives on the indexed // _objects row, so this stays a single-row server-side lookup. var head = await redb.Query() .WhereRedb(o => o.ValueLong == rootId) .OrderByDescendingRedb(o => o.DateCreate) .FirstOrDefaultAsync() .ConfigureAwait(false); if (head is null) return []; // The path walker needs a TreeRedbObject; reload the leaf as a // single-node tree to satisfy GetPathToRootAsync. leafObj = await redb.LoadTreeAsync(head.id, maxDepth: 0).ConfigureAwait(false); if (leafObj is null) return []; } // Server-side ancestor walk; returns root → leaf order. The conversation // root is a ConversationProps node — GetPathToRootAsync // still returns it (cast to MessageProps with default Props), so trim by id. // The Role guard is belt-and-braces for that cast: a role-less row is not a // message, and letting one through means posting an empty role to the // provider (a 400 that looks like a model problem, not a storage one). var ancestors = (await redb.GetPathToRootAsync(leafObj).ConfigureAwait(false)).ToList(); var path = ancestors .Where(a => a.id != rootId && !string.IsNullOrEmpty(a.Props.Role)) .Select(row => Materialize(row, conversationId, rootId, parentLookup: null)) .ToList(); return path; } /// public async Task> LoadTreeAsync( string conversationId, IExchange? exchange = null, CancellationToken ct = default) => await LoadAllMessagesAsync(conversationId, exchange).ConfigureAwait(false); private async Task> LoadAllMessagesAsync(string conversationId, IExchange? exchange) { var (redb, redbName) = Resolve(exchange, out var owned); await using var ownedScope = owned; var rootId = await GetOrCreateRootIdAsync(redb, redbName, conversationId, CancellationToken.None).ConfigureAwait(false); var rootObj = await redb.LoadAsync(rootId).ConfigureAwait(false); if (rootObj is null) return []; // Server-side tree traversal: every MessageProps descendant of this // conversation root, regardless of nesting depth. ToFlatListAsync // skips Parent/Children pointer building — we rebuild parent linkage // manually below via the idToValueString lookup. var rows = await redb.TreeQuery(rootObj) .ToFlatListAsync() .ConfigureAwait(false); // Map redb id → business id (value_string) so child rows can resolve // their parent's business id from the tree's native parent_id. var idToValueString = rows.ToDictionary(r => r.id, r => r.value_string); var list = new List(rows.Count); foreach (var row in rows) list.Add(Materialize(row, conversationId, rootId, idToValueString)); return list; } private static ConversationMessage Materialize( TreeRedbObject row, string conversationId, long rootId, IReadOnlyDictionary? parentLookup) { string? parentValueString = null; if (row.parent_id is { } pid && pid != rootId && parentLookup is not null && parentLookup.TryGetValue(pid, out var pvs)) { parentValueString = pvs; } return new ConversationMessage { Id = row.value_string ?? row.id.ToString(), ParentId = parentValueString, ConversationId = conversationId, Message = new LlmMessage { Role = row.Props.Role, Content = FromStoredBlocks(row.Props.Content) }, Meta = new ConversationMessageMeta { CreatedAtUtc = row.Props.CreatedAtUtc.UtcDateTime, Iteration = row.Props.Iteration, ProviderId = row.Props.ProviderId, ModelId = row.Props.ModelId, StopReason = ParseStopReason(row.Props.StopReason), Usage = new LlmUsage( row.Props.InputTokens, row.Props.OutputTokens, row.Props.CacheCreationInputTokens, row.Props.CacheReadInputTokens), ToolUseId = row.Props.ToolUseId, Temperature = row.Props.Temperature, MaxTokens = row.Props.MaxTokens, TopP = row.Props.TopP, PromptTemplateName = row.Props.PromptTemplateName, PromptTemplateVersion = row.Props.PromptTemplateVersion, ToolSetHash = row.Props.ToolSetHash, ProviderSystemFingerprint = row.Props.ProviderSystemFingerprint, UserId = row.Props.UserId, AuditTags = row.Props.AuditTags is { Count: > 0 } ? new Dictionary(row.Props.AuditTags, StringComparer.Ordinal) : null, FactoryName = row.Props.FactoryName, BaseUrl = row.Props.BaseUrl, ProviderResponseId = row.Props.ProviderResponseId, LatencyMs = row.Props.LatencyMs, ApiKeyFingerprint = row.Props.ApiKeyFingerprint, RetryCount = row.Props.RetryCount } }; } private async Task GetOrCreateRootIdAsync( IRedbService redb, string redbName, string conversationId, CancellationToken ct) { // TTL-bound cache: stale entries (e.g. someone purged the conversation // out-of-band) self-heal after RootCacheTtl instead of pinning a dead // id for the whole process lifetime. Keyed by (instance, conversation) — // the same conversation id in two named databases resolves to two // different root ids, and a conversation-only key would cross them. var key = CacheKey(redbName, conversationId); var now = DateTimeOffset.UtcNow; if (_rootIds.TryGetValue(key, out var cached) && cached.ExpiresAt > now) return cached.Id; var hit = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(conversationId)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (hit is not null) { _rootIds[key] = new CachedRoot(hit.id, now + RootCacheTtl); return hit.id; } // The conversation key rides in _value_unique too: of two concurrent creators // (parallel exchanges, cluster nodes) the per-scheme unique index lets exactly // one root through — without it each writer minted its own root and the // conversation split in two, every reader seeing an arbitrary half. var root = new RedbObject { value_string = conversationId, ValueUnique = RedbUniqueKey.Normalize(conversationId), Props = new ConversationProps { TenantId = string.Empty, Status = "active", StartedAtUtc = now, LastActivityAtUtc = now } }; long id; try { id = await redb.SaveAsync(root).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race. Resolve the winner by the collided key — exactly // one row can hold it — and cache THAT id, never our stillborn row's. var winnerKey = root.ValueUnique; var winner = await redb.Query() .WhereRedb(x => x.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (purged mid-race) — surface the original failure id = winner.id; } _rootIds[key] = new CachedRoot(id, now + RootCacheTtl); return id; } /// /// Resolves a message by its business id within one conversation. /// is not an optimisation — the id is opaque and /// caller-supplied, so an unscoped lookup lets a caller reach (and, through /// AppendAsync, write under) another conversation's node. Returns null /// when the message does not exist or belongs to a different conversation; /// the two cases are deliberately indistinguishable to the caller. /// private static async Task?> FindMessageByValueStringAsync( IRedbService redb, string messageId, long rootId) { // Deliberately NOT ValueUnique (the one value_string lookup left): messages carry // no unique key — messageId is only unique within its conversation, scoped by rootId here. var hit = await redb.Query() .WhereRedb(x => x.ValueString == messageId && x.ValueLong == rootId) .FirstOrDefaultAsync() .ConfigureAwait(false); return hit is null ? null : await redb.LoadTreeAsync(hit.id, maxDepth: 0).ConfigureAwait(false); } private static MessageContentBlock[] ToStoredBlocks(IReadOnlyList blocks) { if (blocks.Count == 0) return []; var arr = new MessageContentBlock[blocks.Count]; for (var i = 0; i < blocks.Count; i++) { arr[i] = blocks[i] switch { LlmTextBlock t => new MessageContentBlock { Kind = "text", Text = t.Text }, LlmToolUseBlock u => new MessageContentBlock { Kind = "tool_use", ToolUseId = u.ToolUseId, ToolName = u.Name, InputJson = u.InputJson }, LlmToolResultBlock r => new MessageContentBlock { Kind = "tool_result", ToolUseId = r.ToolUseId, OutputJson = r.OutputJson, IsError = r.IsError }, // The thought goes in its own field, with the signature it is authenticated by. LlmThinkingBlock t => new MessageContentBlock { Kind = "thinking", ThinkingText = t.Text, Signature = t.Signature, RedactedData = t.RedactedData }, _ => throw new NotSupportedException( $"Content block type '{blocks[i].GetType().Name}' has no stored form.") }; } return arr; } private static IReadOnlyList FromStoredBlocks(MessageContentBlock[]? stored) { if (stored is null || stored.Length == 0) return []; var list = new List(stored.Length); foreach (var b in stored) { list.Add(b.Kind switch { "text" => new LlmTextBlock(b.Text ?? string.Empty), "tool_use" => new LlmToolUseBlock(b.ToolUseId ?? string.Empty, b.ToolName ?? string.Empty, b.InputJson ?? "{}"), "tool_result" => new LlmToolResultBlock(b.ToolUseId ?? string.Empty, b.OutputJson ?? string.Empty, b.IsError), "thinking" => new LlmThinkingBlock( b.ThinkingText ?? string.Empty, b.Signature, b.RedactedData), _ => throw new InvalidOperationException( $"Stored content block kind '{b.Kind}' is unknown.") }); } return list; } private static LlmStopReason? ParseStopReason(string? raw) => Enum.TryParse(raw, out var parsed) ? parsed : null; } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbCostBudgetStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbCostBudgetStore.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . One /// row per conversation, keyed on the conversation id stored in /// _objects.value_string (partial index on PostgreSQL/SQLite; MSSQL cannot /// index NVARCHAR(MAX)) and, normalized, in _objects._value_unique — the /// per-scheme unique index guarantees ONE budget row per conversation even under /// concurrent first writes. /// /// uses the framework's pessimistic-locking primitives /// (redb.Context.ExecuteAtomicAsync + redb.LockForUpdateAsync) so /// concurrent updates from multiple processes / nodes serialise on the row /// instead of trampling each other. No raw SQL. /// /// /// The store does not own an instance. A call with an /// exchange resolves the exchange's service through /// IRouteContext.GetRedbService(name, exchange); a call without one (the /// budget enforcer's, made from every concurrent run) opens a scope of its own with /// IRouteContext.CreateRedbScope(name) and releases it when the call ends. The /// redb name is read from exchange.Properties[LlmKeys.RedbName] (set by the LLM /// endpoint URI), falling back to the constructor-supplied default name and then to the /// host's default unnamed instance. /// /// public sealed class RedbCostBudgetStore : ICostBudgetStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the store. Scheme is synced by the host's redb.InitializeAsync(). public RedbCostBudgetStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// /// The service a call works on. With an exchange it is the exchange's service. Without one - the budget enforcer /// calls without an exchange, from every concurrent run - the call opens a scope of its own and hands it back in /// for the caller to dispose: a shared instance would put every run on one connection, /// and the second of two simultaneous commands on it is refused. A refusal to open that scope is a configuration /// error and is not caught here. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) name = s; if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = _context.CreateRedbScope(name); return owned.Service; } /// public async ValueTask GetUsageAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default) { var redb = Resolve(exchange, out var owned); await using var scope = owned; var row = await LoadAsync(redb, conversationId).ConfigureAwait(false); return row is null ? AgentUsage.Zero : new AgentUsage((int)row.Props.InputTokens, (int)row.Props.OutputTokens, row.Props.CostUsd); } /// public async ValueTask AddAsync(string conversationId, AgentUsage delta, IExchange? exchange = null, CancellationToken ct = default) { var redb = Resolve(exchange, out var owned); await using var scope = owned; // Two passes at most: a row soft-deleted mid-flight (a concurrent ResetAsync — // the documented daily/monthly counter roll) sends the loop back to the // first-write branch, which starts the new period with this delta instead of // throwing it away. for (var attempt = 0; ; attempt++) { // First write happens OUTSIDE the atomic block: the row carries the // conversation key in _value_unique, so of two concurrent first writers the // per-scheme unique index lets exactly one insert through. The row-lock // alone never covered creation: both writers used to insert, splitting the // budget across two rows. (The core now savepoints saves under a caller's // transaction, so a violation no longer dooms it — the insert stays outside // our own atomic block anyway: the common first write needs no transaction // at all, and the loser recovers on a clean connection state.) var existing = await LoadAsync(redb, conversationId).ConfigureAwait(false); if (existing is null) { var fresh = new RedbObject { value_string = conversationId, ValueUnique = RedbUniqueKey.Normalize(conversationId), Props = new CostBudgetProps { InputTokens = delta.InputTokens, OutputTokens = delta.OutputTokens, CostUsd = delta.CostUsd, UpdatedAtUtc = DateTimeOffset.UtcNow } }; try { await redb.SaveAsync(fresh).ConfigureAwait(false); return new AgentUsage((int)fresh.Props.InputTokens, (int)fresh.Props.OutputTokens, fresh.Props.CostUsd); } catch (RedbUniqueViolationException) { // Lost the first-write race — the winner's row exists now; fall // through to the ordinary locked increment onto it. } } var updated = await TryIncrementAsync(redb, conversationId, existing?.id, delta).ConfigureAwait(false); if (updated is not null) return updated.Value; // The row vanished between resolve and increment (concurrent ResetAsync). if (attempt == 1) throw new InvalidOperationException( $"Cost-budget row for conversation '{conversationId}' keeps disappearing mid-increment."); } } /// /// Locked increment of the existing budget row; null when the row vanished /// (the caller restarts from the first-write branch). /// carries the pre-check's resolve so the common path pays no extra lookup. /// private static async Task TryIncrementAsync(IRedbService redb, string conversationId, long? knownId, AgentUsage delta) { AgentUsage? updated = null; await redb.Context.ExecuteAtomicAsync(async () => { long id; if (knownId is { } known) { id = known; } else { // Arrived from the lost-insert race: resolve the winner's row. var resolved = await LoadByKeyAsync(redb, conversationId).ConfigureAwait(false); if (resolved is null) return; // vanished — caller retries id = resolved.id; } await redb.LockForUpdateAsync(id).ConfigureAwait(false); // Re-read BY QUERY after the lock, not redb.LoadAsync. The core has since // stopped serving the zero-DB cache shortcut inside a transaction, but the query path // guarantees a fresh row read regardless of cache mode or core version — // and a stale pre-lock copy here would lose another node's increments, // the exact defect this lock exists to prevent. var row = await redb.Query() .WhereRedb(x => x.Id == id) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) return; // vanished after lock — caller retries row.Props.InputTokens += delta.InputTokens; row.Props.OutputTokens += delta.OutputTokens; row.Props.CostUsd += delta.CostUsd; row.Props.UpdatedAtUtc = DateTimeOffset.UtcNow; row.date_modify = row.Props.UpdatedAtUtc; await redb.SaveAsync(row).ConfigureAwait(false); updated = new AgentUsage((int)row.Props.InputTokens, (int)row.Props.OutputTokens, row.Props.CostUsd); }).ConfigureAwait(false); return updated; } /// public async ValueTask ResetAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default) { var redb = Resolve(exchange, out var owned); await using var scope = owned; var row = await LoadAsync(redb, conversationId).ConfigureAwait(false); if (row is not null) await redb.SoftDeleteAsync([row]).ConfigureAwait(false); } private static Task?> LoadAsync(IRedbService redb, string conversationId) => redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(conversationId)) .FirstOrDefaultAsync(); /// /// Row lookup for the increment path: by the readable value_string first /// (legacy rows carry only that), by the unique key second — the loser of a /// creation race resolves the winner through the key that collided. /// private static async Task?> LoadByKeyAsync(IRedbService redb, string conversationId) { var row = await LoadAsync(redb, conversationId).ConfigureAwait(false); if (row is not null) return row; var uniqueKey = RedbUniqueKey.Normalize(conversationId); return await redb.Query() .WhereRedb(x => x.ValueUnique == uniqueKey) .FirstOrDefaultAsync() .ConfigureAwait(false); } } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbEvalRunStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbEvalRunStore.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . One /// row per run; the run id lives in _objects.value_string (partial index /// on PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX)) and, normalized, in /// _objects._value_unique — concurrent saves of one run converge on a /// single row. Per-iteration metrics are kept as a typed /// nested array on the row — REDB persists them natively, no JSON roundtrip. /// /// The store does not own an instance — each call /// resolves one through IRouteContext.GetRedbService(name, exchange), /// which honours the per-exchange scope cache. The redb name is read from /// exchange.Properties[LlmKeys.RedbName] (set by the LLM endpoint URI), /// falling back to the constructor-supplied default name and then to the host's /// default unnamed instance. /// /// public sealed class RedbEvalRunStore : IEvalRunStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the store. Scheme is synced by the host's redb.InitializeAsync(). public RedbEvalRunStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// /// The service a call works on: the exchange's with one; without one (the eval runner saves without an exchange) /// a scope of its own, handed back in for the caller to dispose, so concurrent calls do not /// share the context's single instance and its one connection. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) name = s; if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = _context.CreateRedbScope(name); return owned.Service; } /// public async Task SaveAsync(EvalRunRecord record, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(record); ArgumentException.ThrowIfNullOrWhiteSpace(record.RunId); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var existing = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(record.RunId)) .FirstOrDefaultAsync() .ConfigureAwait(false); var props = ToProps(record); if (existing is null) { // The run id rides in _value_unique: concurrent saves of one run race to a // single row — the loser re-saves onto the winner (last-writer-wins upsert). var row = new RedbObject { value_string = record.RunId, ValueUnique = RedbUniqueKey.Normalize(record.RunId), Props = props }; try { await redb.SaveAsync(row).ConfigureAwait(false); } catch (RedbUniqueViolationException) { var winnerKey = row.ValueUnique; var winner = await redb.Query() .WhereRedb(o => o.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (deleted mid-race) winner.Props = props; winner.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(winner).ConfigureAwait(false); } } else { existing.Props = props; existing.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(existing).ConfigureAwait(false); } } /// public async Task SaveManyAsync(IEnumerable records, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(records); // One record per run id even within one call — the last entry wins. Two fresh // records sharing an id would otherwise self-collide on the unique index // inside a single bulk save (the pre-barrier code silently inserted both). var input = records .Where(r => r is not null && !string.IsNullOrWhiteSpace(r.RunId)) .GroupBy(r => r.RunId, StringComparer.Ordinal) .Select(g => g.Last()) .ToList(); if (input.Count == 0) return; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; await SaveManyCoreAsync(redb, input, retryOnRace: true, ct).ConfigureAwait(false); } private static async Task SaveManyCoreAsync( IRedbService redb, List input, bool retryOnRace, CancellationToken ct) { // ONE IN-clause lookup for all run ids (partial index on PG/SQLite; a scan // on MSSQL), then ONE bulk SaveAsync — insert/update streams are internal. var keys = input.Select(r => r.RunId).ToArray(); var existingByKey = (await redb.Query() .WhereRedb(o => keys.Contains(o.ValueString)) .ToListAsync() .ConfigureAwait(false)) .Where(o => o.value_string is not null) .ToDictionary(o => o.value_string!, StringComparer.Ordinal); if (!retryOnRace) { // Retry pass after a lost creation race: the winners hold the unique key — // resolve by it too, so every collided run id becomes an update. var normByKey = input.ToDictionary(r => r.RunId, r => RedbUniqueKey.Normalize(r.RunId), StringComparer.Ordinal); var norms = normByKey.Values.ToArray(); var keyByNorm = normByKey.ToDictionary(kv => kv.Value, kv => kv.Key, StringComparer.Ordinal); var byUnique = await redb.Query() .WhereRedb(o => norms.Contains(o.ValueUnique)) .ToListAsync() .ConfigureAwait(false); foreach (var row in byUnique) if (row.ValueUnique is { } u && keyByNorm.TryGetValue(u, out var k)) existingByKey.TryAdd(k, row); } var rowsToSave = new List(input.Count); var now = DateTimeOffset.UtcNow; foreach (var record in input) { ct.ThrowIfCancellationRequested(); var props = ToProps(record); if (existingByKey.TryGetValue(record.RunId, out var existing)) { // Hash-pre-check skips no-op upserts so SaveAsync’s change-tracking // doesn't re-read originals from DB for unchanged rows. On the retry // pass it is skipped: the first pass already mutated instances, and a // pre-check comparing a copy to itself would silently drop the update. var hashBefore = existing.ComputeHash(); existing.Props = props; if (retryOnRace && existing.ComputeHash() == hashBefore) continue; existing.date_modify = now; rowsToSave.Add(existing); } else { rowsToSave.Add(new RedbObject { value_string = record.RunId, ValueUnique = RedbUniqueKey.Normalize(record.RunId), Props = props }); } } if (rowsToSave.Count == 0) return; try { await redb.SaveAsync(rowsToSave).ConfigureAwait(false); } catch (RedbUniqueViolationException) when (retryOnRace) { // A concurrent writer claimed one of the fresh run ids after our lookup and // the batch rolled back whole. The winners are visible now: rebuild from a // fresh lookup and retry once — a second violation is a real error. await SaveManyCoreAsync(redb, input, retryOnRace: false, ct).ConfigureAwait(false); } } private static EvalRunProps ToProps(EvalRunRecord record) => new() { RunId = record.RunId, Scenario = record.Scenario, AgentFingerprint = record.AgentFingerprint, Score = record.Score, InputTokens = record.TotalUsage.InputTokens, OutputTokens = record.TotalUsage.OutputTokens, CostUsd = record.TotalUsage.CostUsd, CreatedAtUtc = new DateTimeOffset(DateTime.SpecifyKind(record.CreatedAtUtc, DateTimeKind.Utc)), Iterations = record.Iterations.Select(i => new EvalIterationMetric { Iteration = i.Iteration, InputTokens = i.InputTokens, OutputTokens = i.OutputTokens, DurationMs = i.DurationMs, Score = i.Score, Notes = i.Notes }).ToArray(), Dimensions = record.Dimensions is null ? null : new Dictionary(record.Dimensions), Fixtures = record.Fixtures is null ? null : new Dictionary(record.Fixtures) }; /// public async Task GetAsync(string runId, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(runId); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var row = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(runId)) .FirstOrDefaultAsync() .ConfigureAwait(false); return row is null ? null : Materialize(row); } /// public async Task> ListAsync(string? scenario = null, int take = 50, IExchange? exchange = null, CancellationToken ct = default) { var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var query = scenario is null ? redb.Query() : redb.Query().Where(p => p.Scenario == scenario); // Sort on the indexed base column (_objects.date_create) — avoids // pulling props just to order leaderboard rows. var rows = await query .OrderByDescendingRedb(o => o.DateCreate) .Take(Math.Max(1, take)) .ToListAsync() .ConfigureAwait(false); return rows.Select(Materialize).ToArray(); } private static EvalRunRecord Materialize(RedbObject row) => new() { RunId = row.Props.RunId, Scenario = row.Props.Scenario, AgentFingerprint = row.Props.AgentFingerprint, Score = row.Props.Score, TotalUsage = new AgentUsage( (int)row.Props.InputTokens, (int)row.Props.OutputTokens, row.Props.CostUsd), Iterations = row.Props.Iterations is null or { Length: 0 } ? [] : row.Props.Iterations.Select(i => new EvalIterationRecord { Iteration = i.Iteration, InputTokens = i.InputTokens, OutputTokens = i.OutputTokens, DurationMs = i.DurationMs, Score = i.Score, Notes = i.Notes }).ToArray(), Dimensions = row.Props.Dimensions, Fixtures = row.Props.Fixtures, CreatedAtUtc = row.Props.CreatedAtUtc.UtcDateTime }; } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbKnowledgeStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbKnowledgeStore.cs ---- using System.Runtime.InteropServices; using System.Text.Json; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . One row per chunk; every chunk /// field is stored on the indexed base columns and /// the scheme is intentionally /// property-less — chunks read / write a single _objects row /// with zero _props rows. Column layout: /// /// value_string — stable chunk id (business key; partial index on /// PostgreSQL/SQLite, no index on MSSQL — NVARCHAR(MAX)). New rows also /// carry it, normalized, in _value_unique: the per-scheme unique /// index keeps concurrent upserts of one id on a single row. /// name — collection / namespace. /// note — JSON envelope {"text":"...","meta":"..."}. /// value_bytes — embedding, written as the raw byte view of /// the float[] via . /// value_long — embedding dimensionality (sanity check). /// /// /// Search strategy: the MVP loads candidate chunks (filtered by /// collection) and computes cosine similarity in process. Acceptable up to a /// few thousand chunks. For production scale plug in a pgvector / Qdrant /// adapter that overrides only . /// /// /// The store does not own an instance — each call /// resolves one through IRouteContext.GetRedbService(name, exchange), /// which honours the per-exchange scope cache. The redb name is read from /// exchange.Properties[LlmKeys.RedbName] (set by the LLM endpoint URI), /// falling back to the constructor-supplied default name and then to the host's /// default unnamed instance. /// /// public sealed class RedbKnowledgeStore : IKnowledgeStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the store. Scheme is synced by the host's redb.InitializeAsync(). public RedbKnowledgeStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// /// The service a call works on: the exchange's with one; without one a scope of its own, handed back in /// for the caller to dispose, so concurrent calls do not share the context's single /// instance and its one connection. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) name = s; if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = _context.CreateRedbScope(name); return owned.Service; } /// public async Task UpsertAsync(KnowledgeChunk chunk, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(chunk); ArgumentException.ThrowIfNullOrWhiteSpace(chunk.Id); ArgumentException.ThrowIfNullOrWhiteSpace(chunk.Text); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var existing = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(chunk.Id)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) { Populate(existing, chunk, out var row); await redb.SaveAsync(row).ConfigureAwait(false); return; } // The chunk id rides in _value_unique: two concurrent ingestors of one id race // to a single row — before, both inserted and searches returned duplicate hits. Populate(new RedbObject(), chunk, out var fresh); fresh.ValueUnique = RedbUniqueKey.Normalize(chunk.Id); try { await redb.SaveAsync(fresh).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race — an upsert is last-writer-wins, so write this // chunk onto the winner's row, resolved by the key that collided. var winnerKey = fresh.ValueUnique; var winner = await redb.Query() .WhereRedb(o => o.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (deleted mid-race) Populate(winner, chunk, out var row); await redb.SaveAsync(row).ConfigureAwait(false); } } /// public async Task UpsertManyAsync(IEnumerable chunks, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(chunks); // One chunk per id even within one call — the last entry wins (re-chunking // pipelines do emit an id twice). Two fresh rows sharing an id would // otherwise self-collide on the unique index inside a single bulk save // (the pre-barrier code silently inserted both). var input = chunks .Where(c => c is not null && !string.IsNullOrWhiteSpace(c.Id) && !string.IsNullOrWhiteSpace(c.Text)) .GroupBy(c => c.Id, StringComparer.Ordinal) .Select(g => g.Last()) .ToList(); if (input.Count == 0) return; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; await UpsertManyCoreAsync(redb, input, retryOnRace: true, ct).ConfigureAwait(false); } private static async Task UpsertManyCoreAsync( IRedbService redb, List input, bool retryOnRace, CancellationToken ct) { // ONE IN-clause lookup for all keys (partial index on PG/SQLite; a scan on // MSSQL), then ONE bulk SaveAsync — insert/update streams are internal. var keys = input.Select(c => c.Id).ToArray(); var existingByKey = (await redb.Query() .WhereRedb(o => keys.Contains(o.ValueString)) .ToListAsync() .ConfigureAwait(false)) .Where(o => o.value_string is not null) .ToDictionary(o => o.value_string!, StringComparer.Ordinal); if (!retryOnRace) { // Retry pass after a lost creation race: the winners hold the unique key — // resolve by it too, so every collided chunk becomes an update. var normByKey = input.ToDictionary(c => c.Id, c => RedbUniqueKey.Normalize(c.Id), StringComparer.Ordinal); var norms = normByKey.Values.ToArray(); var keyByNorm = normByKey.ToDictionary(kv => kv.Value, kv => kv.Key, StringComparer.Ordinal); var byUnique = await redb.Query() .WhereRedb(o => norms.Contains(o.ValueUnique)) .ToListAsync() .ConfigureAwait(false); foreach (var row in byUnique) if (row.ValueUnique is { } u && keyByNorm.TryGetValue(u, out var k)) existingByKey.TryAdd(k, row); } var rowsToSave = new List(input.Count); foreach (var chunk in input) { ct.ThrowIfCancellationRequested(); if (existingByKey.TryGetValue(chunk.Id, out var existing)) { // No Props-hash pre-check here: KnowledgeChunkProps is a // property-less marker (text/id/embedding live on the base // _objects columns, not Props), so ComputeHash() is always empty // and would treat every re-upsert as "unchanged" — silently // dropping real text/embedding updates. Always save the row; // SaveAsync's own change-tracking still diffs the base columns. Populate(existing, chunk, out var same); rowsToSave.Add(same); } else { Populate(new RedbObject(), chunk, out var fresh); fresh.ValueUnique = RedbUniqueKey.Normalize(chunk.Id); rowsToSave.Add(fresh); } } if (rowsToSave.Count == 0) return; try { await redb.SaveAsync(rowsToSave).ConfigureAwait(false); } catch (RedbUniqueViolationException) when (retryOnRace) { // A concurrent ingestor claimed one of the fresh chunk ids after our lookup // and the batch rolled back whole. The winners are visible now: rebuild from // a fresh lookup (collided ids become updates) and retry once — a second // violation is a real error. await UpsertManyCoreAsync(redb, input, retryOnRace: false, ct).ConfigureAwait(false); } } /// public async Task DeleteAsync(string chunkId, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(chunkId); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var row = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(chunkId)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is not null) await redb.SoftDeleteAsync([row]).ConfigureAwait(false); } /// public async Task> SearchAsync( ReadOnlyMemory queryEmbedding, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) { if (queryEmbedding.Length == 0) return []; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; // Pre-filter by collection on the indexed _objects.name column at the // SQL layer; the cosine pass is in-process. var rows = collection is null ? await redb.Query().ToListAsync().ConfigureAwait(false) : await redb.Query() .WhereRedb(o => o.Name == collection) .ToListAsync() .ConfigureAwait(false); if (rows.Count == 0) return []; var ranked = new List(rows.Count); var query = queryEmbedding.Span; foreach (var row in rows) { var embedding = DecodeEmbedding(row.value_bytes); var score = CosineSimilarity(query, embedding); ranked.Add(new KnowledgeSearchResult(MaterializeChunk(row, embedding), score)); } return ranked .OrderByDescending(r => r.Score) .Take(Math.Max(1, topK)) .ToArray(); } /// public async Task> SearchTextAsync( string query, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(query)) return []; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; // Push the substring filter to SQL (LIKE) on the indexed _objects.note // column — which holds the {text,meta} envelope. Only matching rows come // back; we never load the whole table. Collection stays an indexed // _objects.name equality in the same WHERE. // Case-insensitive substring → the parser maps Contains(.., OrdinalIgnoreCase) // to a server-side ILIKE (ComparisonOperator.ContainsIgnoreCase), so "Mask" // matches "mask"/"MASK" in SQL, not just in the in-process re-score below. var matches = collection is null ? await redb.Query() .WhereRedb(o => o.Note != null && o.Note.Contains(query, StringComparison.OrdinalIgnoreCase)) .ToListAsync() .ConfigureAwait(false) : await redb.Query() .WhereRedb(o => o.Note != null && o.Note.Contains(query, StringComparison.OrdinalIgnoreCase) && o.Name == collection) .ToListAsync() .ConfigureAwait(false); if (matches.Count == 0) return []; // Re-score the (already small) matched set against the DECODED text, not // the raw envelope: this ranks by real occurrence count and drops rows // where the substring only hit the JSON structure / meta, never the text. var ranked = new List(matches.Count); foreach (var row in matches) { var embedding = DecodeEmbedding(row.value_bytes); var chunk = MaterializeChunk(row, embedding); var score = KnowledgeTextMatch.CountOccurrences(chunk.Text, query); if (score == 0) continue; ranked.Add(new KnowledgeSearchResult(chunk, score)); } return ranked .OrderByDescending(r => r.Score) .Take(Math.Max(1, topK)) .ToArray(); } private static void Populate(RedbObject row, KnowledgeChunk chunk, out RedbObject result) { var embedding = chunk.Embedding.Span; // float[] -> raw bytes via MemoryMarshal — zero-copy reinterpret + ToArray() // produces the exact little-endian byte sequence we can decode later // with MemoryMarshal.Cast. var bytes = MemoryMarshal.AsBytes(embedding).ToArray(); var envelope = new ChunkEnvelope(chunk.Text, chunk.MetadataJson); row.value_string = chunk.Id; row.name = chunk.Collection ?? string.Empty; row.note = JsonSerializer.Serialize(envelope, EnvelopeJsonOptions); row.value_bytes = bytes; row.value_long = embedding.Length; row.date_modify = new DateTimeOffset(DateTime.SpecifyKind(chunk.UpdatedAtUtc, DateTimeKind.Utc)); result = row; } private static KnowledgeChunk MaterializeChunk(RedbObject row, float[] embedding) { var envelope = TryParseEnvelope(row.note); return new KnowledgeChunk { Id = row.value_string ?? string.Empty, Collection = string.IsNullOrEmpty(row.name) ? null : row.name, Text = envelope.Text, Embedding = embedding, MetadataJson = envelope.Meta, UpdatedAtUtc = row.date_modify.UtcDateTime }; } private static float[] DecodeEmbedding(byte[]? bytes) { if (bytes is null || bytes.Length == 0) return []; return MemoryMarshal.Cast(bytes).ToArray(); } private static ChunkEnvelope TryParseEnvelope(string? json) { if (string.IsNullOrWhiteSpace(json)) return new ChunkEnvelope(string.Empty, null); try { return JsonSerializer.Deserialize(json, EnvelopeJsonOptions) ?? new ChunkEnvelope(string.Empty, null); } catch { return new ChunkEnvelope(json, null); } } private static double CosineSimilarity(ReadOnlySpan a, ReadOnlySpan b) { var len = Math.Min(a.Length, b.Length); if (len == 0) return 0d; double dot = 0, na = 0, nb = 0; for (var i = 0; i < len; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; } var denom = Math.Sqrt(na) * Math.Sqrt(nb); return denom <= 0 ? 0d : dot / denom; } private static readonly JsonSerializerOptions EnvelopeJsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, // Store the text as-is (UTF-8), NOT \uXXXX-escaped. The default encoder // escapes every non-ASCII char, which would bury Cyrillic / CJK text as // "\u041C\u0430..." in the note column — making the keyword LIKE in // SearchTextAsync unable to match a raw non-ASCII query. Relaxed escaping // is safe for DB storage (it only skips HTML-sensitive escaping). Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private sealed record ChunkEnvelope(string Text, string? Meta); } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbPromptTemplateRegistry.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbPromptTemplateRegistry.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . One /// row per (name, version); the composite /// business key "{name}@{version}" lives in _objects.value_string /// (partial index on PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX)) and, /// normalized, in _objects._value_unique — a version registers exactly /// once, concurrent registrations of one version resolve first-wins. /// /// "Latest" lookup is server-side: filter by the value_string prefix /// "{name}@" and pick the most recently created row. /// /// /// The registry does not own an instance — each /// call resolves one through IRouteContext.GetRedbService(name, exchange), /// which honours the per-exchange scope cache. The redb name is read from /// exchange.Properties[LlmKeys.RedbName] (set by the LLM endpoint URI), /// falling back to the constructor-supplied default name and then to the host's /// default unnamed instance. /// /// public sealed class RedbPromptTemplateRegistry : IPromptTemplateRegistry { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the registry. Scheme is synced by the host's redb.InitializeAsync(). public RedbPromptTemplateRegistry(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// /// The service a call works on: the exchange's with one; without one a scope of its own, handed back in /// for the caller to dispose, so concurrent calls do not share the context's single /// instance and its one connection. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) name = s; if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = _context.CreateRedbScope(name); return owned.Service; } /// public async Task GetAsync(string name, string? version = null, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(name); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; if (version is not null) { var key = BuildKey(name, version); var row = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(key)) .FirstOrDefaultAsync() .ConfigureAwait(false); return row is null ? null : Materialize(row); } // Latest: server-side ORDER BY _objects.date_create DESC LIMIT 1. // Sorting on the indexed base column avoids touching props for ordering. var latest = await redb.Query() .Where(p => p.Name == name) .OrderByDescendingRedb(o => o.DateCreate) .FirstOrDefaultAsync() .ConfigureAwait(false); return latest is null ? null : Materialize(latest); } /// public async Task SetAsync(PromptTemplate template, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(template); ArgumentException.ThrowIfNullOrWhiteSpace(template.Name); ArgumentException.ThrowIfNullOrWhiteSpace(template.Version); ArgumentException.ThrowIfNullOrWhiteSpace(template.Body); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var key = BuildKey(template.Name, template.Version); var existing = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(key)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is null) { // The (name, version) key rides in _value_unique: two concurrent // registrations of one version race to a single row. First wins — the // loser's body is dropped, because a version is immutable provenance // (MessageProps pins "which exact prompt drove this answer" to it) and // silently swapping the winner's body would corrupt that audit trail. var row = new RedbObject { value_string = key, ValueUnique = RedbUniqueKey.Normalize(key), Props = new PromptTemplateProps { Name = template.Name, Version = template.Version, Body = template.Body, Description = template.Description, CreatedAtUtc = new DateTimeOffset(DateTime.SpecifyKind(template.CreatedAtUtc, DateTimeKind.Utc)) } }; try { await redb.SaveAsync(row).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // The version is already registered — first wins. } } else if (string.Equals(existing.value_string, key, StringComparison.Ordinal)) { // The upsert contract: re-setting the version you own updates it in place. existing.Props.Body = template.Body; existing.Props.Description = template.Description; // The framework does not auto-stamp date_modify; bump it ourselves // so list/latest queries see the real update time. existing.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(existing).ConfigureAwait(false); } else { // The unique key is owned by a row whose raw string diverged — a race winner the // string lookup used to miss (it then hit the collision path below and dropped the // body). Same doctrine on the new access path: first wins, the incoming body is // dropped, because a version is immutable provenance. } } /// public async Task> ListAsync(IExchange? exchange = null, CancellationToken ct = default) { var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var rows = await redb.Query() .OrderByDescendingRedb(o => o.DateCreate) .ToListAsync() .ConfigureAwait(false); return rows.Select(Materialize).ToArray(); } private static PromptTemplate Materialize(RedbObject row) => new() { Name = row.Props.Name, Version = row.Props.Version, Body = row.Props.Body, Description = row.Props.Description, CreatedAtUtc = row.Props.CreatedAtUtc.UtcDateTime }; private static string BuildKey(string name, string version) => $"{name}@{version}"; } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbToolIdempotencyStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbToolIdempotencyStore.cs ---- using System.Collections.Concurrent; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Repositories; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . Reservations are tracked by a /// (processor name llm-tool-idempotency) over the same redb the tool /// outputs go to: the instance the endpoint's ?redb= names, else the constructor's default name, else the /// context's default redb. One rule for every case, so a reservation never sits in another database than the output it /// guards. The scope of that redb is opened per operation, on first use. Idempotent tool outputs /// are persisted in a row whose composite /// key "llm-tool:{conv}:{toolUseId}" lives in _objects.value_string /// (partial index on PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX)) and, /// normalized, in _objects._value_unique — the per-scheme unique index /// keeps a raced completion on a single row. The dedicated scheme keeps /// idempotency rows physically separate from /// content-hash entries — lookups touch a single scheme partition. /// On a duplicate, the previously-saved output is returned and the model /// never sees a second side effect. /// /// The store does not own an instance — each call /// resolves one through IRouteContext.GetRedbService(name, exchange), /// which honours the per-exchange scope cache. The redb name is read from /// exchange.Properties[LlmKeys.RedbName] (set by the LLM endpoint URI), /// falling back to the constructor-supplied default name and then to the host's /// default unnamed instance. /// /// public sealed class RedbToolIdempotencyStore : IToolIdempotencyStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; // Keyed by the redb name; the empty key is the context's default redb. private readonly ConcurrentDictionary _reservations = new(StringComparer.Ordinal); /// The processor name of the reservations. private const string ReservationProcessorName = "llm-tool-idempotency"; /// /// Creates the store over 's redb: the instance names /// (an endpoint's ?redb= overrides it per exchange), else the context's default redb. Reservations and cached /// outputs are kept there together. /// public RedbToolIdempotencyStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } private string? RedbNameOf(IExchange? exchange) { if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) return s; return string.IsNullOrEmpty(_defaultRedbName) ? null : _defaultRedbName; } /// /// The service the output row is read and written on. With an exchange it is the exchange's service. Without one /// the call opens a scope of its own and hands it back in for the caller to dispose, as /// the reservation does: the context's single instance would put concurrent calls on one connection. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = RedbNameOf(exchange); if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = OpenScope(name ?? string.Empty); return owned.Service; } private IIdempotentRepository ReservationsOf(IExchange? exchange) => _reservations.GetOrAdd(RedbNameOf(exchange) ?? string.Empty, name => new RedbIdempotentRepository( () => OpenScope(name), new RedbIdempotentOptions { ProcessorName = ReservationProcessorName })); private RedbScope OpenScope(string name) { try { return _context.CreateRedbScope(name.Length == 0 ? null : name); } catch (InvalidOperationException ex) { var where = name.Length == 0 ? "the route context's default redb" : $"the redb instance '{name}'"; throw new InvalidOperationException( $"AddRedbLlmStorage: the tool idempotency reservation is kept in {where}, but the route context cannot " + $"open a redb scope for it: {ex.Message} Register redb in the context's container (services.AddRedb... " + "or AddRedbPro), or name an instance the context has (AddRedbLlmStorage(\"name\") or ?redb= on the endpoint).", ex); } } /// public async Task TryReserveAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = BuildKey(conversationId, toolUseId); var fresh = await ReservationsOf(exchange).Add(key, ct).ConfigureAwait(false); if (fresh) return ToolIdempotencyReservation.NewReservation; var redb = Resolve(exchange, out var owned); await using var scope = owned; var cached = await LoadCachedOutputAsync(redb, key).ConfigureAwait(false); return ToolIdempotencyReservation.Hit(cached ?? "{}"); } /// public async Task CompleteAsync(string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default) { var key = BuildKey(conversationId, toolUseId); var redb = Resolve(exchange, out var owned); await using var scope = owned; var row = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(key)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) { // The composite key rides in _value_unique: the reservation protocol makes // a second completer rare (release + re-reserve, crash recovery), but when // one appears the unique index keeps the output on a single row. row = new RedbObject { value_string = key, ValueUnique = RedbUniqueKey.Normalize(key), Props = new ToolIdempotencyProps { ToolName = null, OutputJson = outputJson, CreatedAtUtc = DateTimeOffset.UtcNow } }; try { await redb.SaveAsync(row).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race — write this completion onto the winner's row. var winnerKey = row.ValueUnique; var winner = await redb.Query() .WhereRedb(x => x.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (released mid-race) winner.Props.OutputJson = outputJson; winner.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(winner).ConfigureAwait(false); } } else { row.Props.OutputJson = outputJson; row.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(row).ConfigureAwait(false); } await ReservationsOf(exchange).Confirm(key, ct).ConfigureAwait(false); } /// public async Task ReleaseAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = BuildKey(conversationId, toolUseId); await ReservationsOf(exchange).Remove(key, ct).ConfigureAwait(false); var redb = Resolve(exchange, out var owned); await using var scope = owned; var row = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(key)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is not null) await redb.SoftDeleteAsync([row]).ConfigureAwait(false); } private static async Task LoadCachedOutputAsync(IRedbService redb, string key) { var row = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(key)) .FirstOrDefaultAsync() .ConfigureAwait(false); return row?.Props.OutputJson; } private static string BuildKey(string conversationId, string toolUseId) => $"llm-tool:{conversationId}:{toolUseId}"; } Path: redb-route/redb.Route.Llm/Storage/Redb/RedbToolResultCache.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbToolResultCache.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . Cache entries are keyed on the /// caller-supplied content hash stored in _objects.value_string (partial /// index on PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX), lookups there /// scan the scheme's rows). The key also rides in _objects._value_unique, /// whose per-scheme unique index makes concurrent writers of one key converge /// on a single row. TTL is honoured lazily — entries past expiry are dropped on /// read. /// /// Distinct from : idempotency answers "have I already run /// this tool call (by tool_use_id)?", while this store answers "do I already have an output for /// this exact input?". The engine consults this store for ToolCachingPolicy.Persist tools, /// after approval and before the idempotency reservation. /// /// /// The store does not own an instance — each call /// resolves one through IRouteContext.GetRedbService(name, exchange), /// which honours the per-exchange scope cache. The redb name is read from /// exchange.Properties[LlmKeys.RedbName] (set by the LLM endpoint URI), /// falling back to the constructor-supplied default name and then to the host's /// default unnamed instance. /// /// public sealed class RedbToolResultCache : IToolCacheStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the store. Scheme is synced by the host's redb.InitializeAsync(). public RedbToolResultCache(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// /// The service a call works on: the exchange's with one; without one a scope of its own, handed back in /// for the caller to dispose, so concurrent calls do not share the context's single /// instance and its one connection. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) name = s; if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = _context.CreateRedbScope(name); return owned.Service; } /// public async ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(cacheKey); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var row = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(cacheKey)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) return null; if (row.Props.ExpiresAtUtc is { } exp && exp <= DateTimeOffset.UtcNow) { // Lazy eviction — soft-delete and report a miss. Whoever asked sees a miss, and the // two cases (cold key, expired entry) are indistinguishable through this interface. await redb.SoftDeleteAsync([row]).ConfigureAwait(false); return null; } return row.Props.OutputJson; } /// public async ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(cacheKey); ArgumentNullException.ThrowIfNull(outputJson); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var existing = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(cacheKey)) .FirstOrDefaultAsync() .ConfigureAwait(false); var now = DateTimeOffset.UtcNow; var expiresAt = ttl is { } span && span > TimeSpan.Zero ? now.Add(span) : (DateTimeOffset?)null; if (existing is null) { // The cache key rides in _value_unique: of two concurrent SetAsync for one // key the per-scheme unique index lets exactly one insert through — before, // both inserted and readers picked an arbitrary (possibly stale) copy. var row = new RedbObject { value_string = cacheKey, ValueUnique = RedbUniqueKey.Normalize(cacheKey), Props = new ToolCacheProps { OutputJson = outputJson, CreatedAtUtc = now, ExpiresAtUtc = expiresAt } }; try { await redb.SaveAsync(row).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race — a cache Set is last-writer-wins, so write // onto the winner's row, resolved by the key that collided. var winnerKey = row.ValueUnique; var winner = await redb.Query() .WhereRedb(o => o.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (evicted mid-race) winner.Props.OutputJson = outputJson; winner.Props.CreatedAtUtc = now; winner.Props.ExpiresAtUtc = expiresAt; winner.date_modify = now; await redb.SaveAsync(winner).ConfigureAwait(false); } } else { // Hash-pre-check: idempotent SetAsync (same json/ttl/key) becomes // a no-op instead of a round-trip through SaveAsync change-tracking. var hashBefore = existing.ComputeHash(); existing.Props.OutputJson = outputJson; existing.Props.CreatedAtUtc = now; existing.Props.ExpiresAtUtc = expiresAt; if (existing.ComputeHash() == hashBefore) return; existing.date_modify = now; await redb.SaveAsync(existing).ConfigureAwait(false); } } /// public async ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default) { var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; // Project only ids — avoids materialising props blobs server-side just // to feed them into the bulk SoftDeleteAsync(IEnumerable) overload. var ids = await redb.Query() .Select(r => r.id) .ToListAsync() .ConfigureAwait(false); if (ids.Count == 0) return; await redb.SoftDeleteAsync(ids).ConfigureAwait(false); } } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/ApprovalProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/ApprovalProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// Persisted decision from an IApprovalGate. The combination of /// (, , , /// ) at the top level allows reviewer queries /// ("show every denial last week for tool X") without scanning value rows. /// The approval id itself lives on the value_string column of /// _objects (partial index on PostgreSQL/SQLite; no index on MSSQL) and, /// normalized, in value_unique (per-scheme unique — one decision per id), /// not in props. /// [RedbScheme("LLM Approval")] public class ApprovalProps { /// Owning conversation (null for ad-hoc approvals). public string? ConversationId { get; set; } /// Tool that was gated. public string ToolName { get; set; } = string.Empty; /// Tool-use id from the model response. public string ToolUseId { get; set; } = string.Empty; /// True when the gate let the call proceed. public bool Approved { get; set; } /// Reason text supplied by the approver. public string? Reason { get; set; } /// Identifier of the approver (user / service) — null when auto-approved. public string? ApprovedBy { get; set; } /// When the decision was recorded. public DateTimeOffset DecidedAtUtc { get; set; } /// JSON-serialized tool input as it would be dispatched. public string InputJson { get; set; } = "{}"; } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/ConversationProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/ConversationProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// Root record of a single LLM conversation. Top-level scalar fields are /// hoisted so that WhereRedb queries (by tenant, status, last activity) /// hit the _objects table directly without scanning _values. /// Message nodes are stored as child via /// TreeRedbObject; this record holds only conversation-level counters /// and metadata. /// [RedbScheme("LLM Conversation")] public class ConversationProps { /// Tenant or organization owning the conversation. public string TenantId { get; set; } = string.Empty; /// Human-readable title; null when not yet set by the agent. public string? Title { get; set; } /// Lifecycle state: "active" / "closed" / "archived". public string Status { get; set; } = "active"; /// When the conversation was created. public DateTimeOffset StartedAtUtc { get; set; } /// When the most recent message was appended. public DateTimeOffset LastActivityAtUtc { get; set; } /// Cumulative input tokens across every iteration of every run. public long TotalInputTokens { get; set; } /// Cumulative output tokens across every iteration of every run. public long TotalOutputTokens { get; set; } /// Cumulative cost in USD across the conversation. public decimal TotalCostUsd { get; set; } /// Number of agent runs (resumes) that have touched the conversation. public int RunCount { get; set; } } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/CostBudgetProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/CostBudgetProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// Running cost / token totals scoped to a conversation. One row per /// conversation per billing period — is the /// boundary that lets a daily / monthly reset roll the counters. The /// conversation id lives on the value_string column of _objects /// (partial index on PostgreSQL/SQLite; no index on MSSQL) and, normalized, in /// value_unique (per-scheme unique — one budget row per conversation), /// not in props. /// [RedbScheme("LLM Cost Budget")] public class CostBudgetProps { /// Optional billing-period anchor (e.g. day or month start, UTC). public DateTimeOffset? PeriodStartUtc { get; set; } /// Aggregated input tokens. public long InputTokens { get; set; } /// Aggregated output tokens. public long OutputTokens { get; set; } /// Aggregated cost in USD. public decimal CostUsd { get; set; } /// When the row was last updated. public DateTimeOffset UpdatedAtUtc { get; set; } } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/EvalRunProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/EvalRunProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// A persisted eval-harness run. Scenario / fingerprint / score are top-level /// so leaderboard queries do not touch _values. Per-iteration metrics /// and scoring dimensions are stored as typed nested collections — REDB /// persists them natively, no JSON marshalling. /// [RedbScheme("LLM Eval Run")] public class EvalRunProps { /// Identifier assigned by the eval runner — business key. public string RunId { get; set; } = string.Empty; /// Scenario name (e.g. "summarize-pr", "sql-rag"). public string Scenario { get; set; } = string.Empty; /// Agent / prompt / model fingerprint that produced the run. public string AgentFingerprint { get; set; } = string.Empty; /// Aggregate score in [0.0, 1.0]; null when the harness did not score the run. public double? Score { get; set; } /// Aggregated input tokens. public long InputTokens { get; set; } /// Aggregated output tokens. public long OutputTokens { get; set; } /// Total cost in USD. public decimal CostUsd { get; set; } /// When the run finished. public DateTimeOffset CreatedAtUtc { get; set; } /// /// Per-iteration metrics — one entry per agent loop iteration. Typed nested /// array; queryable by iteration number when needed. /// public EvalIterationMetric[] Iterations { get; set; } = []; /// /// Custom scoring dimensions (e.g. "accuracy" = 0.92, /// "latency_p95_ms" = 870). Native dictionary — no JSON. /// public Dictionary? Dimensions { get; set; } /// /// Fixture identifiers / version hashes consumed by the run — preserves /// reproducibility provenance without leaking fixture payloads into the row. /// public Dictionary? Fixtures { get; set; } } /// Per-iteration metric inside an run. public class EvalIterationMetric { /// 1-based iteration index within the run. public int Iteration { get; set; } /// Input tokens consumed by this iteration. public int InputTokens { get; set; } /// Output tokens produced by this iteration. public int OutputTokens { get; set; } /// Wall-clock duration of the iteration in milliseconds. public int DurationMs { get; set; } /// Per-iteration score in [0.0, 1.0]; null when the harness did not score this iteration. public double? Score { get; set; } /// Optional free-form note (judge rationale, failure tag, etc.). public string? Notes { get; set; } } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/KnowledgeChunkProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/KnowledgeChunkProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// Marker scheme for embedding-backed knowledge chunks. Intentionally /// property-less: every chunk field lives on the indexed /// base columns, which /// means a chunk row reads / writes one table (_objects) with zero /// _props rows. /// /// value_string — stable chunk id (business key; partial index on /// PostgreSQL/SQLite, no index on MSSQL). Rides normalized in /// value_unique on new rows (per-scheme unique race barrier). /// name — collection / namespace partition. /// note — JSON envelope {"text":"...","meta":"..."} /// (chunk text plus optional metadata). Keyword search /// (SearchTextAsync) pushes a LIKE over this column. /// value_bytes — embedding, encoded as a contiguous /// float[] byte buffer. /// value_long — embedding dimensionality (sanity check). /// date_modify — last-upsert timestamp. /// /// For production-scale ANN search (millions of chunks) plug in a Qdrant / /// pgvector backed implementation that only overrides SearchAsync. /// [RedbScheme("LLM Knowledge Chunk")] public class KnowledgeChunkProps { } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/LlmBatchProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/LlmBatchProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// A submitted async-batch job tracked by . /// Carries the provider-issued batch identifier on /// _objects.value_string for direct lookup (partial index on /// PostgreSQL/SQLite; no index on MSSQL) and, normalized, in /// value_unique (per-scheme unique — one row per batch id), plus an /// optional conversation id on _objects.value_long when the caller /// pre-bound the batch to a conversation. Status transitions ("submitted", "running", "completed", /// "failed") are written by /// and friends — the framework does not poll on its own; status is updated /// either when the corresponding webhook arrives or when the host explicitly /// calls UpdateStatusAsync. /// [RedbScheme("LLM Batch Job")] public class LlmBatchProps { /// Provider identifier — "anthropic", "openai", custom values for vLLM/Ollama batch endpoints. public string ProviderId { get; set; } = string.Empty; /// Model id at submit-time. Useful when a model version rolls forward between submit and callback. public string ModelId { get; set; } = string.Empty; /// Conversation correlation id — empty when the batch is conversation-less. public string ConversationId { get; set; } = string.Empty; /// Lifecycle: "submitted" → "running" → "completed" / "failed" / "cancelled". public string Status { get; set; } = "submitted"; /// When the host submitted the batch. public DateTimeOffset SubmittedAtUtc { get; set; } /// When the callback fired (or the host marked completion). public DateTimeOffset? CompletedAtUtc { get; set; } /// Optional URL where the host can fetch results — null when the provider returns them inline in the callback. public string? ResultUrl { get; set; } /// Free-form metadata supplied by the caller at submit time (caller-controlled JSON). public string? MetadataJson { get; set; } /// Last error message recorded against the batch — null while healthy. public string? ErrorMessage { get; set; } /// /// When true the callback processor appends the assistant turn from /// the callback body to the conversation store on completion. See /// . /// public bool AppendToConversation { get; set; } } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/MessageProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/MessageProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// A single message node within a conversation tree. Persisted as a /// TreeRedbObject<MessageProps> with the conversation root (or /// another ) as parent — branching is native: any /// regenerate / parallel-tool / what-if path attaches as another child of the /// same parent. /// /// Identifier lives in value_string (per-message GUID; partial index on /// PostgreSQL/SQLite, no index on MSSQL) and the conversation FK lives in /// value_long (pointing at the root's _objects.id; indexed on /// every provider) — both on the _objects row, so transcript queries /// never scan _values. Parent is tracked natively via the tree's /// parent_id; no duplicate fields here. /// /// Content blocks (text / tool-use / tool-result) are stored as a typed /// nested array () — REDB persists them natively, no /// JSON-string marshalling. /// [RedbScheme("LLM Conversation Message")] public class MessageProps { /// Role: "user" / "assistant" / "system" / "tool". public string Role { get; set; } = string.Empty; /// Agent iteration that produced the message (0 = user prompt). public int Iteration { get; set; } /// When the message was appended. public DateTimeOffset CreatedAtUtc { get; set; } /// Provider id ("openai" / "anthropic" / ...); null for non-provider messages. public string? ProviderId { get; set; } /// Model id as resolved at call time. public string? ModelId { get; set; } /// Stop reason string for assistant messages; null otherwise. public string? StopReason { get; set; } /// Tool-use id when this message is a tool result; null otherwise. public string? ToolUseId { get; set; } /// Input tokens attributed to this turn (0 for non-assistant messages). public int InputTokens { get; set; } /// Output tokens attributed to this turn. public int OutputTokens { get; set; } /// /// Prompt tokens written to the provider's cache by this turn, billed at a premium over normal input /// (LlmUsage.CacheCreationInputTokens). Zero where the provider does not bill cache creation, as DeepSeek. /// public int CacheCreationInputTokens { get; set; } /// /// Prompt tokens this turn read back from the provider's cache, billed at a fraction of normal input /// (LlmUsage.CacheReadInputTokens). is the remainder billed at full price, so the /// turn's prompt is the sum of the three. /// public int CacheReadInputTokens { get; set; } /// /// Effective sampling temperature passed to the provider for the call that /// produced this assistant message; null on user / tool-result rows. /// public double? Temperature { get; set; } /// Effective max-output-tokens cap; null on non-assistant rows. public int? MaxTokens { get; set; } /// Effective top-p value; null on non-assistant rows. public double? TopP { get; set; } /// /// Prompt-template name resolved at call time. Pairs with /// and a row in PromptTemplateProps /// to lock down "which exact prompt drove this answer". /// public string? PromptTemplateName { get; set; } /// Prompt-template version (paired with ). public string? PromptTemplateVersion { get; set; } /// /// Stable hash of the tool-capabilities set exposed to the model on this /// call (canonical JSON of {name, description, schema} sorted by name, /// SHA-256, hex). Lets auditors detect "the same prompt saw a different /// tool surface yesterday". /// public string? ToolSetHash { get; set; } /// /// Opaque provider-side fingerprint identifying the exact backend /// configuration that served the call (OpenAI returns this as /// system_fingerprint; other OpenAI-compatible providers may or may /// not). When the value changes between two otherwise identical requests, /// the provider re-released the model under the same id. /// public string? ProviderSystemFingerprint { get; set; } /// /// Stable identifier of the principal that initiated the call (end-user, /// service account, on-behalf-of subject — the host decides). Captured /// pre-call from the fluent builder (.User(...)) or the /// llm.user.id header; the same value is stamped on every row of /// the same agent turn (system / user / tool / assistant). /// public string? UserId { get; set; } /// /// Connection-factory alias used for this call (e.g. "haiku", /// "gpt-mini") — the operator-chosen profile name from /// LlmConnectionFactory.Name. Audits the *intent* (which configured /// connection was selected) on top of / /// (which model actually answered). Differs from the /// (provider, model) pair when the host registers multiple connections to /// the same provider with different keys / quotas / regions. /// public string? FactoryName { get; set; } /// /// Effective base URL the request was sent to, as configured on /// LlmConnectionFactory.BaseUrl. Null when the factory used the /// provider's built-in default endpoint. Captures self-hosted gateways /// (vLLM, llama.cpp, in-house proxies) that auditors otherwise have to /// chase through environment configuration. /// public string? BaseUrl { get; set; } /// /// Provider-issued response identifier surfaced by the backend (top-level /// id on OpenAI / Anthropic / xAI / Together responses). Null on /// non-assistant rows or when the provider does not surface one. Lets an /// auditor cross-reference a persisted row with the provider's own usage /// / billing logs. /// public string? ProviderResponseId { get; set; } /// /// Wall-clock time (milliseconds) the provider spent producing this /// assistant turn — measured around ILlmProvider.CompleteAsync. /// Null on user / tool-result / system rows. /// public long? LatencyMs { get; set; } /// /// Stable, non-secret fingerprint of the API key used for this call — /// SHA-256 of the key, first 16 hex chars. Lets a host with multiple keys /// per provider (per-tenant, per-environment, rotation pairs) tell which /// key served a given row without storing the key itself. Null when the /// factory exposes no ApiKey (e.g. on-host providers, secret-ref /// resolution skipped). /// public string? ApiKeyFingerprint { get; set; } /// /// How many times the route framework retried the inbound exchange before /// the call succeeded — the operator-visible "this row is from a retry" /// signal. Read from exchange.Properties["RetryAttempt"] /// (set by RetryProcessor) with fallbacks to /// exchange.In.Headers["CamelRedeliveryCounter"] /// (OnExceptionProcessor) and /// exchange.In.Headers["CamelDeadLetterRedeliveryCount"] /// (DeadLetterProcessor). Null when no retry counter is on the /// exchange (first / only delivery). Same value stamped on every row of /// the same agent turn. /// public int? RetryCount { get; set; } /// /// Content blocks for this message, stored as a typed nested array. Each /// block carries a discriminator () /// plus the fields used by the matching LlmContentBlock variant. /// Provider-emitted JSON ( / /// ) stays a raw string — /// those payloads are intentionally schema-less. /// /// A "thinking" block is the model's reasoning, kept with the turn that /// produced it: text in , the /// signature and the redacted payload beside it. /// /// public MessageContentBlock[] Content { get; set; } = []; /// /// Free-form audit tags for this row. Stored as a native REDB /// so LINQ-to-SQL queries like /// x.AuditTags["ab-bucket"] == "A" or /// x.AuditTags.ContainsKey("tier") run server-side via /// redb.Query<MessageProps>(). Captured pre-call (fluent /// .Audit(k,v) or llm.audit.<name> headers) and stamped /// identically on every row of the same turn. /// public Dictionary? AuditTags { get; set; } } /// /// Typed nested representation of an LlmContentBlock. Discriminated /// by ; only the fields used by the active variant are set. /// public class MessageContentBlock { /// Block kind: "text" / "tool_use" / "tool_result" / "thinking". public string Kind { get; set; } = string.Empty; /// Set when == "text". public string? Text { get; set; } /// Set when == "tool_use" or "tool_result". public string? ToolUseId { get; set; } /// Tool name; set when == "tool_use". public string? ToolName { get; set; } /// Raw tool input JSON; set when == "tool_use". public string? InputJson { get; set; } /// Raw tool output JSON; set when == "tool_result". public string? OutputJson { get; set; } /// Error flag for tool results; set when == "tool_result". public bool IsError { get; set; } /// /// Reasoning text; set when == "thinking". Empty when the provider signs the /// block without returning its text, and for a redacted block. /// public string? ThinkingText { get; set; } /// /// Provider signature that authenticates ; "thinking" blocks only, null /// when the provider does not sign. The provider verifies it when the block comes back, so text and /// signature are stored and replayed exactly as received. /// public string? Signature { get; set; } /// /// Encrypted payload of a redacted thinking block; "thinking" blocks only, with /// empty. Nothing in it can be read — only handed back. /// public string? RedactedData { get; set; }} Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/PromptTemplateProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/PromptTemplateProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// A versioned prompt template. (, ) /// is the business key; the framework loads "latest" by ordering on /// . /// [RedbScheme("LLM Prompt Template")] public class PromptTemplateProps { /// Stable template name (free of version). public string Name { get; set; } = string.Empty; /// Version string — semver / hash / monotonic tag. public string Version { get; set; } = string.Empty; /// Template body. Substitution is the caller's responsibility. public string Body { get; set; } = string.Empty; /// Optional human description for tooling. public string? Description { get; set; } /// When this version was registered. public DateTimeOffset CreatedAtUtc { get; set; } } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/ToolAuditProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/ToolAuditProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// One row per tool invocation, written by the audit observer. The scheme is built around the dimensions /// every audit dashboard slices by — , , /// , . /// /// Two different filters, and they cost differently. WhereRedb narrows by OBJECT rows — the columns /// of _objects (id, name, value_*, parent, dates) — which is the fast path, on the owner's /// measurements an order of magnitude faster. Where narrows by VALUES: a props-typed predicate /// resolves through the values table. Both are server-side; the second merely pays for the extra table. /// A dashboard that needs cheap slicing by tool therefore rides a base field — which is why the row /// name leads with the tool name (WhereRedb(o => o.Name.Contains(tool))), and a base filter /// combines with a props predicate in one chain — WhereRedb(...).Where(...), cheap clause first. /// /// [RedbScheme("LLM Tool Audit")] public class ToolAuditProps { /// Owning conversation. public string ConversationId { get; set; } = string.Empty; /// Message id this audit is attached to (the tool-use message). public string? MessageId { get; set; } /// Tool that was invoked. public string ToolName { get; set; } = string.Empty; /// Tool-use id from the model response. public string ToolUseId { get; set; } = string.Empty; /// When the invocation started. public DateTimeOffset InvokedAtUtc { get; set; } /// Wall-clock duration in milliseconds. public int DurationMs { get; set; } /// Outcome bucket: "success" / "error" / "skipped" / "denied". public string Outcome { get; set; } = string.Empty; /// Reason text when is "skipped" / "denied". public string? SkipReason { get; set; } /// JSON-serialized tool input as it was dispatched. public string InputJson { get; set; } = "{}"; /// JSON-serialized tool output; null on failure. public string? OutputJson { get; set; } /// Exception message when is "error". public string? ErrorMessage { get; set; } } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/ToolCacheProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/ToolCacheProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// Cached deterministic tool output. The key is built by Tools/ToolCacheKey.StoreKey and shaped /// persist:{toolName}:{hash} — the hash folds in the tool name, the resolved endpoint URI, the /// governance-policy fingerprint, the caller fingerprint and the tool input JSON, so an entry written /// while a tool was laxer can never answer a call made after the tool got stricter. Only /// Persist-policy entries reach this store; None and Memoize never do (the latter /// stays in the in-process memo: layer). /// /// The key lives on the value_string column of _objects (partial index on /// PostgreSQL/SQLite; no index on MSSQL), not in props — lookups are server-side via /// WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(key)); the key also rides, /// normalized, in value_unique (per-scheme unique race barrier). /// The store honours lazily — entries past expiry are dropped on read. /// /// [RedbScheme("LLM Tool Cache")] public class ToolCacheProps { /// /// Optional tool name for scoped invalidation / metrics. Not written today — the tool name already /// rides in the clear inside the cache key (an _objects column), which is the only place a /// server-side query can reach it without touching props (Tools/ToolCacheKey.cs). /// public string? ToolName { get; set; } /// JSON-serialized tool output. public string OutputJson { get; set; } = "{}"; /// When the entry was created. public DateTimeOffset CreatedAtUtc { get; set; } /// Optional expiry; null = no TTL. public DateTimeOffset? ExpiresAtUtc { get; set; } } Path: redb-route/redb.Route.Llm/Storage/Redb/Schemas/ToolIdempotencyProps.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/Schemas/ToolIdempotencyProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Llm.Storage.Redb.Schemas; /// /// Persisted tool-call idempotency record. Distinct from /// : this row exists for the lifetime of one /// reservation cycle (reserve → complete → optional release) and answers /// "did we already run tool_use_id X for conversation C?". The cache, by /// contrast, is keyed on a content hash and lives on its own TTL. /// /// Each row carries the composite key "llm-tool:{conv}:{toolUseId}" on /// the _objects.value_string column (partial index on PostgreSQL/SQLite; /// no index on MSSQL) and, normalized, in value_unique (per-scheme unique /// race barrier). Filtering by this scheme id alone narrows the scan to /// idempotency rows — no mixing with cache rows in WhereRedb queries. /// /// [RedbScheme("LLM Tool Idempotency")] public class ToolIdempotencyProps { /// Optional tool name for diagnostics / per-tool reports. public string? ToolName { get; set; } /// JSON-serialized tool output that was returned for the original call. public string OutputJson { get; set; } = "{}"; /// When the original tool invocation was confirmed. public DateTimeOffset CreatedAtUtc { get; set; } } Path: redb-route/redb.Route.Llm/Telemetry/LlmMetrics.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Telemetry/LlmMetrics.cs ---- using System.Diagnostics.Metrics; using redb.Route.Telemetry; namespace redb.Route.Llm.Telemetry; /// /// LLM-specific counters and histograms. Published on the same shared meter /// ( = "redb.Route") so a single /// .AddMeter("redb.Route") in OpenTelemetry picks up everything. /// /// Standard tags: llm.provider, llm.model.id, llm.factory. /// Optional: llm.stop_reason, llm.tool.name. /// /// public static class LlmMetrics { /// Meter instance. Same canonical name as . public static readonly Meter Meter = new(RouteMetrics.MeterName, GetVersion()); private static string GetVersion() => typeof(LlmMetrics).Assembly.GetName().Version?.ToString() ?? "0.0.0"; /// Total LLM calls dispatched to a provider (one per provider HTTP roundtrip). public static readonly Counter Calls = Meter.CreateCounter("redb.route.llm.calls", "calls", "Number of provider calls (one per HTTP roundtrip; an agent run with N iterations emits N)."); /// Failed provider calls (timeout, transport error, parsing error). public static readonly Counter CallsFailed = Meter.CreateCounter("redb.route.llm.calls.failed", "calls", "Provider calls that ended with an exception."); /// Provider call latency in milliseconds (one observation per call). public static readonly Histogram CallDuration = Meter.CreateHistogram("redb.route.llm.call.duration", "ms", "Wall-clock duration of a single provider call."); /// Input tokens billed (sum across calls). public static readonly Counter TokensIn = Meter.CreateCounter("redb.route.llm.tokens.in", "tokens", "Input tokens reported by the provider."); /// Output tokens billed. public static readonly Counter TokensOut = Meter.CreateCounter("redb.route.llm.tokens.out", "tokens", "Output tokens reported by the provider."); /// Estimated USD cost (counter; converted to long-cents via x10000). public static readonly Counter CostMicroUsd = Meter.CreateCounter("redb.route.llm.cost.usd_micro", "usd*1e-6", "Estimated cost in micro-USD (1e-6 USD)."); /// Number of agent runs (one per To(\"llm://...\") exchange). public static readonly Counter AgentRuns = Meter.CreateCounter("redb.route.llm.agent.runs", "runs", "Number of agent runs (each may include multiple provider calls)."); /// Total tool-loop iterations performed by the agent (histogram per run). public static readonly Histogram AgentIterations = Meter.CreateHistogram("redb.route.llm.agent.iterations", "iterations", "Tool-loop iterations per agent run."); /// Tool invocations (one per tool_use block executed). public static readonly Counter ToolInvocations = Meter.CreateCounter("redb.route.llm.tool.invocations", "calls", "Number of tool invocations performed by the agent."); /// Tool invocation failures. public static readonly Counter ToolFailures = Meter.CreateCounter("redb.route.llm.tool.failures", "calls", "Number of tool invocations that threw an exception."); /// Tool-cache reads that returned a live (non-expired) cached output. Tag llm.tool.name when known. public static readonly Counter ToolCacheHits = Meter.CreateCounter("redb.route.llm.tool_cache.hits", "reads", "Tool-cache reads that returned a live cached output."); /// Tool-cache reads that found no row (cold key). public static readonly Counter ToolCacheMisses = Meter.CreateCounter("redb.route.llm.tool_cache.misses", "reads", "Tool-cache reads that found no row.");} Path: redb-route/redb.Route.Llm/Tools/AgentRunToolCache.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Tools/AgentRunToolCache.cs ---- namespace redb.Route.Llm.Tools; /// /// Run-scoped memo store for ToolCachingPolicy.Memoize. Created when an agent run starts and /// dropped when it returns, which is the whole of the promise: "memoised for the lifetime of the /// agent run". No TTL, no eviction, no database row — entries cannot outlive the run that wrote /// them, so there is nothing left over to purge. /// /// The run loop dispatches tools sequentially, so a plain dictionary is safe; it is not shared /// between runs. /// /// internal sealed class AgentRunToolCache { private readonly Dictionary _entries = new(StringComparer.Ordinal); /// Returns the memoised output for , or null. public string? Get(string key) => _entries.TryGetValue(key, out var value) ? value : null; /// Memoises under . public void Set(string key, string outputJson) => _entries[key] = outputJson; } Path: redb-route/redb.Route.Llm/Tools/KnowledgeSearchTool.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Tools/KnowledgeSearchTool.cs ---- using System.Text.Json; using System.Text.Json.Nodes; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Extensions; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Tools; /// /// Options for the knowledge_search LLM tool / step. /// public sealed class KnowledgeSearchOptions { /// From(...) URI the tool route binds to. public string EndpointUri { get; set; } = "direct:llm.knowledge_search"; /// Model-facing tool name. public string ToolName { get; set; } = "knowledge_search"; /// /// Explicit store. When null, resolved from exchange.ServiceProvider /// at call time — so AddRedbLlmStorage()'s /// (or the in-memory default) is picked up automatically. /// public IKnowledgeStore? Store { get; set; } /// Top-K when the model does not specify top_k. public int DefaultTopK { get; set; } = 5; /// /// Pin the tool to one collection. When set, the model's collection /// argument is ignored (the tool can only ever see this collection) — the /// lever for scoping an agent to a single tenant / document set. Null lets /// the model choose (or search across all collections). /// public string? Collection { get; set; } /// Max chars of chunk text returned per hit (0 = full text). public int MaxTextChars { get; set; } = 2000; /// /// When set, the tool runs a semantic search: it embeds the query with /// this provider and ranks chunks by cosine similarity /// (). When null it runs a /// keyword substring search (). /// Semantic needs the chunks to have been ingested with embeddings. /// public IEmbeddingProvider? EmbeddingProvider { get; set; } } /// /// DSL step that answers a knowledge_search tool call: reads /// {"query":"...","top_k":int?,"collection":string?} from the exchange /// body, runs (keyword / substring), /// and writes {"results":[{"id","collection","score","text"}]} to the body. /// public static class KnowledgeSearchDsl { private static readonly JsonSerializerOptions JsonOpts = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; /// Adds a knowledge keyword-search step. See . public static IRouteDefinition KnowledgeSearch(this IRouteDefinition self, KnowledgeSearchOptions options) { ArgumentNullException.ThrowIfNull(self); ArgumentNullException.ThrowIfNull(options); return self.Process(async (exchange, ct) => { var store = options.Store ?? exchange.ServiceProvider?.GetService(typeof(IKnowledgeStore)) as IKnowledgeStore ?? throw new InvalidOperationException( "knowledge_search: no IKnowledgeStore available. Set KnowledgeSearchOptions.Store " + "or register one (e.g. AddRedbLlmStorage())."); var (query, topK, collection) = ParseInput(exchange.In.Body); var effectiveTopK = Math.Clamp(topK ?? options.DefaultTopK, 1, 50); var effectiveCollection = options.Collection ?? collection; // pinned collection wins // Semantic when an embedding provider is configured, else keyword. IReadOnlyList hits; if (options.EmbeddingProvider is { } embedding) { var vector = await embedding.EmbedOneAsync(query, ct).ConfigureAwait(false); hits = await store .SearchAsync(vector, effectiveTopK, effectiveCollection, exchange, ct) .ConfigureAwait(false); } else { hits = await store .SearchTextAsync(query, effectiveTopK, effectiveCollection, exchange, ct) .ConfigureAwait(false); } var results = new JsonArray(); foreach (var hit in hits) { var text = hit.Chunk.Text; if (options.MaxTextChars > 0 && text.Length > options.MaxTextChars) text = text[..options.MaxTextChars] + "…"; results.Add(new JsonObject { ["id"] = hit.Chunk.Id, ["collection"] = hit.Chunk.Collection, ["score"] = hit.Score, ["text"] = text }); } exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = new JsonObject { ["results"] = results }.ToJsonString(JsonOpts); exchange.Out.Headers["llm.knowledge_search.hits"] = results.Count; }); } private static (string Query, int? TopK, string? Collection) ParseInput(object? body) { var json = body as string ?? body?.ToString(); if (string.IsNullOrWhiteSpace(json)) throw new ArgumentException("knowledge_search: empty tool input."); using var doc = JsonDocument.Parse(json); var root = doc.RootElement; if (!root.TryGetProperty("query", out var q) || q.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(q.GetString())) throw new ArgumentException("knowledge_search: 'query' (string) is required."); int? topK = root.TryGetProperty("top_k", out var tk) && tk.ValueKind == JsonValueKind.Number ? tk.GetInt32() : null; string? collection = root.TryGetProperty("collection", out var c) && c.ValueKind == JsonValueKind.String ? c.GetString() : null; return (q.GetString()!, topK, collection); } } /// /// Self-contained RouteBuilder that mounts knowledge_search as an /// LLM tool. Prefer the DSL .KnowledgeSearch(opts) on an existing route; /// this shim is for handing a ready route to context.AddRoutes(...). /// /// /// context.AddRoutes(new KnowledgeSearchTool(new KnowledgeSearchOptions /// { /// Collection = "rules", // pin the agent to one collection /// })); /// // ...then expose it: Llm.Factory("claude").Tools("knowledge_search") /// /// /// public sealed class KnowledgeSearchTool : RouteBuilder { private const string InputSchema = """ { "type": "object", "properties": { "query": { "type": "string", "description": "Keyword / substring to find in the knowledge base." }, "top_k": { "type": "integer", "description": "Max hits to return (default 5, capped at 50)." }, "collection": { "type": "string", "description": "Restrict to this collection (ignored when the tool is pinned to one)." } }, "required": ["query"], "additionalProperties": false } """; private readonly KnowledgeSearchOptions _options; /// Creates the tool with the given options. public KnowledgeSearchTool(KnowledgeSearchOptions options) => _options = options ?? throw new ArgumentNullException(nameof(options)); /// protected override void Configure() => From(_options.EndpointUri) .AsLlmTool(_options.ToolName) .Description("Search the knowledge base for chunks whose text contains the query " + "(case-insensitive keyword / substring). Returns " + "{\"results\":[{\"id\",\"collection\",\"score\",\"text\"}]}, most relevant first.") .Input(InputSchema) .SideEffect(ToolSideEffect.ReadOnly) .Cost(ToolCostClass.Cheap) .Then() .KnowledgeSearch(_options); } Path: redb-route/redb.Route.Llm/Tools/ToolCacheKey.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Tools/ToolCacheKey.cs ---- using System.Security.Cryptography; using System.Text; using System.Text.Json; using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Tools; /// /// Content-hash keys for the tool cache. Two layers, one question ("do I already have an output for /// this exact input?"): the in-process run-scoped memo answers inside a run, the store answers across /// runs. Memoize never reaches the store — an entry keyed for one run could only be read by /// that run, so it would be unreadable garbage that nothing ever evicts. /// /// Both keys carry the RESOLVED endpoint address, the tool's POLICY fingerprint and the CALLER /// fingerprint, not the tool name alone: may address a /// per-tenant / per-principal endpoint, and a tool route also receives the caller's identity and the /// headers the route opted into propagating (see ToolHeaderPolicy) — so "same input" is not the /// same answer for two callers. An entry written while the tool was laxer must not answer a call made /// after it got stricter either. The address is folded in as a hash and never stored or logged raw — /// URIs may carry sensitive parameters, and so may a caller identity. /// /// /// The tool name, by contrast, is kept in the clear as a label: operators reading the cache scheme need /// to tell whose rows they are looking at, and a server-side query can scope a scheme to one tool by it /// (REDB keeps props out of the object columns, so the stored key is the only place a tool name can /// live). Everything security-relevant still goes through the hash. /// /// internal static class ToolCacheKey { /// Key for the in-process run-scoped memo layer. public static string MemoKey( string toolName, string resolvedEndpointUri, string policyFingerprint, string callerFingerprint, string inputJson) => $"memo:{toolName}:{Hash(toolName, resolvedEndpointUri, policyFingerprint, callerFingerprint, inputJson)}"; /// Key for the persistent store; null for None and Memoize. public static string? StoreKey( string toolName, string resolvedEndpointUri, string inputJson, ToolCachingPolicy policy, string policyFingerprint, string callerFingerprint) => policy == ToolCachingPolicy.Persist ? $"persist:{toolName}:{Hash(toolName, resolvedEndpointUri, policyFingerprint, callerFingerprint, inputJson)}" : null; /// /// Fingerprint of the tool's governance policy, folded into both keys. An entry written while a /// tool was laxer must never answer a call made after the tool got stricter — adding a required /// claim or changing the caching policy invalidates the old entries instead of quietly serving /// their output. Claims are length-prefixed (as in ToolSetHash), so splitting one claim in /// two cannot collide with a single claim that merely contains a separator. /// public static string PolicyFingerprint(LlmToolSafety safety) { var sb = new StringBuilder(); sb.Append(safety.SideEffect).Append('/').Append(safety.Caching).Append('/') .Append(safety.RequiresApproval ? '1' : '0'); foreach (var claim in safety.RequiredClaims.OrderBy(c => c, StringComparer.Ordinal)) sb.Append('\n').Append(claim.Length).Append(':').Append(claim); return sb.ToString(); } /// Relative TTL of a persisted entry (owner-tunable; not yet a route option). public static TimeSpan StoreTtl => TimeSpan.FromHours(24); private static string Hash( string toolName, string resolvedEndpointUri, string policyFingerprint, string callerFingerprint, string inputJson) { var canonical = Canonicalize(inputJson); var payload = $"{toolName}\n{resolvedEndpointUri}\n{policyFingerprint}\n{callerFingerprint}\n{canonical}"; return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload))).ToLowerInvariant(); } /// /// Canonical form of the input JSON: object properties sorted by name, recursively. Two texts that /// differ only in key order mean the same tool call, and a cache that disagreed would report a miss /// for an identical request. Anything that is not valid JSON is used verbatim — a key that is /// merely conservative is correct, a key built on a parse failure is not. /// private static string Canonicalize(string inputJson) { if (string.IsNullOrWhiteSpace(inputJson)) return string.Empty; try { using var doc = JsonDocument.Parse(inputJson); var buffer = new MemoryStream(); using (var writer = new Utf8JsonWriter(buffer)) WriteCanonical(writer, doc.RootElement); return Encoding.UTF8.GetString(buffer.ToArray()); } catch (JsonException) { return inputJson; } } private static void WriteCanonical(Utf8JsonWriter writer, JsonElement element) { switch (element.ValueKind) { case JsonValueKind.Object: writer.WriteStartObject(); foreach (var property in element.EnumerateObject() .OrderBy(p => p.Name, StringComparer.Ordinal)) { writer.WritePropertyName(property.Name); WriteCanonical(writer, property.Value); } writer.WriteEndObject(); break; case JsonValueKind.Array: writer.WriteStartArray(); foreach (var item in element.EnumerateArray()) WriteCanonical(writer, item); writer.WriteEndArray(); break; default: element.WriteTo(writer); break; } } } Path: redb-route/redb.Route.Llm/Tools/ToolFilter.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Tools/ToolFilter.cs ---- using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Tools; /// /// Resolves the per-call tool list from a registry given a CSV/wildcard filter. /// Centralises the parsing rules so URI options, the inline DSL builder and the /// consumer all behave the same. /// internal static class ToolFilter { /// /// Resolves the tool list for a single call. /// /// Registry to read from. May be null when DI is incomplete. /// /// null/empty \u2014 no tools (default; explicit opt-in); /// "*" \u2014 every descriptor in the registry; /// CSV of names \u2014 only the named descriptors (missing names are skipped silently). /// public static IReadOnlyList Resolve( IToolDescriptorRegistry? registry, string? filter) { if (registry is null) return []; if (string.IsNullOrWhiteSpace(filter)) return []; if (filter.Trim() == "*") return registry.All(); var names = filter .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (names.Length == 0) return []; var result = new List(names.Length); foreach (var name in names) { var descriptor = registry.Get(name); if (descriptor is not null) result.Add(descriptor); } return result; } } Path: redb-route/redb.Route.Llm/Transcription/SttComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Transcription/SttComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Transcription; /// /// Speech-to-text transport. Scheme: stt. Producer-only, symmetric with /// llm:// and embed://: To("stt://<connectionFactoryName>") /// turns the exchange body (recorded audio as byte[], ReadOnlyMemory<byte> /// or a Stream) into the recognised text written to Out.Body. /// /// The URI host names an (Provider / BaseUrl / /// ApiKey / ModelId — set ModelId to the speech model), which is where local /// and paid recognition part company: point BaseUrl at a whisper server on /// 127.0.0.1 and the route costs nothing to run, point it at a paid endpoint /// and the same route bills. Neither is visible from the route. /// /// /// /// From("direct://voice") /// .To(Tg.Download(token)) // attachment file_id → bytes /// .To("stt://local") // bytes → text /// .To("direct://chat"); // and on as an ordinary reply /// /// /// [EndpointRole(EndpointRole.Producer, Hint = "Use To(\"stt://\").")] public sealed class SttComponent : ComponentBase { /// public override string Scheme => "stt"; /// /// Builds the from a resolved connection /// factory. Defaults to ; override /// for a custom provider or in tests. /// public Func ProviderFactory { get; set; } = OpenAiTranscriptionProvider.Create; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new SttEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new SttEndpoint(uri, this, options); } } /// Options for an stt:// endpoint. public sealed class SttEndpointOptions : EndpointOptions { /// Alternative to the URI host for the connection-factory name. [RegistryReference(typeof(LlmConnectionFactory))] public string? ConnectionFactory { get; set; } /// /// ISO-639-1 language hint passed to the model (ru). Empty lets the model /// detect the language, which costs accuracy on short recordings — a few words are /// routinely detected as the wrong language. Overridable per exchange with the /// header. /// public string? Language { get; set; } /// /// Decoding hint: names and terms the model would not otherwise spell right. /// Off by default, and deliberately so — a hint can also displace what was said. /// public string? Prompt { get; set; } /// /// Name to upload the audio under. Speech endpoints pick a demuxer by extension, so /// this decides whether an Ogg/Opus voice note is decoded or rejected. When unset the /// producer derives it from the exchange ContentType, falling back to /// audio.ogg. /// public string? FileName { get; set; } /// public override void Validate() { } } /// Speech-to-text endpoint. URI path = connection-factory name. public sealed class SttEndpoint : EndpointBase { /// Connection-factory name (URI path or ?connectionFactory=). public string FactoryName { get; } /// Factory resolved from the route context (null when wired later). internal LlmConnectionFactory? ResolvedFactory { get; } /// Creates the endpoint. public SttEndpoint(EndpointUri uri, SttComponent component, SttEndpointOptions options) : base(uri, component, options) { FactoryName = !string.IsNullOrWhiteSpace(uri.Path) ? uri.Path : (options.ConnectionFactory ?? string.Empty); if (string.IsNullOrWhiteSpace(FactoryName)) throw new InvalidOperationException( "stt:// requires a connection factory — use 'stt://' or '?connectionFactory='."); if (component.Context is not null) ResolvedFactory = component.Context.GetFromRegistry(FactoryName); } /// public override IProducer CreateProducer() => new SttProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException("stt:// is producer-only. Use To(\"stt://\")."); } Path: redb-route/redb.Route.Llm/Transcription/SttProducer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Transcription/SttProducer.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Transcription; /// /// Speech-to-text producer: transcribes the exchange body and writes the recognised /// text to Out.Body. /// /// An empty result is a result, not a failure: silence and music transcribe to an /// empty string, and the route decides what to say about that. The producer reports it /// as = 0 rather than throwing, so /// "nothing was said" and "recognition broke" stay distinguishable — the second one /// throws. /// /// public sealed class SttProducer : ConnectableProducer { private readonly SttEndpoint _endpoint; private readonly SttEndpointOptions _options; private ITranscriptionProvider? _provider; /// Creates the producer. public SttProducer(SttEndpoint endpoint, SttEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"stt:{_endpoint.FactoryName}"; /// protected override Task ConnectAsync(CancellationToken ct) => Task.CompletedTask; /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(exchange); var provider = ResolveProvider(); var audio = await ReadAudioAsync(exchange, ct).ConfigureAwait(false); var result = await provider.TranscribeAsync( new TranscriptionRequest( audio, ResolveFileName(exchange), Language: ResolveOptional(exchange, LlmHeaders.TranscriptionLanguage, _options.Language), Prompt: ResolveOptional(exchange, LlmHeaders.TranscriptionPrompt, _options.Prompt)), ct).ConfigureAwait(false); exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = result.Text; exchange.Out.ContentType = "text/plain"; exchange.Out.Headers[LlmHeaders.TranscriptionModel] = provider.ModelId; exchange.Out.Headers[LlmHeaders.TranscriptionProvider] = provider.ProviderId; // Length and not the text: a header travels into logs, audits and dead letters, and // a transcription is the person's own words. How much was recognised answers "did it // work" without repeating what was said. exchange.Out.Headers[LlmHeaders.TranscriptionChars] = result.Text.Length; if (result.Language is { Length: > 0 } language) exchange.Out.Headers[LlmHeaders.TranscriptionLanguage] = language; if (result.DurationSeconds is { } duration) exchange.Out.Headers[LlmHeaders.TranscriptionDuration] = duration; Logger?.LogDebug( "stt: transcribed {Bytes} bytes into {Chars} characters via {Provider}/{Model}", audio.Length, result.Text.Length, provider.ProviderId, provider.ModelId); } /// /// Reads the recording off the exchange. A is buffered because the /// upload needs a length — speech endpoints take a multipart part, not a chunked one. /// private static async Task> ReadAudioAsync(IExchange exchange, CancellationToken ct) { switch (exchange.In.Body) { case byte[] bytes: return bytes; case ReadOnlyMemory memory: return memory; case Stream stream: { using var buffer = new MemoryStream(); if (stream.CanSeek) stream.Position = 0; await stream.CopyToAsync(buffer, ct).ConfigureAwait(false); return buffer.ToArray(); } default: throw new InvalidOperationException( $"stt://: unsupported body type '{exchange.In.Body?.GetType().Name ?? "null"}'. " + "Expected recorded audio as byte[], ReadOnlyMemory or Stream — for a Telegram " + "voice note that is what 'telegram://download' puts on the exchange."); } } /// /// Name to upload under: header, then option, then the exchange content type, then a /// plain default. The content-type step is what lets a transport that already knows the /// format ("audio/ogg") get it right with no configuration at all. /// private string ResolveFileName(IExchange exchange) { if (ResolveOptional(exchange, LlmHeaders.TranscriptionFileName, _options.FileName) is { Length: > 0 } name) return name; return exchange.In.ContentType?.Split(';')[0].Trim().ToLowerInvariant() switch { "audio/ogg" or "audio/opus" or "audio/x-opus+ogg" => "audio.oga", "audio/mpeg" or "audio/mp3" => "audio.mp3", "audio/mp4" or "audio/x-m4a" => "audio.m4a", "audio/wav" or "audio/x-wav" or "audio/wave" => "audio.wav", "audio/flac" or "audio/x-flac" => "audio.flac", "audio/webm" or "video/webm" => "audio.webm", "video/mp4" => "audio.mp4", _ => "audio.ogg" }; } private static string? ResolveOptional(IExchange exchange, string header, string? fallback) { if (exchange.In.Headers.TryGetValue(header, out var value) && value?.ToString() is { Length: > 0 } fromHeader) return fromHeader; return string.IsNullOrWhiteSpace(fallback) ? null : fallback; } private ITranscriptionProvider ResolveProvider() { if (_provider is not null) return _provider; var component = (SttComponent)_endpoint.Component; var factory = _endpoint.ResolvedFactory ?? component.Context?.GetFromRegistry(_endpoint.FactoryName) ?? throw new InvalidOperationException( $"stt://: connection factory '{_endpoint.FactoryName}' is not registered in the route context."); _provider = component.ProviderFactory(factory); return _provider; } } Path: redb-route/redb.Route.Llm/doc/RAG.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/doc/RAG.md ---- # redb.Route.Llm — RAG (knowledge base) > Retrieval-augmented generation as **routes and DSL steps**, not a separate vector > service. Documents are ingested through a scheme, embedded through a provider, > searched by keyword **or** vector, and fed to the model either as a **tool** the > agent calls or as **context injected** into the system prompt. Everything is a > redb.Route primitive. Added incrementally in **3.3.0** — see [CHANGELOG](../../CHANGELOG.md). --- ## The loop ```text From("file://docs")──►To("knowledge://kb") ← ingest: chunk (+embed) → upsert │ ▼ IKnowledgeStore (RedbKnowledgeStore) KnowledgeChunkProps: text=note, embedding=value_bytes │ ┌───────────────┴────────────────┐ ▼ ▼ SearchTextAsync (keyword LIKE) SearchAsync (cosine, needs embeddings) │ │ └───────────────┬─────────────────┘ ▼ ┌─────────────────────┴──────────────────────┐ ▼ ▼ knowledge_search tool .Knowledge("kb", k) DSL (agent calls it in the loop) (injects top-K into the system prompt) │ │ └───────────────────┬─────────────────────────┘ ▼ .To("llm://claude") ``` ## Pieces (all in `redb.Route.Llm`) | Piece | Type | What | |---|---|---| | `knowledge://` | scheme (producer) | `To(...)` — chunk the exchange body, optionally embed, upsert | | `embed://` | scheme (producer) | `To(...)` — embed the body as a route step (text → `float[]`, texts → `float[][]`) | | `IEmbeddingProvider` / `OpenAiEmbeddingProvider` | provider | text → vectors (OpenAI-compatible `/embeddings`) | | `IKnowledgeStore.SearchTextAsync` | store method | keyword substring, server-side `ILIKE` on the indexed `note` | | `IKnowledgeStore.SearchAsync` | store method | cosine over embeddings | | `KnowledgeSearchTool` (`knowledge_search`) | `.AsLlmTool` | the agent searches the base itself | | `.Knowledge("coll", k)` | DSL step | retrieve + inject top-K into the system prompt | Storage is the property-less `KnowledgeChunkProps` (`value_string`=chunk id, `name`=collection, `note`=`{text,meta}` JSON, `value_bytes`=embedding). Enabled by `AddRedbLlmStorage()` → `RedbKnowledgeStore` (or `InMemoryKnowledgeStore` for tests). --- ## Keyword vs semantic - **Keyword** (`SearchTextAsync`, `knowledge_search` without an embedder, `.Knowledge()` without one): server-side `LIKE` over the chunk text. No embedding infra, cheap, exact — best for structured / numbered / code / ID content, and for a query that *is* a term. - **Semantic** (with an `IEmbeddingProvider`): embed the query, cosine-rank. Matches meaning / paraphrase — best for prose corpora and natural-language questions. - Hybrid is a matter of running both and merging; each surface degrades gracefully. Non-ASCII (Cyrillic / CJK) is stored as UTF-8 in `note` (relaxed JSON escaping), so keyword `LIKE` matches a raw non-ASCII query — not `\uXXXX`. --- ## End to end ```csharp // DI services.AddRedbRoute(route => { route.Services.AddRedbRouteLlm(); route.Services.AddRedbLlmStorage(); // IKnowledgeStore → redb route.Services.AddLlmConnectionFactory("claude", f => { f.Provider="anthropic"; f.ModelId="claude-haiku-4-5"; f.ApiKeySecretRef="anthropic.api-key"; }); }); // optional: register an embedding provider for semantic search // services.AddSingleton(OpenAiEmbeddingProvider.Create( // new LlmConnectionFactory { Provider="openai", ModelId="text-embedding-3-small", ApiKey=key })); // component for the ingest scheme context.AddComponent(new KnowledgeComponent()); // 1) ingest From("file://handbook?include=*.md") .To("knowledge://handbook?chunkChars=1000&overlap=100"); // 2a) let the agent search (tool) context.AddRoutes(new KnowledgeSearchTool(new KnowledgeSearchOptions { Collection = "handbook" })); From("kafka://questions") .To(Llm.Factory("claude").Tools("knowledge_search").AsUri()) .To("kafka://answers"); // 2b) or inject context automatically (DSL) From("kafka://questions") .Knowledge("handbook", k: 5) // retrieve + inject into the system prompt .To("llm://claude") .To("kafka://answers"); ``` **IP-scoping:** `KnowledgeSearchOptions.Collection` (and the `.Knowledge` collection) **pin** the agent to one collection — the model's `collection` argument is ignored. Chunk text goes into the model's reasoning context (tool result / system prompt), not to the end user; pair with a "ground on it, don't quote verbatim" instruction to keep source material private. --- ## Not shipped yet - `vector://` sink scheme (route a vector to an external store as a step) — `embed://` produces vectors; there is no companion sink scheme yet. - ANN index — `RedbKnowledgeStore.SearchAsync` is an O(N) in-process cosine scan (fine for thousands of chunks). For millions, wrap `IKnowledgeStore` with a pgvector / Qdrant implementation that overrides `SearchAsync`. - Rich document loaders (PDF/DOCX parsing) — bring your own text; chunking is a deterministic character window. Path: redb-route/redb.Route.Llm/doc/STORAGE.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/doc/STORAGE.md ---- # redb.Route.Llm — Storage Guide > **Audience:** developers already wiring DSL routes with `redb.Route` who want > the **LLM to be a fully-fledged pipeline citizen** — with memory, budget, > approvals and audit trail — not a stateless HTTP call that leaves nothing > behind. > > **TL;DR:** a single line — `route.Services.AddRedbLlmStorage()` — flips the > agent loop from *"forgets everything on restart"* into a **persistent-by-default** > system. All five surfaces (transcripts, approvals, budgets, idempotency, > audit) move into redb. **Not a single line of route code changes** — your > existing `.To("llm://claude")` starts persisting on its own. --- ## Contents 1. [Why storage in an LLM connector at all](#why-storage-in-an-llm-connector-at-all) 2. [One call flips everything — `AddRedbLlmStorage()`](#one-call-flips-everything--addredbllmstorage) 3. [Map — what flows where](#map--what-flows-where) 4. [The join key — `llm.conversation.id`](#the-join-key--llmconversationid) 5. [Concrete recipes — *the why and the how*](#concrete-recipes--the-why-and-the-how) - [A chatbot that remembers](#1-a-chatbot-that-remembers--multi-turn-via-conversationid) - [Inline `.Llm()` — conversation without a URI](#2-inline-llm--conversation-without-a-uri) - [Approval gates for dangerous tools](#3-approval-gates-for-dangerous-tools--verdict-into-redb) - [Hard budget per conversation](#4-hard-budget-per-conversation--050-and-the-agent-shuts-up) - [Idempotent tool retries](#5-idempotent-tool-retries--dont-transfer-money-twice) - [Audit every tool call](#6-audit-every-tool-call--what-the-agent-tried-and-what-blew-up) - [Branching — rewrite a turn and compare](#7-branching--rewrite-a-turn-and-compare) - [`From("llm://...")` — nightly agent](#8-fromllm--nightly-agent-with-permanent-memory) 6. [Schemas — how redb actually stores it](#schemas--how-redb-actually-stores-it) 7. [Stores and interfaces — reference](#stores-and-interfaces--reference) 8. [Operational gotchas](#operational-gotchas) 9. [What's next — Phase 2 / 3](#whats-next--phase-2--3) --- ## Why storage in an LLM connector at all A bare LLM call from C# is just an HTTP client. You hit `client.SendAsync()`, get a response, hand it to the user — **done**. A second later: - you don't know **what** you just talked about with the model; - you don't know **how much** it cost; - you don't know **which tools** the agent invoked or **what they returned**; - if the user types *"continue from where we left off"* — you scrape context by hand from your own data layer, because the LLM client has no memory. These are **cross-cutting** concerns of every production agent, and ~80% of their solutions are **identical**: write to the DB, read from the DB, by key. So why isn't this in the box? In `redb.Route.Llm` it **is** in the box — because redb already gives you tree-structured objects, indexed `value_string` columns, soft-delete and `TreeQuery`. We aren't writing "yet another little ORM for LLM logs". We declare 9 schemas, ship 5 stores — and the agent loop starts writing into a **typed, indexed, query-able** redb layer. All of it — for **one line** of DI registration. --- ## One call flips everything — `AddRedbLlmStorage()` ```csharp services.AddRedbRoute(route => { route.Services.AddRedbRouteLlm(); // engine + in-memory defaults route.Services.AddRedbLlmStorage(); // ← one line: everything moves to redb route.Services.AddLlmConnectionFactory("claude", f => { f.Provider = "anthropic"; f.ModelId = "claude-haiku-4-5"; f.ApiKeySecretRef = "anthropic.api-key"; }); route.AddRouteBuilder(); }); ``` What `AddRedbLlmStorage()` does (`Extensions/ServiceCollectionExtensions.cs:155`): | Interface | Default (in-memory) | Replaced with | Persists | | ---------------------- | -------------------------------- | --------------------------- | ---------------------------------- | | `IConversationStore` | `InMemoryConversationStore` | `RedbConversationStore` | conversation tree | | `IApprovalStore` | `InMemoryApprovalStore` | `RedbApprovalStore` | approver decisions | | `ICostBudgetStore` | `InMemoryCostBudgetStore` | `RedbCostBudgetStore` | running token / $ counters | | `IToolIdempotencyStore`| `InMemoryToolIdempotencyStore` | `RedbToolIdempotencyStore` | cached tool outputs | | `IAgentObserver` | `NoopAgentObserver` | `RedbAuditObserver` | one row per tool invocation | **Not a single line** in your routes changes. The old `.To("llm://claude")` starts writing to the DB on its own — because the engine (`AgentEngine`) already calls these five interfaces. Before this line, it called in-memory fakes; after, it calls redb. That's what *opt-in persistence* should look like: **not a new API**, but a default replacement. No code migrations — your `.To("llm://claude")` works exactly as it did, only now it has memory. --- ## Map — what flows where ```text .From("kafka://chat.in") │ ▼ ──── headers["llm.conversation.id"] = userId ┌──────────────────────┐ │ LlmProducer │ (reads the header → conversationId) └────────┬─────────────┘ ▼ ┌────────────────────────────────────────────────────┐ │ AgentEngine (tool loop) │ │ │ │ ┌── IConversationStore ──► RedbConversationStore │ │ • AppendAsync() per turn ──► ConversationProps │ │ • LoadPathAsync() to rebuild context ──► MessageProps[] (tree) │ │ │ │ ├── IBudgetEnforcer ──► your impl │ │ │ • PreCheckAsync() / RecordAndCheckAsync() │ │ │ • accumulates via ICostBudgetStore ▼ │ │ ──► CostBudgetProps (per-conv) │ ├── IApprovalGate ──► your impl │ │ • AwaitAsync() before risky tools │ │ │ • IApprovalStore.RecordAsync() ─────────────► ApprovalProps │ │ │ │ ├── IToolIdempotencyStore ──► RedbToolIdempotencyStore │ │ • TryReserveAsync() / CompleteAsync() ──► ToolCacheProps │ │ │ │ └── IAgentObserver ──► RedbAuditObserver │ • OnToolInvokedAsync() per tool ──► ToolAuditProps └────────┬───────────────────────────────────────────────┘ ▼ .To("kafka://chat.out") ``` Everything inside the engine box is **not part of your route**. It's the engine, and *it* talks to redb through the interfaces. Your responsibility is the DSL and the headers. Persistence is a side effect of running the agent. --- ## The join key — `llm.conversation.id` Persistence rests on **one header**. If the inbound exchange carries `llm.conversation.id`, all five stores write rows attached to that key. No header — persistence is silently skipped (no error), the agent runs stateless. You set the header three ways: ```csharp // (1) URI param: producer reads the header from the exchange .To(Llm.Factory("claude").ConversationFromHeader().AsUri()) // → ?conversation=header // (2) URI param: use RouteId as conversationId .To(Llm.Factory("claude").ConversationFromRoute().AsUri()) // → ?conversation=property // (3) Inline DSL — set the header yourself .SetHeader(LlmHeaders.ConversationId, ex => ex.In.Headers["X-User-Id"]?.ToString()) .To(Llm.Factory("claude").ConversationFromHeader().AsUri()) ``` Full set of headers that affect storage (`LlmHeaders.cs`): | Constant | Key | Who writes | Where it lands | | ------------------------- | --------------------- | ---------------------------- | ------------------------------------ | | `ConversationId` | `llm.conversation.id` | inbound to producer | `IConversationStore`, `ICostBudgetStore`, `IApprovalStore`, `IToolIdempotencyStore`, `IAgentObserver` | | `ApprovalId` | `llm.approval.id` | `IApprovalGate` | `IApprovalStore` (`value_string`) | | `ToolUseId` | `llm.tool.use_id` | model in a tool_use block | dedup key in `IToolIdempotencyStore`, FK in audit | | `TokensIn` / `TokensOut` | `llm.tokens.in/out` | producer after a call | feeds `ICostBudgetStore.AddAsync` | | `CostUsd` | `llm.cost.usd` | producer (optional) | feeds `ICostBudgetStore.AddAsync` | --- ## Concrete recipes — *the why and the how* ### 1. A chatbot that remembers — multi-turn via `ConversationId` **Problem.** The user types *"What about the second option?"* — without memory all you have is that question. Context is gone. **Solution.** One route on a Kafka topic, header `X-User-Id` → `llm.conversation.id`, the engine does `LoadPathAsync(userId)` before the call and `AppendAsync(userId, ..., assistantTurn)` after. ```csharp public sealed class ChatRoutes : IRouteDefinition { public void Configure(IRouteBuilder routes) { routes.From("kafka://chat.in") .SetHeader(LlmHeaders.ConversationId, ex => ex.In.Headers["X-User-Id"]?.ToString()) .To(Llm.Factory("claude") .ConversationFromHeader() // → ?conversation=header .MaxTokens(2048) .AsUri()) .To("kafka://chat.out"); } } ``` What happens automatically *after* `AddRedbLlmStorage()`: - on entry the engine resolves `conversationId = ex.In.Headers["llm.conversation.id"]`; - `LoadPathAsync(userId)` — a server-side ancestor walk via `redb.GetPathToRootAsync` — pulls the entire previous root → leaf path. **Not a top-N slice** — it's a true path through `_objects.parent_id`; - every turn (user → assistant → tool → ...) `AppendAsync` writes a new `MessageProps` via `CreateChildAsync`. Tree integrity comes from redb, not us; - the assistant reply becomes `path.Last()` of the next call. **Bonus.** `LoadTreeAsync(userId)` returns the whole conversation tree in one shot — for an admin panel, analytics, or replay. --- ### 2. Inline `.Llm()` — conversation without a URI Same thing without `Llm.Factory(...).AsUri()` — for cases where you don't want a separate endpoint: ```csharp routes.From("kafka://support.in") .Llm("claude", b => b .WithConversationFromHeader("X-Ticket-Id") // ticket = conversationId .WithSystemPrompt("You are first-line support. Ask for clarification, never invent facts.") .WithMaxIterations(4)) .To("kafka://support.out"); ``` `WithConversationFromHeader("X-Ticket-Id")` (`LlmRouteDefinitionExtensions.cs:163`) tells the builder: "read header `X-Ticket-Id` and pass it to the engine as the conversation key". From there it's the same as before — the ticket has its own tree, every message is a `MessageProps` under that root. --- ### 3. Approval gates for dangerous tools — verdict into redb **Problem.** The agent can call `delete_user`. You want a human in the loop on Slack first — and you want a **permanent** record of who, when, why. **Solution.** Implement `IApprovalGate` (sends to Slack), the engine itself persists the `ApprovalDecision` through `IApprovalStore` (`Engine/Governance/IApprovalGate.cs:13`). ```csharp public sealed class SlackApprovalGate : IApprovalGate { private readonly ISlackClient _slack; private readonly IApprovalStore _store; public async Task AwaitAsync(ApprovalRequest req, CancellationToken ct) { var msg = await _slack.AskAsync( $"Tool `{req.Tool.Name}` on conversation `{req.ConversationId}`:\n```{req.InputJson}```", ct); var decision = msg.Approved ? ApprovalDecision.Approve($"slack:{msg.MessageId}") : ApprovalDecision.Deny(msg.RejectReason ?? "denied in slack"); await _store.RecordAsync(req, decision, ct); // ← persisted in ApprovalProps return decision; } } services.Replace(ServiceDescriptor.Singleton()); ``` The route doesn't change. When the model calls a tool whose `LlmToolSafety.RequiresApproval == true`, the engine awaits `gate.AwaitAsync(...)`, persists the decision into `ApprovalProps`. Six months later an auditor asks *"who approved deleting user 4242"*: ```csharp var rec = await approvalStore.FindAsync("slack:C12345.1709"); // approvalId == _objects.value_string // → ApprovalRecord { ConversationId, ToolName="delete_user", Approved=true, ApprovedBy="@vasya", DecidedAtUtc=... } ``` One query. Indexed. No JSON parsing. --- ### 4. Hard budget per conversation — $0.50 and the agent shuts up **Problem.** A loopy agent can run away — 50 tool-use iterations, $14 per conversation. **Solution.** `IBudgetEnforcer` (`Engine/Governance/IBudgetEnforcer.cs:8`) checks the limit **before** every iteration and **after** every response. `RedbCostBudgetStore` carries the running total across runs. ```csharp public sealed class HardBudgetEnforcer : IBudgetEnforcer { private readonly ICostBudgetStore _store; private static readonly AgentBudget Limit = new(0, 0, MaxCostUsd: 0.50m); public async ValueTask PreCheckAsync(string? convId, AgentBudget _, AgentUsage __, CancellationToken ct) { if (convId is null) return BudgetDecision.Allow; var u = await _store.GetUsageAsync(convId, ct); return u.CostUsd >= Limit.MaxCostUsd ? BudgetDecision.Stop($"conversation budget exhausted: ${u.CostUsd:F4}") : BudgetDecision.Allow; } public async ValueTask RecordAndCheckAsync(string? convId, AgentBudget _, AgentUsage delta, AgentUsage __, CancellationToken ct) { if (convId is null) return BudgetDecision.Allow; var total = await _store.AddAsync(convId, delta, ct); // ← upsert into CostBudgetProps return total.CostUsd >= Limit.MaxCostUsd ? BudgetDecision.Stop($"cost cap hit: ${total.CostUsd:F4}") : BudgetDecision.Allow; } } services.Replace(ServiceDescriptor.Singleton()); ``` `AddAsync` returns the **post-update** total — one redb round-trip both bumps the counter and tells you if you crossed the limit. On the next user request `PreCheckAsync` sees the budget is gone and the engine refuses **before** any provider HTTP call. **Cheap, because no provider charge is incurred.** --- ### 5. Idempotent tool retries — don't transfer money twice **Problem.** The agent invoked `transfer_money`, the network blipped, the retry policy retried the whole exchange. The tool runs twice → money transferred twice. **Solution.** `IToolIdempotencyStore` deduplicates by `(conversationId, toolUseId)`. `toolUseId` is the stable id the **model** itself returns in the tool_use block. Two retries — one tool_use_id — one real call: ```csharp // inside the tool bridge var res = await idempotencyStore.TryReserveAsync(convId, toolUseId, ct); if (!res.IsNew) return res.CachedOutputJson!; // ← short-circuit on retry var output = await ExecuteRealTransfer(input); await idempotencyStore.CompleteAsync(convId, toolUseId, output, ct); return output; ``` `RedbToolIdempotencyStore` keeps the reservation as an entry of redb.Route's idempotent repository (processor name `llm-tool-idempotency`) and the response body in `ToolIdempotencyProps`, both in the agent's redb (the `?redb=` instance, else the `AddRedbLlmStorage("")` one, else the context's default). Hit-rate, miss-rate and TTL evictions are emitted as OpenTelemetry counters on the shared `redb.Route` meter (`redb.route.llm.tool_cache.hits` / `.misses` / `.expired`, tagged with `llm.tool.name`) so the engine never writes to the row on a read — add `.AddMeter("redb.Route")` to your OTel pipeline and the dashboard is there. --- ### 6. Audit every tool call — what the agent tried and what blew up **Problem.** A month from now compliance asks: *"For client A on Nov 12, what tools did the agent call? How long did each take? Which failed?"* You need an answer **in a minute**, not a week. **Solution.** `RedbAuditObserver` writes one row into `ToolAuditProps` per `OnToolInvokedAsync` callback. Outcome is auto-classified: | `ctx.Skipped` | `ctx.Exception` | `Outcome` | | -------------- | --------------- | ---------- | | `true`, reason contains `"deni"` | — | `denied` | | `true`, otherwise | — | `skipped` | | `false` | non-null | `error` | | `false` | null | `success` | The compliance query is one LINQ line on indexed columns: ```csharp var failedToday = await redb.Query() .Where(p => p.ConversationId == clientConvId && p.Outcome == "error" && p.InvokedAtUtc >= DateTimeOffset.UtcNow.AddDays(-1)) .ToListAsync(); ``` One important detail — `RedbAuditObserver` **swallows** its own failures. If the DB is briefly unavailable, the agent **does not crash**. Audit is a best-effort layer; if it's load-bearing for compliance, stack a second observer that logs to file/Kafka and ships externally. --- ### 7. Branching — rewrite a turn and compare `RedbConversationStore` keeps messages as a **tree**, not a flat list. So: ```csharp var trunk = await store.AppendAsync(conv, parentId: null, userTurn1, meta); var v1 = await store.AppendAsync(conv, parentId: trunk, assistantA, meta); var v2 = await store.AppendAsync(conv, parentId: trunk, assistantB, meta); // sibling under same parent var pathV1 = await store.LoadPathAsync(conv, leafId: v1); // [user, assistantA] var pathV2 = await store.LoadPathAsync(conv, leafId: v2); // [user, assistantB] ``` This is **free** — not "yet another versions table", but native `_objects.parent_id`. Any other redb node in your system gets the same. For a prompt A/B-testing UI, the cost of this feature is exactly zero. --- ### 8. `From("llm://...")` — nightly agent with permanent memory ```csharp routes.From(Llm.Factory("claude") .Schedule("0 3 * * *") // every night at 3:00 .ConversationFromRoute() // RouteId becomes conversationId .InitialBody("ref:#daily-prompt") .AsUri()) .To("kafka://summaries.out"); ``` `ConversationFromRoute()` writes `?conversation=property` → producer uses `exchange.RouteId` as the conversation key. Every run is a new message **under the same conversation root**. A year later — a structured history of nightly runs with trends across `TotalCostUsd`, `RunCount`, `LastActivityAtUtc` (fields on `ConversationProps`): ```csharp var history = await redb.Query() .WhereRedb(p => p.ValueString == "morning-summary-route") .FirstOrDefaultAsync(); // history.Props.RunCount, .TotalCostUsd, .LastActivityAtUtc — straight to a dashboard ``` --- ## Schemas — how redb actually stores it Two rules pervade everything: 1. **Indexed scalars on `_objects`.** The fields you filter on (`ConversationId`, `ToolName`, `Outcome`, `Approved`) live as top-level `*Props` properties. redb materialises them into indexed columns on `_values` — `WhereRedb` hits the index, no JSON scan. 2. **Business key on `value_string` / `value_long`.** The visible identifier (conversation id, message id, approval id) lives in the indexed `_objects.value_string` column. The FK back to a tree root lives in `_objects.value_long`. No JSON marshalling for any of *our* fields. | Schema | `[RedbScheme]` | Top-level (indexed) | Notes | | --- | --- | --- | --- | | `ConversationProps` | `LLM Conversation` | TenantId, Title?, Status, StartedAtUtc, LastActivityAtUtc, TotalInputTokens, TotalOutputTokens, TotalCostUsd, RunCount | tree-root; `value_string` = conversation id | | `MessageProps` | `LLM Conversation Message` | Role, Iteration, CreatedAtUtc, ProviderId?, ModelId?, StopReason?, ToolUseId?, InputTokens, OutputTokens, Content[] | tree-child; `value_long` = root id; `Content` is a typed array of `MessageContentBlock` | | `ApprovalProps` | `LLM Approval` | ConversationId?, ToolName, ToolUseId, Approved, Reason?, ApprovedBy?, DecidedAtUtc, InputJson | one row per decision | | `CostBudgetProps` | `LLM Cost Budget` | PeriodStartUtc?, InputTokens, OutputTokens, CostUsd, UpdatedAtUtc | one row per conversation; `value_string` = conv id | | `ToolCacheProps` | `LLM Tool Cache` | ToolName?, OutputJson, CreatedAtUtc, ExpiresAtUtc? | `value_string` = `{conv}:{toolUseId}`; hit/miss/expire counts live on the `redb.Route` OTel meter, not in the row | | `ToolAuditProps` | `LLM Tool Audit` | ConversationId, MessageId?, ToolName, ToolUseId, InvokedAtUtc, DurationMs, Outcome, SkipReason?, InputJson, OutputJson?, ErrorMessage? | one row per invocation | | `KnowledgeChunkProps` | `LLM Knowledge Chunk` | ChunkId, Collection?, Text, Embedding[], Dimension, MetadataJson?, UpdatedAtUtc | Phase 2 RAG; `Embedding` is a native `float[]` | | `PromptTemplateProps` | `LLM Prompt Template` | Name, Version, Body, Description?, CreatedAtUtc | Phase 2; `(Name, Version)` is the business key | | `EvalRunProps` | `LLM Eval Run` | RunId, Scenario, AgentFingerprint, Score?, InputTokens, OutputTokens, CostUsd, CreatedAtUtc, Iterations[] | Phase 3; `Iterations` is a typed metric array | `MessageProps.Content` is a typed array of `MessageContentBlock` (`Kind` ∈ `text` / `tool_use` / `tool_result` / `thinking`) — no JSON serialisation for **our own** fields. Foreign JSON (tool input, tool output) is stored as `string` on `InputJson` / `OutputJson` only when the structure isn't ours. A `thinking` block keeps the model's reasoning in `ThinkingText`, with `Signature` (Anthropic) and `RedactedData` (`redacted_thinking`) beside it; `Text` belongs to the `text` kind only. The provider and model that produced the turn are the message's own `ProviderId` / `ModelId`. A block type or a stored kind the store has no form for is an error, on write and on read. --- ## Stores and interfaces — reference All interfaces live in `redb.Route.Llm.Engine.Storage`. Implementations live in `redb.Route.Llm.Storage.Redb`. ```csharp public interface IConversationStore { Task AppendAsync(string convId, string? parentMessageId, LlmMessage message, ConversationMessageMeta meta, CancellationToken ct); Task> LoadPathAsync(string convId, string? leafId = null, CancellationToken ct); Task> LoadTreeAsync(string convId, CancellationToken ct); } public interface IApprovalStore { Task RecordAsync(ApprovalRequest req, ApprovalDecision decision, CancellationToken ct); Task FindAsync(string approvalId, CancellationToken ct); } public interface ICostBudgetStore { ValueTask GetUsageAsync(string convId, CancellationToken ct); ValueTask AddAsync(string convId, AgentUsage delta, CancellationToken ct); ValueTask ResetAsync(string convId, CancellationToken ct); } public interface IToolIdempotencyStore { Task TryReserveAsync(string convId, string toolUseId, CancellationToken ct); Task CompleteAsync(string convId, string toolUseId, string outputJson, CancellationToken ct); Task ReleaseAsync(string convId, string toolUseId, CancellationToken ct); } public interface IAgentObserver // engine fires these on lifecycle events { Task OnRunStartedAsync(AgentRunContext, CancellationToken); Task OnIterationCompletedAsync(AgentIterationContext, CancellationToken); Task OnToolInvokedAsync(AgentToolInvocationContext, CancellationToken); // ← audit row written here Task OnRunCompletedAsync(AgentRunCompletedContext, CancellationToken); } ``` `RedbConversationStore` uses **server-side** tree primitives end-to-end: - `redb.CreateChildAsync(child, parent)` — tree integrity at the DB level. - `redb.TreeQuery(rootObj).ToFlatListAsync()` — every descendant in one query, no parent/children pointer-building. - `redb.GetPathToRootAsync(leaf)` — ancestor walk in **root → leaf** order. Latest-leaf detection scopes a `TreeQuery` to the conversation root, applies `.WhereLeaves()`, orders by `CreatedAtUtc DESC` and takes one. Cheap, because a conversation tree is usually small (tens of messages). --- ## Operational gotchas - **Cost-budget isn't atomic across processes.** Two app instances racing on `AddAsync` may lose an increment. If a cluster-wide hard cap is critical, back `ICostBudgetStore` with a SQL row using `SELECT ... FOR UPDATE`. The default store assumes single-instance / eventual consistency. - **Audit is best-effort.** `RedbAuditObserver` swallows failures. If audit **must** land, log to a file/Kafka via a second observer and ship out. - **The idempotency store needs a redb it can open.** `RedbToolIdempotencyStore` keeps reservations and outputs in the agent's redb; a context with none fails at the first reserved tool call with a message naming `AddRedbLlmStorage`. - **Cleanup — only roots and flat schemas.** `DeleteWithPurgeAsync` cascades soft-delete down the tree. Pass only `ConversationProps.id` — `MessageProps` descendants ride along automatically. **Never** `DELETE FROM _objects` — you'd wipe data from neighbouring tests or other services sharing the schema. - **Cross-TFM parallel tests.** Storage integration tests run net8/9/10 concurrently against the same DB — so each test uses a unique `convId = $"c-{Guid.NewGuid():N}"` and queries are scoped via `Where(p => p.ConversationId == ...)`. Don't write a bare `ToListAsync()` without a predicate — you'll see other TFMs' rows. - **Postgres Pro free tier.** All 16 storage tests fit inside the 1024-query free-tier budget on a single run. - **Both streaming modes run the agent loop, stores included.** `stream=calls` makes every model call a stream inside the route; `stream=body` makes the run when the body is read, after the route. Either way `RedbConversationStore`, `RedbApprovalStore`, `RedbCostBudgetStore`, `RedbToolIdempotencyStore` and `RedbAuditObserver` see a streamed turn as they see any other. The `stream=body` run reads the exchange's redb scope after the route, so the body must be read before the exchange ends, and it is refused inside `.Transacted()`. --- ## What's next — Phase 2 / 3 The schemas are already declared — the stores follow: | Phase | Schema | Adds | | ----- | ----------------------- | ------------------------------------------------------- | | 2 | `KnowledgeChunkProps` | `IKnowledgeStore` — RAG retrieval over the embedding column | | 2 | `PromptTemplateProps` | versioned `IPromptTemplateRegistry` (currently in-memory) | | 2 | `ToolCacheProps` (+TTL) | a dedicated `IToolCacheStore` for deterministic tools | | 3 | `EvalRunProps` | `IEvalRunStore` for leaderboard queries (scenario × fingerprint) | All of them plug in via the **same** one-line `AddRedbLlmStorage()` — no migrations, no DSL breakage. --- ## See also - [README.md § Persistence — `AddRedbLlmStorage()`](../README.md#persistence--addredbllmstorage) — the short registration form - [USER-GUIDE.md § Storage & Persistence](USER-GUIDE.md#storage--persistence) — where storage lands in the long guide - `redb.Route/tests/redb.Route.Tests.Llm/Storage/` — 16 integration tests, one per store - `Storage/Redb/Schemas/` — POCOs with `[RedbScheme]` attributes - `Engine/Storage/` — interfaces and in-memory defaults - `Engine/Governance/` — `IApprovalGate`, `IBudgetEnforcer`, the extension points Path: redb-route/redb.Route.Llm/doc/USER-GUIDE.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/doc/USER-GUIDE.md ---- # redb.Route.Llm — Connector User Guide > **Audience:** C# developers who already think in routes — Apache Camel, redb.Route, MassTransit, NServiceBus — and want a Large Language Model to be just one more endpoint in the pipeline. > > **What this is:** the canonical reference for how the `llm://` scheme works, how tools-as-routes work, how dynamic prompts work, what each provider needs, and how the test suite proves all of it against real APIs (including Claude). --- ## Table of contents 1. [The five-second pitch](#the-five-second-pitch) 2. [Mental model — connector, not SDK](#mental-model--connector-not-sdk) 3. [Architecture in one diagram](#architecture-in-one-diagram) 4. [Quick start](#quick-start) 5. [The four DSL shapes](#the-four-dsl-shapes) - [`.To("llm://…")` — model as a pipeline step](#1-tollm--model-as-a-pipeline-step) - [`From("llm://…")` — scheduled agent (consumer)](#2-fromllm--scheduled-agent-consumer) - [`.Llm("name", b => …)` — inline C# sugar](#3-llmname-b---inline-c-sugar) - [`.AsLlmTool("name")` — turn any route into a tool](#4-asllmtoolname--turn-any-route-into-a-tool) 6. [Headers vs URI options — per-message overrides](#headers-vs-uri-options--per-message-overrides) 7. [Dynamic prompts — the `#`-registry pattern](#dynamic-prompts--the--registry-pattern) 8. [Tool dispatch deep dive](#tool-dispatch-deep-dive) 9. [Pre-built homeless tools](#pre-built-homeless-tools) 10. [Provider matrix — 14 OpenAI-compat backends](#provider-matrix--14-openai-compat-backends) 11. [Spotlight: Anthropic Claude](#spotlight-anthropic-claude) 12. [URI parameter reference](#uri-parameter-reference) 13. [Headers reference](#headers-reference) 14. [Observability — headers, OTel, tsak.web](#observability--headers-otel-tsakweb) 15. [Streaming (`stream=calls` / `stream=body`)](#streaming-streamcalls--streambody) 16. [Storage & Persistence](#storage--persistence) 17. [Testing strategy](#testing-strategy) 18. [Apache Camel comparison](#apache-camel-comparison) 19. [Roadmap](#roadmap) 20. [FAQ](#faq) --- ## The five-second pitch ```csharp .From("kafka://orders") .To(Llm.Factory("claude").Temperature(0.2).MaxTokens(1024).AsUri()) .To("kafka://orders.translated"); ``` That single fluent-DSL line is a fully wired LLM call: - the inbound message body becomes the user prompt; - the agent loop runs against the provider configured in factory `claude`; - the assistant text replaces `exchange.Out.Body`; - token usage, model id, stop reason and tool iterations land in headers; - OpenTelemetry traces and metrics light up automatically; - the endpoint is visible in the tsak.web dashboard with msg/sec, average duration, error rate and last-error info — like every other connector in redb.Route. No new framework to learn, no new conversation layer, no new retry/idempotency story. The LLM is *already* a redb.Route endpoint. --- ## Mental model — connector, not SDK Most C# LLM libraries — `Anthropic.SDK`, `OpenAI`, `LLamaSharp`, `LangChain.NET` — are direct API clients. They own retries, conversation state, tool dispatch, observability. Sometimes well, often partially, almost always incompatible with each other. The redb.Route engine *already has* every primitive an LLM caller needs: | Concern | DSL primitive | | --- | --- | | Retry / backoff | `RedeliveryPolicy`, `OnException` | | Rate limiting | `Throttle` | | Resilience | `CircuitBreaker` | | Idempotency | `IdempotentConsumer` | | Compensation | `Saga` | | Audit / shadow | `WireTap`, `Multicast` | | Tracing & metrics | `RouteActivitySource`, `RouteMetrics` | | Persistence | `redb` schemes (typed object engine) | **Wrapping an LLM as just another connector means every one of those primitives applies for free.** No retries reinvented, no breakers reinvented, no dashboards reinvented. One connector, the entire engine carries it. That is the whole architectural argument. The rest of this guide is consequences. --- ## Architecture in one diagram ```text exchange ──► LlmEndpoint ──► LlmProducer ──► AgentEngine ──► ILlmProvider │ (HTTP) ▼ tool loop (optional) │ ▼ IToolDescriptorRegistry ──► RouteToolBridge │ ▼ IProducerTemplate │ ▼ any redb.Route route mounted with .AsLlmTool("name") ``` | Piece | Role | | --- | --- | | `LlmComponent` | Registers itself for scheme `llm`. One scheme, by design. | | `LlmEndpoint` | Created from `llm://?...`. Resolves the named factory, owns options, exposes `IEndpointStatistics` for tsak.web. | | `LlmConnectionFactory` | POCO with `Provider`, `ModelId`, API key (or secret-ref), tuning defaults. `Build()` produces an `ILlmProvider`. | | `ILlmProvider` | The only thing that talks HTTP. Production: `OpenAiProvider` (covers 14 vendors). Tests: `StubProvider` and `FakeProvider`. | | `IAgentEngine` | The tool-use loop. One inbound exchange = one agent run = N provider calls. Handles iterations, transcript, tool dispatch, governance hooks. | | `IToolDescriptorRegistry` + `RouteToolBridge` | Tools-as-routes machinery. | | `IPromptTemplateRegistry` | Versioned prompt store backing the `#`-ref resolver. | | `Fluent/Llm.cs` | `Llm.Factory("...")` builder used to compose the URI. | | `Extensions/...` | Sugar: `route.Llm("factory", b => ...)` for inline LLM steps; `.AsLlmTool(...)` for tool registration. | --- ## Quick start ### 1. Register ```csharp services.AddRedbRoute(route => { route.Services.AddRedbRouteLlm(); route.Services.AddLlmConnectionFactory("claude", f => { f.Provider = "anthropic"; // resolves to https://api.anthropic.com/v1/ f.ModelId = "claude-haiku-4-5"; f.ApiKeySecretRef = "anthropic.api-key"; f.Temperature = 0.2; f.MaxTokens = 1024; }); route.AddRouteBuilder(); }); ``` `AddRedbRouteLlm()` registers `IAgentEngine`, `IToolDescriptorRegistry`, `InMemoryPromptTemplateRegistry`, `LlmComponent`, and the inline-`.Llm()` extension wiring. One line — everything you need. ### 2. Use it ```csharp public sealed class MyRoutes : RouteBuilder { public override void Configure() { From("kafka://orders") .To("llm://claude?temperature=0.1&maxTokens=512") .To("kafka://orders.translated"); } } ``` That's the full minimum-viable shape. From here, everything else is variations. --- ## The four DSL shapes ### 1. `.To("llm://…")` — model as a pipeline step This is the most common shape: the producer treats the inbound message as **one user turn**, runs the agent loop to completion, and writes the assistant text into `Out.Body`. ```csharp From("kafka://orders") .To("llm://claude?temperature=0.1&maxTokens=512&conversation=header") .To("kafka://orders.translated"); ``` What happens, step by step: 1. **Input.** `exchange.In.Body` is wrapped as a single `LlmTextBlock`. Any other type is `.ToString()`'d. 2. **Tools.** The `?tools=` parameter is parsed: missing/empty = no tools, `*` = every tool in the registry, CSV = named tools only. 3. **Agent loop.** `AgentEngine.RunAsync` cycles `provider call → optional tool_use → RouteToolBridge dispatch → next call → …` until `EndTurn`, `MaxIterations`, or cancellation. 4. **Output.** Assistant text in `Out.Body`. Headers populated with usage, model id, stop reason, tool iterations. This is the shape to use when "an LLM call is one stage of a longer pipeline" — Kafka in, Kafka out, with an LLM in the middle. ### 2. `From("llm://…")` — scheduled agent (consumer) `From("llm://factory?schedule=...")` is **not** "listen for replies" (LLMs are pull, not push). It is a scheduler that fires a fresh agent run every interval and pushes the assistant reply down the rest of the route as a normal exchange. ```csharp From("llm://groq?schedule=5m" + "&systemPromptRef=#watchdog-system" + "&initialBodyRef=#daily-brief" + "&tools=*") .To("rabbitmq://alerts"); ``` Use cases: - **Watchdog agents** — every five minutes, the agent checks health endpoints (via tools), produces a verdict, drops it on a queue. - **Scheduled report generation** — every morning at 8:00, the agent summarizes yesterday's traffic and emails it. - **Self-improving agents with conversation memory** — the agent's own previous replies are part of its context (with `conversation=property`). `?schedule=` accepts simple intervals: `500ms`, `30s`, `5m`, `1h`. For cron expressions, prefer `From("quartz://...").To("llm://...")` — Quartz is already a scheduler, no need to duplicate it inside the LLM consumer. The agent's user prompt comes from `?initialBodyRef=`; the system prompt comes from `?systemPromptRef=`. Both honour the `#`-ref pattern (see [Dynamic prompts](#dynamic-prompts--the--registry-pattern)). > **This is the shape no other ESB has.** Apache Camel's `langchain4j-*` family is producer-only — its "scheduled agent" pattern is `from("timer:...").to("langchain4j-chat:...")`, which couples *what fires the agent* and *what the agent says* into the same route. We treat the LLM endpoint itself as a scheduler. ### 3. `.Llm("name", b => …)` — inline C# sugar When the LLM step is just an inline transformation, skip the URI: ```csharp From("seda://drafts") .Llm("claude", x => x .WithSystemPrompt("Rewrite the user's text in formal English. Reply with text only.") .WithTemperature(0.0) .WithMaxTokens(800)) .To("seda://drafts.formal"); ``` `Llm(...)` is a thin extension over `Process(Func)`. It calls `IAgentEngine.RunAsync` directly — same result as `.To("llm://...")`, but compiler-checked parameters, IntelliSense for tuning options, no URI escaping. **Trade-off:** inline `.Llm(...)` requires `exchange.ServiceProvider` to resolve `IRouteContext` at runtime. Inside a hosted route this is automatic; in unit tests, build the exchange via `Exchange.Create(msg, scopeFactory)` so the service provider flows through. ### 4. `.AsLlmTool("name")` — turn any route into a tool > **Tools are routes.** A tool is an ordinary `RouteBuilder` route mounted with one extra DSL aspect: `.AsLlmTool("name")`. ```csharp r.From("rabbitmq://orders.lookup") .AsLlmTool("lookup_order") .Description("Look up an order by id from the orders queue.") .Input("{ \"orderId\": \"string\" }") .Process(e => e.Out!.Body = ResolveOrder(e.In.Body)); ``` That's the tool. The agent loop discovers it through `IToolDescriptorRegistry`, and when the model emits a `tool_use` block with `name: "lookup_order"`, `RouteToolBridge` invokes the route as request/reply. Whatever lands in the final `Out.Body` is handed back to the model as the tool result. This is **the architectural decision** that makes the connector cross-cutting: every existing redb.Route component (Kafka, RabbitMQ, HTTP, SQL, file, redb, …) becomes a potential LLM tool with one method call. **No per-connector LLM package, ever.** `0 bumps` across 22 connectors. ### Which shape to pick | Use case | Pick | | --- | --- | | Mixed-transport pipeline (Kafka → llm → SQL) | `To("llm://…")` | | Multiple LLM hops with different prompts | `To("llm://…")` + `Process` for headers | | One-off inline call from C# code | `.Llm(name, b => …)` | | Periodic agent that *generates* messages | `From("llm://…?schedule=…")` | | Make any existing route callable by the model | `.AsLlmTool("…")` after `.From(...)` | --- ## Headers vs URI options — per-message overrides Per-message headers always win over URI options. This lets a single endpoint URI handle many variations without rewrites: ```csharp .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Reply in French.") .To("llm://claude?systemPromptRef=defaultPrompt") // header wins for THIS message ``` Two LLM hops in a row, different system prompts, same connection factory, no URI proliferation: ```csharp From("direct:translate-then-summarize") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Translate to English. Reply with translation only.") .To("llm://claude") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Summarize in one sentence.") .To("llm://claude") .To("seda://summaries"); ``` The URI is unchanged; only the header changes between hops. This is *the* pattern when the same factory is used for multiple steps with different prompts. --- ## Dynamic prompts — the `#`-registry pattern `?initialBodyRef=` and `?systemPromptRef=` carry the framework-wide **registry-ref convention**: a leading `#` turns the value into a lookup key instead of a literal. This matches how Kafka/S3/Firebase already resolve `#name` connection factories from `IRouteContext.GetFromRegistry`. ### Resolution order For a value `"#daily-brief"`: 1. **`IPromptTemplateRegistry`** — if a template named `daily-brief` exists, the latest version's body wins. Templates are versionable, so eval replays bind to a specific revision. 2. **`IRouteContext` registry** — fallback to a plain string registered via `ctx.AddToRegistry("daily-brief", "...")`. 3. If neither resolves, the result is `null` (treated as empty user prompt / no system prompt). Plain values without a `#` prefix are passed through verbatim — backwards compatible with the literal-string usage. ### Why this matters: prompt-as-mutable-data It decouples **who owns the prompt** from **who calls the model**. One route refreshes the value on its own schedule, another route consumes it. They share nothing but a name in the registry. ```csharp // Route A — refreshes the prompt every minute from the database. From("timer://refresh-prompt?period=1m") .Process(async (e, ct) => { var fresh = await _db.LoadDailyBriefAsync(ct); e.Context.AddToRegistry("daily-brief", fresh); }); // Route B — agent ticks every 5 minutes, picks up whatever the latest brief is. From("llm://groq?schedule=5m" + "&initialBodyRef=#daily-brief" + "&systemPromptRef=#watchdog-system" + "&tools=*") .To("rabbitmq://alerts"); ``` Route B never changes. Route A can be replaced with a Kafka consumer, an HTTP webhook, an S3 polling job — the agent route doesn't care. ### Versioned templates Same syntax, but resolved through `IPromptTemplateRegistry`: ```csharp await templates.SetAsync(new PromptTemplate { Name = "watchdog-system", Version = "v3", Body = "You are an SRE watchdog. Reply with PASS or FAIL only." }); // Then ?systemPromptRef=#watchdog-system picks v3 (the latest) at every tick. ``` Eval replays can bind to a specific version (`?systemPromptRef=#watchdog-system@v2`) — coming in Phase 2 with explicit version pinning. --- ## Tool dispatch deep dive When `.AsLlmTool("name")` is added after `.From(...)`, three things happen: 1. The route's `From()` URI is captured. 2. A `RouteToolBridge` is built that wraps the URI and a description into an `ILlmToolDescriptor`. 3. The descriptor is registered against `name` in `IToolDescriptorRegistry`. When the model emits a `tool_use` block at runtime: 1. `AgentEngine` looks up the descriptor by name. 2. The bridge builds an `IMessage` with the input JSON body. 3. `IProducerTemplate.RequestBody(uri, msg)` invokes the route as request/reply. 4. The route runs end-to-end. Whatever lands in `exchange.Out.Body` (or `In.Body` when `Out` is null) at the end of the pipeline is serialized and handed back to the model as the tool result. That last point is critical: **the tool's result is the final body of the route**, not the body of any specific `.To(...)`. Three patterns work: ### Pattern A — explicit response in a final `.Process` (most predictable) ```csharp r.From("direct:tool-lookup") .AsLlmTool("lookup") .Description("Look up the magic word for a key.") .Input("""{"type":"object","properties":{"key":{"type":"string"}},"required":["key"]}""") .Process(e => { var input = JsonSerializer.Deserialize((string)e.In.Body!); var result = DoLookup(input); e.Out ??= e.In.Clone(); e.Out.Body = JsonSerializer.Serialize(result); // ← returned to the model }); ``` This is what live tests use because it makes assertions trivial. ### Pattern B — request/reply `.To` populates `Out.Body` itself ```csharp r.From("direct:tool-customer") .AsLlmTool("get_customer") .To("redb://customers/getById"); // Out.Body = customer JSON ``` When the underlying connector is request/reply (HTTP, redb, SQL), it already populates `Out.Body`. The route is one line. ### Pattern C — fire-and-forget `.To` with a manual response ```csharp r.From("direct:tool-publish") .AsLlmTool("publish_event") .Process(e => e.In.Body = BuildKafkaPayload(e.In.Body)) .To("kafka://events") .Process(e => { e.Out ??= e.In.Clone(); e.Out.Body = "{\"ok\":true}"; // ← what the model sees }); ``` When the underlying transport is fire-and-forget (Kafka, RabbitMQ publish), append a `.Process` that fabricates a response body. The model sees `{"ok":true}` and moves on. ### Tool filter: the `?tools=` parameter | Value | Meaning | | --- | --- | | (omitted) | no tools, plain chat | | `*` | every tool in `IToolDescriptorRegistry` | | `lookup_order,publish_event` | explicit allow-list | Per-call filtering matters: an agent that does customer lookup should not also have access to `publish_payment`, even if both routes are mounted. The filter lives on the URI, so different LLM endpoints can expose different tool subsets from the same registry. --- ## Pre-built homeless tools These ship in `redb.Route.Llm.Tools` (a separate package — homeless tools that don't have a natural connector home). ### `HttpFetchTool` A safe, allow-listed HTTP `GET`. The model passes `{"url":"…"}`, the tool fetches, returns body + status. ```csharp context.AddService(typeof(ILlmToolDescriptor), new HttpFetchTool(new HttpFetchOptions { HostAllowlist = new[] { "api.example.com", "docs.example.com" }, Timeout = TimeSpan.FromSeconds(5), MaxBytes = 256 * 1024 })); r.From("direct:agent") .To(Llm.Factory("claude").Tools("http_fetch").AsUri()) .To("mock:done"); ``` `HostAllowlist` is enforced before the request is made — out-of-list URLs come back as a tool error without ever leaving the process. This is the recommended way to give an agent the open web *with a leash*. ### Coming soon > The next session will add three deps-free utility tools and one HTTP-backed search tool: > > - **`JsonPathTool`** — extract a value by JSONPath from inbound JSON. > - **`RegexExtractTool`** — capture-by-name from inbound text. > - **`MathEvalTool`** — shunting-yard arithmetic, no `NCalc`, no eval injection. > - **`WebSearchTool` (Tavily)** — `https://api.tavily.com/search` with API key. Plus a brand-new `redb.Route.Exec` connector for shell commands, with `.AsLlmTool("shell")` as the natural LLM-side mounting point. See the comparison with Camel: their `camel-exec` is producer-only; we add a scheduled-consumer mode using the same `PeriodicTimer` pattern as `LlmConsumer`. --- ## Provider matrix — 14 OpenAI-compat backends One `OpenAiProvider` class, fourteen vendors. The only thing that changes is the base URL and (sometimes) auth-header quirks. | `Provider` value | Base URL | Notes | | --- | --- | --- | | `openai` | `https://api.openai.com/v1/` | Default. The reference implementation. | | `anthropic` / `claude` | `https://api.anthropic.com/v1/` | **Claude via the official OpenAI-compat endpoint.** Live-tested with Haiku 4.5 and Sonnet 4.6. See [the spotlight](#spotlight-anthropic-claude). | | `groq` | `https://api.groq.com/openai/v1/` | Fast Llama 3 / Llama 3.3, free tier. Strict-assertion test target. | | `cerebras` | `https://api.cerebras.ai/v1/` | Llama 3.1 70B, very fast. | | `openrouter` | `https://openrouter.ai/api/v1/` | Aggregator. Adds `HTTP-Referer` + `X-Title` headers automatically. | | `gemini` / `google` | `https://generativelanguage.googleapis.com/v1beta/openai/` | Gemini's own OpenAI-compat surface. | | `github-models` / `github` | `https://models.inference.ai.azure.com/` | GitHub Models. | | `mistral` | `https://api.mistral.ai/v1/` | Mistral Small / Large. | | `together` | `https://api.together.xyz/v1/` | Together AI. | | `huggingface` / `hf` | `https://router.huggingface.co/v1/` | HF inference router. | | `deepseek` | `https://api.deepseek.com/v1/` | DeepSeek. | | `ollama` | `http://localhost:11434/v1/` | Local. No API key needed. | | `lmstudio` | `http://localhost:1234/v1/` | Local. | | any other / `custom` | falls through to `https://api.openai.com/v1/`, **override `BaseUrl`** | For self-hosted gateways (vLLM, llama.cpp server, in-house). | Adding a fifteenth vendor is a one-line change to `OpenAiProvider.ResolveDefaultBaseUrl`. ### Per-vendor configuration cheat-sheet ```csharp // OpenAI services.AddLlmConnectionFactory("openai", f => { f.Provider = "openai"; f.ModelId = "gpt-4o-mini"; f.ApiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY"); }); // Anthropic Claude (via OpenAI-compat endpoint) services.AddLlmConnectionFactory("claude", f => { f.Provider = "anthropic"; f.ModelId = "claude-haiku-4-5"; f.ApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY"); }); // Groq services.AddLlmConnectionFactory("groq", f => { f.Provider = "groq"; f.ModelId = "llama-3.3-70b-versatile"; f.ApiKey = Environment.GetEnvironmentVariable("GROQ_API_KEY"); }); // Local Ollama — no key services.AddLlmConnectionFactory("local", f => { f.Provider = "ollama"; f.ModelId = "qwen2.5:7b"; }); // In-house gateway services.AddLlmConnectionFactory("inhouse", f => { f.Provider = "custom"; f.BaseUrl = new Uri("https://llm-gateway.internal/v1/"); f.ModelId = "internal-model-v3"; f.ApiKey = ""; }); ``` --- ## Spotlight: Anthropic Claude Claude is the most reliable closed-source model the connector has access to, and the live-test suite uses it as the **strict-assertion** reference. Everything below is verified end-to-end against the real Anthropic endpoint at `https://api.anthropic.com/v1/`. ### Why Claude through OpenAI-compat (not native Messages API) Anthropic publishes an OpenAI-compatible endpoint that speaks the same `chat/completions` contract as OpenAI itself. That means **one line in `OpenAiProvider`** wires Claude in: ```csharp "anthropic" or "claude" => new("https://api.anthropic.com/v1/"), ``` — and our universal `OpenAiProvider` handles requests, responses, tool calls, streaming and finish reasons identically. No new provider class, no Anthropic SDK, no separate retry logic. A native `AnthropicProvider` (Messages API) **also ships** alongside the OpenAI-compat path — `f.Provider = "anthropic"` resolves to it. It exists to consume features the OpenAI-compat surface flattens away — notably the **true Messages-API SSE stream** (`message_start` / `content_block_delta` / `message_stop`), which is what `stream=body` against `provider=anthropic` delivers end-to-end via `HttpConsumer` / `WsConsumer`. **For non-streaming chat / tool-use, either path is fine.** Pick OpenAI-compat for vendor portability, pick native Anthropic for the streaming and Messages-API-only features (prompt caching, computer-use, fine-grained image blocks) as they land. ### Models The Claude family rolls forward continuously. Model IDs the connector has been tested against: | Model | Use case in tests | Why | | --- | --- | --- | | `claude-haiku-4-5` | Strict literal-token chat, tool-use loop | Smaller, fastest, cheapest. Reliably follows "reply with the literal token X". | | `claude-sonnet-4-6` | Two-hop translation/summarization chain | Bigger, more degrees of freedom. Used for fuzzy assertions ("French-shaped output"). | | `claude-opus-4-7` | (Available; not used in CI for cost reasons) | Top-of-stack for complex agentic work. | ### What lands in tests The `ClaudeChatTests` suite runs three scenarios. All three pass deterministically. **1. Literal-token chat (`Claude_Haiku_45_From_To_Mock_DeliversAnswer`)** — system prompt asks for the literal token `pong`, user sends `ping`, the assertion is `reply.Should().Contain("pong")`. Haiku 4.5 returns exactly `pong` in ~800ms. ```csharp [EnvFact("REDB_LLM_ANT_API03_KEY")] public async Task Claude_Haiku_45_From_To_Mock_DeliversAnswer() { await using var host = LiveLlmHost.Build() .AddFactory("claude", new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-haiku-4-5", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"), Temperature = 0.0, MaxTokens = 32 }); await host.StartAsync(r => { r.From("direct:chat") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Reply with the literal token 'pong' and nothing else. No punctuation.") .To(LlmDsl.Factory("claude").Temperature(0.0).MaxTokens(8).AsUri()) .To("mock:result"); }); await host.SendAsync("direct:chat", "ping"); var sink = host.Mock("mock:result"); sink.ReceivedCount.Should().Be(1); var reply = ((string)sink.ReceivedExchanges[0].In.Body!).Trim().ToLowerInvariant(); reply.Should().Contain("pong"); } ``` **2. Tool-use loop (`Claude_Haiku_45_Tools_LookupAgent_UsesTool`)** — a `lookup` tool is mounted via `EchoToolRoute` (a `RouteBuilder` that registers `direct:tool-lookup` with `.AsLlmTool("lookup")`). The system prompt instructs Claude to call the tool first, then echo the answer. Claude calls the tool, captures the canned reply (`{"answer":"the magic word is rosebud"}`), and the final assistant message contains `rosebud`. ```csharp var lookup = new EchoToolRoute( toolName: "lookup", description: "Look up the magic word for a key.", inputSchema: """{"type":"object","properties":{"key":{"type":"string"}},"required":["key"]}""", replyJson: """{"answer":"the magic word is rosebud"}"""); await host.StartAsync(lookup, r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Use the lookup tool to find the magic word, then reply with that exact phrase. " + "Do not invent a word — call the tool first.") .To(LlmDsl.Factory("claude").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done"); }); await host.SendAsync("direct:agent", "What is the magic word?"); lookup.CapturedInputs.Should().NotBeEmpty(); // the tool was called final.Should().Contain("rosebud"); // the model echoed the result ``` **3. Two-hop chain (`Claude_Sonnet_46_TwoHopChain_SummarizeThenTranslate`)** — body flows through two `To("llm://…")` hops in a row. First hop summarizes English to one sentence. Second hop translates that sentence to French. No glue code between hops; the assistant text from hop 1 is the user message for hop 2. ```csharp r.From("direct:chain") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Summarize the user's text in one short English sentence.") .To(LlmDsl.Factory("claude").Temperature(0.0).MaxTokens(64).AsUri()) .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Translate the user's text to French. Reply with the translation only, no preamble.") .To(LlmDsl.Factory("claude").Temperature(0.0).MaxTokens(64).AsUri()) .To("mock:done"); ``` The assertion is loose — French-shaped output, not a specific translation — because Sonnet has more freedom on a fuzzy task than Haiku does on `"return pong"`. ### Production-readiness checklist for a Claude-backed route | Concern | What to do | | --- | --- | | API key in code | Don't. Use `LlmConnectionFactory.ApiKeySecretRef = "anthropic.api-key"` and resolve via your secret store. | | Rate limits | Wrap the `To("llm://...")` in `.Throttle(...)`. Anthropic has per-minute and per-day limits. | | Retries on 5xx | `.OnException().MaximumRedeliveries(3).Backoff(...)` — same as any other connector. | | Conversation memory | Set `LlmHeaders.ConversationId` on inbound messages (`conversation=header` on the URI). Store-backed memory is Phase 2. | | Token budget | Phase 2 governance hook. Today, hard-cap with `MaxTokens` on the factory and on the URI per-call. | | Cost observability | Read `llm.tokens.in` / `llm.tokens.out` headers, push to your metrics pipeline via `WireTap`. | --- ## URI parameter reference ```text llm:// ?temperature=0.2 &maxTokens=1024 &topP=0.9 &systemPromptRef= &initialBodyRef= # consumer only &conversation=none|header|property &stream=calls|body # producer only — calls: engine streams each call; body: HTTP→SSE, WS→per-frame &schedule=500ms|30s|5m|1h # consumer only &maxIterations=8 &tools=*|name1,name2 &connectionFactory= # alternative to the URI host ``` | Param | Producer (`To`) | Consumer (`From`) | Notes | | --- | --- | --- | --- | | `temperature`, `maxTokens`, `topP` | yes | yes | Floats / ints. Override factory defaults. | | `systemPromptRef` | yes (header beats it) | yes | Honours `#`-ref. | | `initialBodyRef` | n/a | yes | Honours `#`-ref. The consumer's user-prompt source. | | `conversation` | yes | yes (`header` resolves to none — consumer-born exchanges have no inbound header) | Future: persistent memory backends. | | `stream` | yes (`Out.Body = IAsyncEnumerable`) | n/a | Producer-only. End-to-end on the wire via `redb.Route.Http` (SSE with `event: done` summary trailer) and `redb.Route.WebSocket` (one text frame per token). See [Streaming responses](#streaming-responses-streamtrue). | | `schedule` | n/a | required | `500ms` / `30s` / `5m` / `1h`. | | `maxIterations` | yes | yes | Hard ceiling on tool-loop turns. Default 8. | | `tools` | yes | yes | `*`, CSV, or omitted. | --- ## Headers reference ### Headers the connector reads (per-message inputs) | Header | Equivalent URI param | Purpose | | --- | --- | --- | | `LlmHeaders.SystemPrompt` (`llm.system_prompt`) | `systemPromptRef` | Per-message system prompt. Wins over URI. | | `LlmHeaders.ConversationId` (`llm.conversation_id`) | n/a | Conversation correlation key. | | `LlmHeaders.Temperature` (`llm.temperature`) | `temperature` | Per-message override. | | `LlmHeaders.MaxTokens` (`llm.max_tokens`) | `maxTokens` | Per-message override. | ### Headers the connector writes (per-message outputs) | Header | Meaning | | --- | --- | | `llm.provider.id` | `"anthropic"`, `"openai"`, `"groq"`, `"stub"`, … | | `llm.model.id` | The actual model used (may differ from factory default if overridden). | | `llm.tokens.in` / `llm.tokens.out` | Token usage from `usage` field in the response. | | `llm.tool.iterations` | How many loop steps the agent took. | | `llm.stop_reason` | `EndTurn`, `ToolUse`, `MaxTokens`, `Other`. | | `llm.raw_stop_reason` | Vendor-native value (`"stop"`, `"tool_calls"`, `"length"`, `"content_filter"`). | | `llm.streaming` | `true` when the response body is an `IAsyncEnumerable` of token deltas. Set by `LlmProducer` for `stream=body`; downstream transports branch on it (or on `Out.Body` shape) to pick a streaming wire frame. | | `llm.cost.usd` | Estimated cost of the call in USD (when the model has a known price). Carried into the SSE `event: done` trailer alongside the token / stop-reason fields. | These flow downstream like any other headers — `WireTap` them to your metrics pipeline, branch on them, log them, persist them. --- ## Observability — headers, OTel, tsak.web The connector hooks into redb.Route's existing observability stack. Nothing extra to wire. **OpenTelemetry traces.** Every `LlmEndpoint` call is a span on `RouteActivitySource`. Tags include provider id, model id, token counts, iterations, stop reason. If your collector ingests redb.Route spans, LLM calls are already in there. **Metrics.** `LlmMetrics` registers a Counter (`llm.requests`) and Histogram (`llm.duration_ms`) on the shared Meter. Tagged by provider and model. **Endpoint statistics.** `LlmEndpoint` exposes `IEndpointStatistics`: `MessagesIn`, `MessagesOut`, `BytesIn`, throughput, `LastErrorMessage`, `HealthStatus`. `tsak.web` reads these the same way it reads from Kafka or RabbitMQ — no per-connector adapter. **Cost dashboards.** Persist `llm.tokens.in` / `llm.tokens.out` to your OLAP store via a `WireTap` route, multiply by the per-vendor rate, you have a cost dashboard. The connector doesn't ship a cost calculator (vendor pricing changes too often), but every input it needs is already on the message. --- ## Streaming (`stream=calls` / `stream=body`) Two modes, chosen with `stream=` on the URI (`.Stream(LlmStreamMode.Calls)` / `.Stream(LlmStreamMode.Body)` in the DSL): - **`stream=calls`** — the agent engine makes every model call as a stream, **inside the route**. Tools, the conversation, the budget, approvals, the audit and the route's `.Transacted()` work exactly as without streaming. The pieces go to `IAgentObserver.OnDeltaAsync` as the model writes them, visible text and thinking marked apart; `Out.Body` is the final text. The connection carries data the whole time, so a long answer survives tunnels and proxies that cut a silent connection, over HTTP/1.1 too. - **`stream=body`** — `Out.Body` is an `IAsyncEnumerable`, and the agent run — tools, conversation, budget, approvals, audit — happens **when the body is read**, after the route, the way a streamed SQL result is read. The visible text of every model call streams as the model writes it, for HTTP (SSE), WebSocket and gRPC consumers to forward; thinking stays out of the body. - Without `stream=` nothing is streamed. Any other value, `stream=true` included, is refused when the endpoint is created. Both modes are limited by `RequestTimeoutMs` as a whole call, and by `StreamIdleTimeoutMs` (off by default) for silence. ### The wire contract (`stream=body`) For user-facing chat surfaces a 4-second "please wait" before the assistant replies feels broken even when the total wall-clock is identical. `stream=body` runs token by token **end-to-end** — from provider HTTP SSE through the agent engine to the public HTTP or WebSocket consumer that fronts the route. `LlmProducer` puts the lazy body into `exchange.Out.Body`, sets `Out.ContentType = "text/event-stream"` (whatever type the request carried) and `Out.Headers["llm.streaming"] = true`. Late-bound summary headers — `llm.tokens.in`, `llm.tokens.out`, `llm.stop_reason`, `llm.tool.iterations` — are populated **after** the run completes (`llm.provider.id` and `llm.model.id` are populated up-front). Transports read these post-enumeration and surface them in a transport-appropriate way. > **The body belongs to its exchange.** The run reads the exchange's resources — the conversation store, the redb scope — so: > - it is read **once**: one read is one agent run, tools included, and a second read fails; > - it is released with the exchange (`ExchangeResources`): a read after the exchange ended fails, and a run still going when it ends is stopped; > - `ProducerTemplate.RequestBody` refuses it, because it ends the exchange before it returns: call `RequestAsync(endpoint, exchange)`, read the body, then dispose the exchange. The HTTP, WebSocket and gRPC consumers read it before they end the exchange; > - it is refused inside `.Transacted()`: the run happens after the block, so the block would commit before the answer exists and the tools would not join it. Use `stream=calls` inside a transaction. > > A failure of the run reaches the reader and is counted on the endpoint; the route's `OnException` does not see it, because the route has finished by then. Downstream transports inspect `Out.Body`: - `redb.Route.Http` (`HttpConsumer`): picks SSE or chunked plain text based on `Content-Type`, flushes per yield, sets the right "do-not-buffer-me" envelope. - `redb.Route.WebSocket` (`WsConsumer`): one `WebSocketMessageType.Text` frame per yield, `endOfMessage=true`, order preserved. - Anything else (Kafka, RabbitMQ, mock…): reads the body as the framework's default object — streaming becomes a stringified enumerable, which is rarely what you want. Streaming is meaningful only against transports that themselves have a streaming wire shape. ### Over HTTP — Server-Sent Events with a `done` trailer ```csharp From("http://+:8080/chat") .To("llm://claude?stream=body"); ``` The browser receives: ```text HTTP/1.1 200 OK Content-Type: text/event-stream Cache-Control: no-cache, no-transform X-Accel-Buffering: no Transfer-Encoding: chunked data: Hello data: , data: world data: ! event: done data: {"llm.tokens.in":12,"llm.tokens.out":4,"llm.stop_reason":"EndTurn","llm.tool.iterations":1,"llm.model.id":"claude-haiku-4-5","llm.provider.id":"anthropic"} ``` Key points: - `Cache-Control: no-cache, no-transform` defeats the gzip middleware that otherwise buffers the response for compression. - `X-Accel-Buffering: no` is the nginx hint that disables its proxy buffer — without it nginx holds the whole response until the upstream closes, defeating SSE. - `IHttpResponseBodyFeature.DisableBuffering()` turns off ASP.NET's own response buffer so each `WriteAsync` hits the socket immediately. - Empty / null yields are silently skipped — providers periodically emit empty keep-alive deltas that must not turn into empty wire chunks. - The terminal `event: done` frame's payload is a JSON object built from whichever `llm.*` summary headers are present on the message at end-of-stream (`llm.tokens.in`, `llm.tokens.out`, `llm.cost.usd`, `llm.stop_reason`, `llm.tool.iterations`, `llm.model.id`, `llm.provider.id`). Missing headers are simply omitted from the payload — the contract is "opportunistic": if your route enriches `Out.Headers` with a custom `llm.cost.usd` (e.g. in a `WireTap` to a pricing table), it lands in the trailer for free. - Client cancellation (`HttpClient.CancelPendingRequests`, tab close, browser navigation) propagates into the server-side `await foreach` via `HttpContext.RequestAborted`, so the upstream provider stream is torn down promptly. If the response Content-Type is something other than `text/event-stream`, the transport falls back to **chunked plain text**: one yield = one Transfer-Encoding chunk, no SSE framing, no trailer. Useful for clients that want progressive plain text without the SSE protocol layer (curl pipelines, log tails, etc.). ### Over WebSocket — one Text frame per token ```csharp From("ws://+:9001/chat") .To("llm://claude?stream=body"); ``` Each provider token delta becomes one `WebSocketMessageType.Text` frame with `endOfMessage=true`. Order is preserved (the per-connection receive loop awaits each `SendAsync` before reading the next inbound frame, so writes are naturally serial per socket); empty chunks are skipped; the cancellation token is the consumer's drain-safe `_drain.ProcessingToken`, so a streaming response completes during a graceful shutdown rather than being torn mid-message. The non-streaming path (`Out.Body` is a `string` / `byte[]` / etc.) is unchanged — one full response frame, just as in 3.1.0. > **Known limitation.** `WsConsumer.HandleWebSocket` currently does not echo a client-initiated Close frame — it returns on the first inbound Close without sending one back. Browser clients dispose the underlying socket cleanly, but C# `ClientWebSocket` callers that rely on `CloseAsync()` returning normally will see `remote party closed without handshake`. As a workaround, in tests rely on `using` / `Dispose` to tear down the connection instead of an explicit `CloseAsync`. This is unrelated to streaming and predates 3.1.1; a follow-up will echo the Close. ### Picking a streaming provider - **`AnthropicProvider`** (`Provider = "anthropic"`) reads true Anthropic Messages SSE (`message_start` / `content_block_delta` / `message_stop` events) and yields one string per text delta. This is the reference for what streaming "should" feel like. - **`OpenAiProvider`** (`Provider = "openai" | "groq" | "cerebras" | "gemini" | "mistral" | "openrouter" | ...`) consumes the universal OpenAI-compat `data: {...}\n\n` SSE shape and yields `choices[0].delta.content` chunks. Works the same against all 14 OpenAI-compatible vendors. - **`StubProvider`** has no streaming — it returns the whole reply as a single `await foreach` yield for deterministic tests. ### Tests that pin the contract - `redb.Route.Tests.Http/HttpStreamingTests` (4 tests) — verifies SSE framing, the `event: done` JSON payload, chunked-plain fallback, **progressive arrival** (asserts first chunk arrives well before the last yield is produced, proving no buffering), and that aborting the `HttpClient` request surfaces on the server-side enumerator within seconds. - `redb.Route.Tests.WebSocket/WsStreamingTests` (2 tests) — one-frame-per-yield, empty-chunk skipping. - `redb.Route.Tests.Llm/LiveStreamingTests` (env-gated, 6 providers) — each test asserts `ChunkCount > 1` (proves the wire is genuinely streamed, not faked from a buffered response), at least one text delta, the expected substring in the accumulated answer, and a non-null terminal `StopReason`. Skips when the relevant `REDB_LLM_*_KEY` env var is missing, same as `LiveProviderTests`. --- ## Storage & Persistence By default the agent loop is stateless — fast for tests, useless for production. **One DI line** swaps every state surface (transcripts, approvals, budgets, idempotency, audit) onto redb without touching a single route: ```csharp route.Services.AddRedbRouteLlm(); route.Services.AddRedbLlmStorage(); // ← persists everything to redb ``` After this call, your existing `.From("kafka://chat.in").To(Llm.Factory("claude").AsUri())` route starts writing every turn into a tree-structured `ConversationProps` + `MessageProps` schema, every tool call into `ToolAuditProps`, every approval decision into `ApprovalProps`, every accepted retry into `ToolCacheProps`. The join key is one header — `llm.conversation.id`. **For the why and the how** — concrete DSL recipes (multi-turn chat with `ConversationFromHeader()`, Slack-backed approval gates, hard cost caps via `IBudgetEnforcer`, idempotent tool retries, branching transcripts, scheduled `From("llm://…")` agents with persistent run history) and the full schema tour, see [`STORAGE.md`](STORAGE.md). --- ## Testing strategy The test suite lives in `redb.Route.Tests.Llm`. It splits into three layers: ### Layer 1 — wiring tests (no network) `LlmComponentTests`, `LlmEndpointTests`, `LlmProducerTests`, `LlmIntegrationTests`, `LlmServiceCollectionExtensionsTests`, `LlmBuilderTests`, `LlmConnectionFactoryTests`, `LlmEndpointOptionsTests`, `StubProviderTests`. Service registration, options binding, scheme registration, end-to-end with `FakeProvider`. Run on every `dotnet test`. ### Layer 2 — DSL showcase (live, gated by env) `DslShowcase/*Tests.cs`. Each file is the **smallest live shape that proves a single DSL claim**. They are written to be **read like documentation**. | File | DSL shape | Provider | | --- | --- | --- | | `BasicChatTests.cs` | `From("direct:chat") → To("llm://…") → To("mock:result")` | Groq, Gemini, Mistral | | `InlineLlmTests.cs` | `From("direct:chat") → .Llm("name", b => …) → To("mock:result")` | Groq, Mistral | | `ToolRouteTests.cs` | A `RouteBuilder` mounted with `.AsLlmTool(...)` is auto-discovered by the agent loop | Groq | | `HttpFetchToolTests.cs` | The pre-built `HttpFetchTool` plugs into a route with one line | Scripted | | `ChainedLlmTests.cs` | Two `To("llm://…")` hops carry the body forward | Groq | | `RegistryDrivenPromptTests.cs` | `?systemPromptRef=#name` resolves through the registry chain | Scripted | | `ClaudeChatTests.cs` | All shapes against Anthropic Claude — chat, tool-use, two-hop chain | **Anthropic Claude** | These tests are gated with `[EnvFact("REDB_LLM__KEY")]` — they're **skipped, not failed**, when the matching key is unset. A clean checkout still passes `dotnet test`. ### Layer 3 — provider-specific live tests `LiveProviderTests` for the older free-tier providers (Groq, Mistral, Cerebras, Gemini, OpenRouter), and `ClaudeChatTests` (the strict-assertion reference). ### How assertions are tuned per provider Different providers have different reliability. The test suite reflects this: | Provider | Assertion strictness | Why | | --- | --- | --- | | **Anthropic Claude (Haiku 4.5 + Sonnet 4.6)** | **Strictest** — literal tokens, tool-call captures | Reliably follows "reply with the literal token X" instructions. Used as the reference suite. | | Groq + Llama 3.3 70B | Strict — literal `pong` | Fast, free, reliable. | | Mistral / Cerebras | "Some non-empty reply" | Small free-tier models phrase things differently each call. | | Gemini / OpenRouter | "Some non-empty reply" + tolerance for 429 | Quotas; failures are usually quota artefacts, not connector regressions. | ### Test helpers worth knowing | Helper | Role | | --- | --- | | `LiveLlmHost` | Hand-rolled wiring of `RouteContext` + `LlmComponent` + `AgentEngine` + `IProducerTemplate` + `IToolDescriptorRegistry`. Lets a test stay close to a Camel-style example. | | `EchoToolRoute` | A `RouteBuilder` that mounts `direct:tool-{name}` with `.AsLlmTool(name)` and captures every input the agent passes. | | `LocalHttpServer` | Tiny in-process `HttpListener` server for testing HTTP-backed tools deterministically. | | `FakeProvider` | Scriptable `ILlmProvider`. `EnqueueText`, `EnqueueToolUse`, exposes `CallCount` and `CapturedRequests`. Network-free. | | `EnvLoader` | `[ModuleInitializer]` that loads `.env.local` once per process, never overwriting set variables. | | `EnvFactAttribute` | xUnit `FactAttribute` that sets `Skip` when the named env var is missing. | | `LiveLlmCollection` | xUnit `CollectionDefinition` with `DisableParallelization = true` — live tests don't race against shared free-tier quotas. | ### Adding a new live test — six-step recipe 1. Pick the smallest DSL shape that proves the new behavior. 2. Use `LiveLlmHost.Build()` and `.AddFactory(name, factory)`. 3. Tag: `[Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")]`. 4. Gate with `[EnvFact("REDB_LLM__KEY")]`. 5. Pick assertion strictness matching the provider's reliability. 6. Read the test out loud. If it sounds like prose, ship it. If it reads like wiring, simplify. --- ## Apache Camel comparison Camel's LLM story lives in a family — `camel-langchain4j-chat`, `-embeddings`, `-tokenizer`, `-tools`, `-agent`, `-web-search`, plus `camel-anthropic`, `camel-djl`, `camel-huggingface`. It's the closest analogue. ### What both ship | Capability | `camel-langchain4j-*` | `redb.Route.Llm` | | --- | --- | --- | | Chat completion endpoint | `langchain4j-chat://chatId?chatModel=#model` | `llm://factory` | | Tool dispatch into a route | `langchain4j-tools://name` (separate component) | `.AsLlmTool("name")` (DSL aspect on any `From(...)`) | | Agent loop | `langchain4j-agent://...` | built into `IAgentEngine` | | Scheduled invocation | only via `from("timer:...").to("langchain4j-chat:...")` — the LLM is producer-only | **`From("llm://factory?schedule=...")` is a first-class consumer** | | Streaming responses | LangChain4j streaming chat model | `stream=body` end-to-end: `Out.Body = IAsyncEnumerable`, `HttpConsumer` flushes as SSE with `event: done` summary trailer, `WsConsumer` as one text frame per token | | Registry refs (`#name`) | yes — Camel-wide | yes — framework-wide; works for connection factories *and* prompts | | Provider matrix | 25+ via LangChain4j (Anthropic, Bedrock, Vertex, Azure OpenAI, OpenAI, Mistral, Ollama, …) | 14 OpenAI-compatible behind one `OpenAiProvider` (incl. Anthropic Claude live-tested) | | Embeddings / vector store | yes — `langchain4j-embeddings` + LangChain4j vector stores | Phase 2 (`embed://`, `vector://` schemes planned) | ### Where redb.Route.Llm wins - **`From("llm://...")` is a first-class consumer.** No equivalent in the LangChain4j family — every component there is producer-only. Self-driven agents in one declarative line. - **One scheme.** `llm://` and only `llm://`. Streaming, tools, scheduling and conversation are query options on the same endpoint — not five sibling components. - **Tools are routes, not a separate component.** `.AsLlmTool("name")` is one DSL aspect. `0 bumps for 22 connectors`. - **One `OpenAiProvider` for 14 vendors.** Adding a vendor is a base-URL change, not a new package. - **`#`-registry refs apply to prompts.** Versioned prompts and "another route refreshes the prompt" both work without modifying the LLM route. - **Endpoint statistics for free.** Every `LlmEndpoint` exposes `IEndpointStatistics` the same as Kafka or RabbitMQ; tsak.web renders it with no extra wiring. - **Small dependency graph.** `redb.Route` + `Microsoft.Extensions.*` + `System.Text.Json`. No LangChain wrapper, no vendor SDKs. ### Where Camel `langchain4j-*` wins today - Wider provider matrix (Bedrock, Vertex, Azure OpenAI with native auth). - Embeddings, RAG, document loaders, web search shipping today (we're Phase 2). - Chat memory stores in the box. ### Architectural differences worth knowing - **Wrapper vs. transport.** Camel's `langchain4j-*` is an adapter over LangChain4j; we talk HTTP directly through `ILlmProvider` and own our agent loop. - **One scheme vs. one component per primitive.** Camel mirrors LangChain4j's type system at the URI layer. We collapse those into options on a single endpoint. - **Tool registration philosophy.** Camel exposes tools via a dedicated URI; we annotate routes with `.AsLlmTool`. Practical consequence: zero coordination across connector packages to support LLM tools. - **Prompt-as-data.** We route prompts through a versioned registry (`#name`) by default. Camel does this with custom processors. --- ## Roadmap ### Phase 1 (current — shipped) - ✅ `OpenAiProvider` covering 14 OpenAI-compatible providers (incl. Anthropic Claude live-tested with Haiku 4.5 + Sonnet 4.6). - ✅ `LlmProducer` (`.To("llm://...")`). - ✅ `LlmConsumer` (`From("llm://...?schedule=...")`). - ✅ Inline `.Llm("factory", ...)` extension. - ✅ Tools-as-routes — `.AsLlmTool` aspect, `RouteToolBridge`. - ✅ `HttpFetchTool` in `redb.Route.Llm.Tools`. - ✅ `#`-ref resolver for `systemPromptRef` / `initialBodyRef` (producer + consumer). - ✅ `IPromptTemplateRegistry` + `InMemoryPromptTemplateRegistry`. - ✅ OTel + tsak.web statistics. - ✅ DSL showcase test suite (BasicChat, InlineLlm, ToolRoute, ChainedLlm, HttpFetchTool, RegistryDrivenPrompt, ClaudeChat). - ✅ **Streaming end-to-end** (`stream=body`; `stream=calls` keeps the agent loop and streams each model call inside it): `LlmProducer` emits `IAsyncEnumerable`; `redb.Route.Http` flushes per-chunk as SSE (`event: done` JSON trailer with final usage / stop reason / cost); `redb.Route.WebSocket` yields one text frame per token. Live-tested against Anthropic Claude (native SSE), Groq, Cerebras, Gemini, Mistral, OpenRouter. ### Phase 1.5 (next session — confirmed scope) - Utility tools in `redb.Route.Llm.Tools`: `JsonPathTool`, `RegexExtractTool`, `MathEvalTool`, `WebSearchTool` (Tavily). - New connector `redb.Route.Exec` — shell command runner, **producer + scheduled consumer**, allowlist + cwd + timeout + env-overrides + output limits. - One live integration test: Claude calls a `shell` tool wired through `redb.Route.Exec` via `.AsLlmTool("shell")`. ### Phase 2 - Native `AnthropicProvider` (Messages API) — for prompt caching, computer-use, fine-grained vision. - Streaming producer surface (real `IAsyncEnumerable` in `Out.Body`). - Governance hooks: budget, shadow, approval, redaction (cut-points already in `IAgentEngine`). - Persistent conversation memory backed by `[RedbScheme]` POCOs. - Embeddings / vector schemes (`embed://`, `vector://`). - More homeless tools and connectors: SSH, Git, Browser/Playwright. --- ## FAQ **Q: Why one `llm://` scheme instead of `llm-chat://`, `llm-stream://`, `llm-agent://`?** A: Modes are options, not separate transports. The semantics — request goes to a model, response comes back — are the same; only knobs differ. One scheme keeps the URI surface small and IDE-completable. If a future capability *changes the transport semantics* (embeddings return vectors, not text), it gets its own scheme (`embed://`). **Q: Why is the user prompt always `In.Body` and not configurable?** A: It is configurable — for the consumer via `?initialBodyRef=` (with `#`-ref support). For the producer, the inbound body is, by definition, the message you want to process. If you need a fixed prompt with the body as a placeholder, do it in a `.Process` step before `.To("llm://...")` — explicit beats implicit. **Q: Can a tool be implemented in pure C# without a route?** A: Yes — implement `ILlmToolDescriptor` directly and register it in `IToolDescriptorRegistry`. `HttpFetchTool` is exactly that pattern. But if your tool would naturally be a route (HTTP endpoint, Kafka publish, SQL query), prefer the route + `.AsLlmTool` shape — you get retries, telemetry, and the same governance for free. **Q: How do I A/B-test two prompts?** A: Two registry keys (`prompt.A`, `prompt.B`), one route per arm, route A goes through `?systemPromptRef=#prompt.A`, route B through `#prompt.B`. WireTap both arms to your evaluator. With `IPromptTemplateRegistry` you can pin specific versions. **Q: Does `conversation=header` persist across process restarts?** A: No — Phase 1 stores conversation state only in-memory inside the `IAgentEngine` for the duration of a single agent run. Persistent multi-turn memory is Phase 2 and will be backed by `[RedbScheme]`. For now, a "conversation" is a single inbound message that may include several tool-loop turns inside one agent run. **Q: What happens when the model returns more tokens than `MaxTokens`?** A: The provider returns `finish_reason: "length"` and the connector surfaces it as `LlmStopReason.MaxTokens` in the `llm.stop_reason` header. The truncated assistant text is still in `Out.Body`. It is the route author's responsibility to decide whether truncated output is acceptable. **Q: How do I add a fifteenth provider?** A: One line in `OpenAiProvider.ResolveDefaultBaseUrl`. Or, if the provider deviates from the OpenAI contract in some non-trivial way, implement `ILlmProvider` directly — it's a small interface with one method (`CompleteAsync`) plus an optional `StreamAsync`. The factory wires the new provider in via `LlmConnectionFactory.PrebuiltProvider`. **Q: How is this different from semantic-kernel / Microsoft.Extensions.AI?** A: Those are SDK-shaped libraries you call from your code. They live inside one application and own the call stack. `redb.Route.Llm` is an ESB connector — the call stack is the route, and the LLM is *one stage* in a longer pipeline that may also touch Kafka, redb, S3, SQL. If your application is a redb.Route process already, this is the natural shape; if it isn't, semantic-kernel is probably less friction. Path: redb-route/redb.Route.Llm/redb.Route.Llm.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/redb.Route.Llm.csproj ---- redb.Route.Llm Industrial LLM connector for redb.Route ESB framework. Provider-agnostic agent engine, tool-loop with governance (budget, shadow, idempotency, approval), conversation persistence via redb-engine, native EIP integration. esb;messaging;llm;ai;agents;tool-use;rag;redb README.md