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 */ }
}
}
}