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;
}
}