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