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