Bundle: redb-route / tests/redb.Route.Tests.Llm (tests.redb.Route.Tests.Llm.txt), 102 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/tests/redb.Route.Tests.Llm/AgentEngineThinkingTests.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/tests/redb.Route.Tests.Llm/AgentEngineThinkingTests.cs
----
using redb.Route.Llm.Engine.Storage;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// A thinking block travels through the run and reaches the conversation record in the block's own
/// field, with its signature, never as text. It is not an answer: it never reaches
/// AgentResponse.Text or Out.Body.
///
/// Every turn is written, including a turn the model spent entirely on thinking: the record keeps what
/// happened (the thought, the usage, the stop reason). Whether such a turn is sent back to a provider
/// is a request-shape question, answered by the provider request tests.
///
///
public sealed class AgentEngineThinkingTests
{
private static AgentEngine Engine(IConversationStore? conversation = null) => new(
logger: null,
producerTemplate: null,
observer: null,
budget: null,
approval: null,
redaction: null,
shadow: null,
conversation: conversation,
idempotency: null,
approvalStore: null);
private static LlmConnectionFactory Factory(FakeProvider provider) => new()
{
Provider = "fake",
ModelId = provider.ModelId,
PrebuiltProvider = provider
};
private static LlmResponse Reply(LlmStopReason stop, params LlmContentBlock[] blocks) => new()
{
Content = blocks,
StopReason = stop,
Usage = new LlmUsage(3, 4)
};
[Fact]
public async Task ThinkingBlock_IsAppendedToConversation()
{
var store = new InMemoryConversationStore();
var provider = new FakeProvider().Enqueue(Reply(LlmStopReason.EndTurn,
new LlmThinkingBlock("hidden chain of thought", "sig-1"), new LlmTextBlock("shipped")));
var response = await Engine(store).RunAsync(new AgentRequest
{
Factory = Factory(provider),
Exchange = new Exchange(new Message("status of order 42?")),
UserContent = [new LlmTextBlock("status of order 42?")],
ConversationId = "conv-thinking"
});
// The run itself keeps the block — that is what makes the next iteration of a tool loop work.
response.Content.OfType().Should().ContainSingle();
var path = await store.LoadPathAsync("conv-thinking");
path.Should().HaveCount(2, "the prompt and the answer; a thinking block is not a third message");
// The record holds the block with its turn: the schema has a field for the thought and for the
// signature.
var stored = path[^1].Message.Content.OfType().Should().ContainSingle().Subject;
stored.Text.Should().Be("hidden chain of thought");
stored.Signature.Should().Be("sig-1");
path[^1].Message.Content.OfType().Should().ContainSingle().Which.Text.Should().Be("shipped");
}
[Fact]
public async Task TurnWithNothingButThinking_IsWritten()
{
var store = new InMemoryConversationStore();
// The model spent the whole turn thinking and ran out of tokens before saying anything. The
// turn is still part of what happened: its row carries the thought, the tokens it cost and the
// stop reason that explains the empty answer.
var provider = new FakeProvider().Enqueue(Reply(LlmStopReason.MaxTokens, new LlmThinkingBlock("still thinking")));
await Engine(store).RunAsync(new AgentRequest
{
Factory = Factory(provider),
Exchange = new Exchange(new Message("status?")),
UserContent = [new LlmTextBlock("status?")],
ConversationId = "conv-silent"
});
var path = await store.LoadPathAsync("conv-silent");
path.Should().HaveCount(2, "the prompt and the turn that was nothing but thinking");
var turn = path[1];
turn.Message.Role.Should().Be("assistant");
turn.Message.Content.Should().ContainSingle()
.Which.Should().BeOfType().Which.Text.Should().Be("still thinking");
turn.Meta.StopReason.Should().Be(LlmStopReason.MaxTokens);
turn.Meta.Usage.OutputTokens.Should().Be(4, "the tokens the turn cost are recorded with it");
}
[Fact]
public async Task VisibleAnswer_DoesNotContainThinkingText()
{
const string Secret = "SECRET chain of thought";
var provider = new FakeProvider();
for (var i = 0; i < 2; i++)
provider.Enqueue(Reply(LlmStopReason.EndTurn, new LlmThinkingBlock(Secret), new LlmTextBlock("shipped")));
var response = await Engine().RunAsync(new AgentRequest
{
Factory = Factory(provider),
Exchange = new Exchange(new Message("status?")),
UserContent = [new LlmTextBlock("status?")]
});
response.Text.Should().Be("shipped", "the answer is the text block, not the block that came first");
response.Text.Should().NotContain(Secret);
// The same invariant at the edge of a route: what a caller reads is the answer.
var ctx = new RouteContext();
var component = new LlmComponent();
ctx.AddComponent(component);
ctx.AddToRegistry("fake", Factory(provider));
ctx.AddService(typeof(IAgentEngine), new AgentEngine());
var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("llm://fake"));
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("status?"));
await producer.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.Body.Should().Be("shipped");
exchange.Out.Body!.ToString().Should().NotContain(Secret);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/AnthropicModelProfileTests.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/tests/redb.Route.Tests.Llm/AnthropicModelProfileTests.cs
----
namespace redb.Route.Tests.Llm;
///
/// Classification of Anthropic model ids into contract tiers. The tier decides whether
/// the sampling knobs (temperature/top_p) may be sent — current-generation models reject
/// them with HTTP 400, so an unrecognised id must fail forward to Modern.
///
public sealed class AnthropicModelProfileTests
{
[Theory]
// Current generation — sampling removed (HTTP 400 if sent).
[InlineData("claude-opus-5", AnthropicModelTier.Modern)]
[InlineData("claude-sonnet-5", AnthropicModelTier.Modern)]
[InlineData("claude-fable-5", AnthropicModelTier.Modern)]
[InlineData("claude-opus-4-8", AnthropicModelTier.Modern)]
[InlineData("claude-opus-4-7", AnthropicModelTier.Modern)]
[InlineData("claude-opus-4-8-20251001", AnthropicModelTier.Modern)] // date snapshot suffix
// Transitional — sampling still accepted.
[InlineData("claude-opus-4-6", AnthropicModelTier.Transitional)]
[InlineData("claude-sonnet-4-6", AnthropicModelTier.Transitional)]
// Legacy — sampling accepted.
[InlineData("claude-sonnet-4-5", AnthropicModelTier.Legacy)]
[InlineData("claude-haiku-4-5", AnthropicModelTier.Legacy)]
[InlineData("claude-haiku-4.5", AnthropicModelTier.Legacy)] // dot separator
[InlineData("claude-3-7-sonnet-20250219", AnthropicModelTier.Legacy)]
[InlineData("claude-3-5-sonnet-20241022", AnthropicModelTier.Legacy)]
// Unknown / future id — fail forward to Modern (never send a now-removed field).
[InlineData("claude-something-new", AnthropicModelTier.Modern)]
[InlineData("", AnthropicModelTier.Modern)]
public void Resolve_ClassifiesByGeneration(string modelId, AnthropicModelTier expected)
{
AnthropicModelProfile.Resolve(modelId).Tier.Should().Be(expected);
}
[Theory]
// The sampling contract is three-state, not binary — 4.0–4.6 accept ONE knob.
[InlineData("claude-opus-5", AnthropicSamplingPolicy.None)]
[InlineData("claude-sonnet-5", AnthropicSamplingPolicy.None)]
[InlineData("claude-opus-4-8", AnthropicSamplingPolicy.None)]
[InlineData("claude-opus-4-7", AnthropicSamplingPolicy.None)]
[InlineData("claude-opus-4-6", AnthropicSamplingPolicy.AtMostOne)]
[InlineData("claude-sonnet-4-6", AnthropicSamplingPolicy.AtMostOne)]
[InlineData("claude-sonnet-4-5", AnthropicSamplingPolicy.AtMostOne)]
[InlineData("claude-haiku-4-5", AnthropicSamplingPolicy.AtMostOne)]
[InlineData("claude-3-5-sonnet-20241022", AnthropicSamplingPolicy.Both)]
[InlineData("claude-3-opus-20240229", AnthropicSamplingPolicy.Both)]
[InlineData("claude-something-new", AnthropicSamplingPolicy.None)]
public void Resolve_ClassifiesSamplingPolicy(string modelId, AnthropicSamplingPolicy expected)
{
AnthropicModelProfile.Resolve(modelId).Sampling.Should().Be(expected);
}
[Theory]
[InlineData(AnthropicSamplingPolicy.None, false)]
[InlineData(AnthropicSamplingPolicy.AtMostOne, true)]
[InlineData(AnthropicSamplingPolicy.Both, true)]
public void SamplingSupported_MatchesPolicy(AnthropicSamplingPolicy policy, bool expected)
{
new AnthropicModelProfile(AnthropicModelTier.Legacy, policy).SamplingSupported.Should().Be(expected);
}
[Theory]
[InlineData("legacy", AnthropicModelTier.Legacy)]
[InlineData("Transitional", AnthropicModelTier.Transitional)]
[InlineData("MODERN", AnthropicModelTier.Modern)]
public void Resolve_TierOverride_WinsOverModelId(string tierOverride, AnthropicModelTier expected)
{
// A modern id that would classify as Modern, forced to another tier by override.
AnthropicModelProfile.Resolve("claude-opus-5", tierOverride).Tier.Should().Be(expected);
}
[Fact]
public void Resolve_UnknownOverride_FallsBackToModelClassification()
{
AnthropicModelProfile.Resolve("claude-haiku-4-5", "nonsense").Tier
.Should().Be(AnthropicModelTier.Legacy);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/AnthropicProviderRequestTests.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/tests/redb.Route.Tests.Llm/AnthropicProviderRequestTests.cs
----
using System.Net;
using System.Text.Json.Nodes;
namespace redb.Route.Tests.Llm;
///
/// Verifies the shape of the outgoing Anthropic request body — in particular that the
/// sampling knobs (temperature/top_p) are emitted only for models whose contract accepts
/// them. Current-generation models reject those fields with HTTP 400, so a configured
/// Temperature pointed at a modern model must NOT appear on the wire.
///
public sealed class AnthropicProviderRequestTests
{
/// Captures the JSON body of the last request and returns a canned Anthropic reply.
private sealed class CapturingHandler : HttpMessageHandler
{
public JsonObject? LastBody { get; private set; }
public Version? LastVersion { get; private set; }
public HttpVersionPolicy? LastVersionPolicy { get; private set; }
protected override async Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var raw = await request.Content!.ReadAsStringAsync(cancellationToken);
LastBody = JsonNode.Parse(raw) as JsonObject;
LastVersion = request.Version;
LastVersionPolicy = request.VersionPolicy;
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(
"""
{"id":"msg_1","content":[{"type":"text","text":"ok"}],
"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}
""")
};
}
}
private static async Task CaptureBodyAsync(
string modelId, double? temperature, double? topP,
string? tierOverride = null, string? requestModelId = null)
{
var handler = new CapturingHandler();
var factory = new LlmConnectionFactory
{
Provider = "anthropic",
ModelId = modelId,
ApiKey = "test-key",
ModelContractTier = tierOverride
};
var provider = new AnthropicProvider(factory, new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest
{
ModelId = requestModelId,
Messages = [LlmMessage.User("hi")],
Temperature = temperature,
TopP = topP
});
return handler.LastBody!;
}
[Fact]
public async Task SystemPrompt_IsAPlainString_UntilCachingIsAskedFor()
{
var handler = new CapturingHandler();
var provider = new AnthropicProvider(
new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "k" },
new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest
{
SystemPrompt = "constitution",
Messages = [LlmMessage.User("hi")],
});
// Default shape unchanged: a bare string. Switching everyone to the block form would be a
// silent wire change for callers who never asked for caching.
handler.LastBody!["system"]!.GetValue().Should().Be("constitution");
(handler.LastBody!["system"] is System.Text.Json.Nodes.JsonArray).Should().BeFalse();
}
[Fact]
public async Task CacheSystemPrompt_EmitsTheBlockFormWithCacheControl()
{
var handler = new CapturingHandler();
var provider = new AnthropicProvider(
new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "k" },
new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest
{
SystemPrompt = "constitution",
CacheSystemPrompt = true,
Messages = [LlmMessage.User("hi")],
});
// cache_control is a property OF a content block — a bare string has nowhere to hang it,
// so asking for caching necessarily switches the shape.
var system = handler.LastBody!["system"]!.AsArray();
system.Count.Should().Be(1);
system[0]!["type"]!.GetValue().Should().Be("text");
system[0]!["text"]!.GetValue().Should().Be("constitution");
system[0]!["cache_control"]!["type"]!.GetValue().Should().Be("ephemeral");
}
[Fact]
public async Task CacheBreakpoint_OnAMessage_MarksItsLastBlock_AndNothingElse()
{
var handler = new CapturingHandler();
var provider = new AnthropicProvider(
new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "k" },
new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest
{
SystemPrompt = "constitution",
CacheSystemPrompt = true,
Messages =
[
LlmMessage.User("read it?"),
new LlmMessage
{
Role = "assistant",
Content = [new LlmTextBlock("part one"), new LlmTextBlock("part two")],
CacheBreakpoint = true
},
LlmMessage.User("hi"),
],
});
var messages = handler.LastBody!["messages"]!.AsArray();
messages.Count.Should().Be(3);
// The breakpoint sits on the LAST block of the marked message — the cached prefix runs up
// to it inclusive — and on no other block of any other message.
var marked = messages[1]!["content"]!.AsArray();
marked.Count.Should().Be(2);
marked[0]!.AsObject().ContainsKey("cache_control").Should().BeFalse();
marked[1]!["cache_control"]!["type"]!.GetValue().Should().Be("ephemeral");
messages[0]!["content"]!.AsArray()[0]!.AsObject().ContainsKey("cache_control").Should().BeFalse();
messages[2]!["content"]!.AsArray()[0]!.AsObject().ContainsKey("cache_control").Should().BeFalse();
// Two breakpoints in the request: system and the marked message. Anthropic allows four.
handler.LastBody!["system"]!.AsArray()[0]!["cache_control"].Should().NotBeNull();
}
[Fact]
public async Task ModernModel_DropsSamplingKnobs()
{
// The bug: connector sent temperature/top_p to a modern model → HTTP 400.
var body = await CaptureBodyAsync("claude-opus-4-8", temperature: 0.7, topP: 0.9);
body.ContainsKey("temperature").Should().BeFalse("modern models reject temperature (400)");
body.ContainsKey("top_p").Should().BeFalse("modern models reject top_p (400)");
}
[Fact]
public async Task Claude3_KeepsBothSamplingKnobs()
{
// Claude 3.x is the only generation that accepts temperature AND top_p together.
var body = await CaptureBodyAsync("claude-3-5-sonnet-20241022", temperature: 0.5, topP: 0.8);
body["temperature"]!.GetValue().Should().Be(0.5);
body["top_p"]!.GetValue().Should().Be(0.8);
}
[Fact]
public async Task Claude4x_WithBothKnobs_KeepsOnlyTemperature()
{
// Claude 4.0–4.6 reject temperature+top_p together (400); keep temperature, drop top_p.
var body = await CaptureBodyAsync("claude-sonnet-4-6", temperature: 0.5, topP: 0.8);
body["temperature"]!.GetValue().Should().Be(0.5);
body.ContainsKey("top_p").Should().BeFalse("Claude 4.x accepts at most one sampling knob");
}
[Fact]
public async Task Claude4x_WithOnlyTopP_KeepsTopP()
{
var body = await CaptureBodyAsync("claude-haiku-4-5", temperature: null, topP: 0.8);
body["top_p"]!.GetValue().Should().Be(0.8);
body.ContainsKey("temperature").Should().BeFalse();
}
[Fact]
public async Task TierOverride_ForcesLegacyOnModernId()
{
var body = await CaptureBodyAsync("claude-opus-5", temperature: 0.3, topP: null, tierOverride: "legacy");
body["temperature"]!.GetValue().Should().Be(0.3);
}
[Fact]
public async Task PerRequestModelOverride_IsClassifiedFresh()
{
// Factory is a legacy model (cached profile → sampling allowed), but the request
// overrides to a modern id — the per-request resolve must win and drop sampling.
var body = await CaptureBodyAsync(
"claude-haiku-4-5", temperature: 0.5, topP: null, requestModelId: "claude-opus-4-8");
body["model"]!.GetValue().Should().Be("claude-opus-4-8");
body.ContainsKey("temperature").Should().BeFalse("the overridden modern model rejects sampling");
}
[Fact]
public async Task ModernModel_WithoutSampling_StillWorks()
{
var body = await CaptureBodyAsync("claude-opus-4-8", temperature: null, topP: null);
body.ContainsKey("temperature").Should().BeFalse();
body["model"]!.GetValue().Should().Be("claude-opus-4-8");
}
[Fact]
public void DefaultTransport_UsesHttp2_WithKeepAlivePings()
{
// A non-streaming completion is tens of seconds of silence on the wire, and tunnels/NATs cut
// a silent TLS connection at ~50 s. PING frames while the request is in flight are what keeps
// a long answer alive — and they need HTTP/2 to exist at all. The delay must stay well under
// the ~50 s cut so at least one ping always lands before it.
var handler = AnthropicProvider.BuildDefaultHandler();
handler.KeepAlivePingPolicy.Should().Be(HttpKeepAlivePingPolicy.WithActiveRequests);
handler.KeepAlivePingDelay.Should().BeGreaterThan(TimeSpan.Zero).And.BeLessThan(TimeSpan.FromSeconds(30));
handler.KeepAlivePingTimeout.Should().BeGreaterThan(TimeSpan.Zero);
using var client = AnthropicProvider.BuildDefaultClient(new LlmConnectionFactory
{
Provider = "anthropic",
ModelId = "claude-opus-4-8",
ApiKey = "sk-test",
RequestTimeoutMs = 90_000,
});
client.DefaultRequestVersion.Should().Be(System.Net.HttpVersion.Version20);
client.DefaultVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 must stay the fallback");
client.Timeout.Should().Be(Timeout.InfiniteTimeSpan,
"RequestTimeoutMs limits the whole call and is applied per call; the client's own Timeout would stop at the headers");
}
[Fact]
public async Task Request_CarriesTheClientsHttpVersion()
{
// HttpClient.DefaultRequestVersion never touches a hand-built HttpRequestMessage — it
// starts at HTTP/1.1 regardless. The provider builds its own messages, so it must copy
// the client's defaults onto them, or the HTTP/2 keep-alive pings silently never happen.
var handler = new CapturingHandler();
var client = new HttpClient(handler)
{
DefaultRequestVersion = HttpVersion.Version20,
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower,
};
var provider = new AnthropicProvider(new LlmConnectionFactory
{
Provider = "anthropic", ModelId = "claude-opus-4-8", ApiKey = "test-key",
}, client);
await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] });
handler.LastVersion.Should().Be(HttpVersion.Version20);
handler.LastVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower);
}
[Fact]
public async Task EmptyMessages_AreSkipped_NotSentAsEmptyTextBlocks()
{
// One assistant reply with no text (the model spent max_tokens on thinking) used to be
// rendered as {"type":"text","text":""}, which the API rejects with 400 — and since the
// reply was persisted, EVERY later call of that conversation failed. Empty and
// whitespace-only messages must simply not be sent; consecutive same-role turns are fine.
var handler = new CapturingHandler();
var provider = new AnthropicProvider(new LlmConnectionFactory
{
Provider = "anthropic", ModelId = "claude-opus-4-8", ApiKey = "test-key",
}, new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest
{
Messages =
[
LlmMessage.User("первый вопрос"),
new LlmMessage { Role = "assistant", Content = [new LlmTextBlock(string.Empty)] },
LlmMessage.User("второй вопрос"),
new LlmMessage { Role = "assistant", Content = [new LlmTextBlock(" ")] },
new LlmMessage { Role = "assistant", Content = [] },
LlmMessage.User("третий вопрос"),
],
});
var messages = handler.LastBody!["messages"]!.AsArray();
messages.Count.Should().Be(3, "the three empty assistant replies are not sent");
messages.Should().OnlyContain(m => m!["role"]!.GetValue() == "user");
foreach (var message in messages)
foreach (var block in message!["content"]!.AsArray())
if (block!["type"]!.GetValue() == "text")
block["text"]!.GetValue().Should().NotBeNullOrWhiteSpace();
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task Effort_Unset_SendsNoOutputConfig(string? effort)
{
var handler = new CapturingHandler();
var provider = new AnthropicProvider(new LlmConnectionFactory
{
Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key", Effort = effort,
}, new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] });
handler.LastBody!.ContainsKey("output_config").Should().BeFalse("the provider's default effort must stay the provider's");
}
[Fact]
public async Task Effort_Set_GoesInsideOutputConfig()
{
// Thinking tokens count against max_tokens; at the default (high) effort Sonnet 5 spent
// all 4096 on thinking and answered with nothing. The knob lives in output_config, not
// top-level, and is sent only for the factory that asked for it.
var handler = new CapturingHandler();
var provider = new AnthropicProvider(new LlmConnectionFactory
{
Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key", Effort = " medium ",
}, new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] });
handler.LastBody!["output_config"]!["effort"]!.GetValue().Should().Be("medium");
handler.LastBody!.ContainsKey("effort").Should().BeFalse("effort is not a top-level field");
}
///
/// Captures the body of every request and answers with the scripted body per call — the second
/// request is the one under test, so one canned reply is not enough.
///
private sealed class ScriptedHandler : HttpMessageHandler
{
private readonly string[] _bodies;
private int _calls;
public ScriptedHandler(params string[] bodies) => _bodies = bodies;
public List Bodies { get; } = [];
protected override async Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Bodies.Add(JsonNode.Parse(await request.Content!.ReadAsStringAsync(cancellationToken))!.AsObject());
var body = _bodies[Math.Min(_calls++, _bodies.Length - 1)];
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) };
}
}
private static LlmToolCapability LookupTool() => new()
{
Name = "order_lookup",
Description = "Look up an order by id.",
InputSchema = """{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}"""
};
[Fact]
public async Task Anthropic_SecondRequest_CarriesSignedThinkingBlock()
{
// The model thinks, then asks for a tool. The thinking it produced comes back signed, and
// the API verifies that signature: the block has to travel on untouched, in the order the
// API issued it, or the second call of a tool loop is rejected with 400.
var handler = new ScriptedHandler(
"""
{"id":"msg_1","content":[
{"type":"thinking","thinking":"the user wants an order status","signature":"sig-abc"},
{"type":"text","text":"let me look"},
{"type":"tool_use","id":"tu_1","name":"order_lookup","input":{"orderId":"42"}}],
"stop_reason":"tool_use","usage":{"input_tokens":10,"output_tokens":5}}
""");
var provider = new AnthropicProvider(
new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "test-key" },
new HttpClient(handler));
var first = await provider.CompleteAsync(new LlmRequest
{
Messages = [LlmMessage.User("what is the status of order 42?")],
Tools = [LookupTool()]
});
var thinking = first.Content.OfType().Should().ContainSingle(
"the thinking block is parsed as a block of its own").Which;
thinking.Text.Should().Be("the user wants an order status");
thinking.Signature.Should().Be("sig-abc");
// Thinking is not the answer: the visible text is what the model said afterwards.
first.Content.OfType().Should().ContainSingle().Which.Text.Should().Be("let me look");
// Second call of the same run: history + the tool result.
await provider.CompleteAsync(new LlmRequest
{
Messages =
[
LlmMessage.User("what is the status of order 42?"),
new LlmMessage { Role = "assistant", Content = first.Content },
new LlmMessage { Role = "user", Content = [new LlmToolResultBlock("tu_1", """{"status":"shipped"}""")] }
],
Tools = [LookupTool()]
});
var sent = handler.Bodies[1]["messages"]!.AsArray()[1]!["content"]!.AsArray();
sent.Should().HaveCount(3);
sent[0]!["type"]!.GetValue().Should().Be("thinking");
sent[0]!["thinking"]!.GetValue().Should().Be("the user wants an order status");
sent[0]!["signature"]!.GetValue().Should().Be("sig-abc");
sent[1]!["type"]!.GetValue().Should().Be("text");
sent[2]!["type"]!.GetValue().Should().Be("tool_use");
}
[Fact]
public async Task Anthropic_RedactedAndOmittedThinking_GoBackVerbatim()
{
// Two shapes the signed-block test does not cover. With display "omitted" (the default on
// models that think on their own) the thinking text is empty and the signature is what
// travels; a redacted_thinking block carries an encrypted payload in "data" and no text. Both
// must come back field for field, or the API cannot verify them.
var handler = new ScriptedHandler(
"""
{"id":"msg_1","content":[
{"type":"thinking","thinking":"","signature":"sig-omitted"},
{"type":"redacted_thinking","data":"EncryptedPayload=="},
{"type":"tool_use","id":"tu_1","name":"order_lookup","input":{"orderId":"42"}}],
"stop_reason":"tool_use","usage":{"input_tokens":10,"output_tokens":5}}
""");
var provider = new AnthropicProvider(
new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key" },
new HttpClient(handler));
var first = await provider.CompleteAsync(new LlmRequest
{
Messages = [LlmMessage.User("what is the status of order 42?")],
Tools = [LookupTool()]
});
var parsed = first.Content.OfType().ToList();
parsed.Should().HaveCount(2);
parsed[0].Text.Should().BeEmpty();
parsed[0].Signature.Should().Be("sig-omitted");
parsed[1].IsRedacted.Should().BeTrue();
parsed[1].RedactedData.Should().Be("EncryptedPayload==");
await provider.CompleteAsync(new LlmRequest
{
Messages =
[
LlmMessage.User("what is the status of order 42?"),
new LlmMessage { Role = "assistant", Content = first.Content },
new LlmMessage { Role = "user", Content = [new LlmToolResultBlock("tu_1", """{"status":"shipped"}""")] }
],
Tools = [LookupTool()]
});
var sent = handler.Bodies[1]["messages"]!.AsArray()[1]!["content"]!.AsArray();
sent.Should().HaveCount(3);
var omitted = sent[0]!.AsObject();
omitted.Count.Should().Be(3, "type, thinking and signature, nothing added");
omitted["type"]!.GetValue().Should().Be("thinking");
omitted["thinking"]!.GetValue().Should().BeEmpty();
omitted["signature"]!.GetValue().Should().Be("sig-omitted");
var redacted = sent[1]!.AsObject();
redacted.Count.Should().Be(2, "type and data: a redacted block has no text to send");
redacted["type"]!.GetValue().Should().Be("redacted_thinking");
redacted["data"]!.GetValue().Should().Be("EncryptedPayload==");
sent[2]!["type"]!.GetValue().Should().Be("tool_use");
}
[Fact]
public async Task UnsignedThinkingBlock_HasNoAnthropicForm_IsNotSent()
{
// A conversation continued here after a provider switch can carry unsigned blocks (DeepSeek
// reasoning_content). The Anthropic wire has no form for them: a thinking block without a
// signature is a 400. So the block is not written into the request, and the rest of the turn
// goes on unchanged.
var handler = new CapturingHandler();
var provider = new AnthropicProvider(
new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key" },
new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest
{
Messages =
[
LlmMessage.User("status of order 42?"),
new LlmMessage
{
Role = "assistant",
Content = [new LlmThinkingBlock("deepseek reasoning"), new LlmTextBlock("shipped")]
},
LlmMessage.User("and order 43?")
]
});
var messages = handler.LastBody!["messages"]!.AsArray();
messages.Count.Should().Be(3, "the turn itself is sent");
var turn = messages[1]!["content"]!.AsArray();
turn.Count.Should().Be(1, "only the text: an unsigned thinking block has no Anthropic form");
turn[0]!["type"]!.GetValue().Should().Be("text");
turn[0]!["text"]!.GetValue().Should().Be("shipped");
}
[Fact]
public async Task ThinkingOnlyTurn_IsNotSent()
{
// The model spent the whole turn thinking and said nothing. The turn is kept in the record, but
// a message with no text and no tool call has nothing to continue from, and sending it would
// put a message the API may refuse into every later request of the conversation (the class of
// 2026-09-07). Signed and redacted alike: the turn is left out of the request.
var handler = new CapturingHandler();
var provider = new AnthropicProvider(
new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key" },
new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest
{
Messages =
[
LlmMessage.User("status of order 42?"),
new LlmMessage { Role = "assistant", Content = [new LlmThinkingBlock("ran out of tokens", "sig-1")] },
LlmMessage.User("and now?"),
new LlmMessage { Role = "assistant", Content = [new LlmThinkingBlock(string.Empty, RedactedData: "opaque")] },
LlmMessage.User("still there?")
]
});
var messages = handler.LastBody!["messages"]!.AsArray();
messages.Count.Should().Be(3, "the two turns of nothing but thinking are not sent");
messages.Should().OnlyContain(m => m!["role"]!.GetValue() == "user");
}
[Fact]
public async Task OldHistory_WithoutThinkingBlocks_RequestShapeIsRecorded()
{
// A conversation written before phase 16 carries text only. Nothing new may appear on the
// wire for it: no thinking block, no empty text block, no top-level thinking knob. Whether
// an old history is ACCEPTED is what the 16.0a live probe answers — a unit test can only
// pin the shape we send.
var handler = new ScriptedHandler(
"""
{"id":"msg_1","content":[{"type":"text","text":"ok"}],
"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}
""");
var provider = new AnthropicProvider(
new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "test-key" },
new HttpClient(handler));
await provider.CompleteAsync(new LlmRequest
{
Messages =
[
LlmMessage.User("hi"),
LlmMessage.Assistant("hello"),
LlmMessage.User("and now?")
]
});
var body = handler.Bodies[0];
body.ContainsKey("thinking").Should().BeFalse("we do not ask the model to think; that is decision 15");
var messages = body["messages"]!.AsArray();
messages.Should().HaveCount(3, "three non-empty turns, nothing added and nothing dropped");
messages[1]!["content"]!.AsArray().Should().HaveCount(1, "no thinking block, no empty text block");
messages[1]!["content"]!.AsArray()[0]!["type"]!.GetValue().Should().Be("text");
messages[1]!["content"]!.AsArray()[0]!["text"]!.GetValue().Should().Be("hello");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/CachedPromptUsageTests.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/tests/redb.Route.Tests.Llm/CachedPromptUsageTests.cs
----
using System.Net;
using System.Text;
namespace redb.Route.Tests.Llm;
///
/// A prompt served from the provider's cache reaches on the OpenAI-compatible path too
/// (issue #11). LlmUsage.InputTokens is the uncached remainder, not the whole prompt, so the cached part is
/// taken out of it: a cost calculator or an audit built on these numbers would otherwise bill a cached prefix at full
/// price. DeepSeek reports the split in its own fields, OpenAI in prompt_tokens_details; both mean the same.
///
public sealed class CachedPromptUsageTests
{
private sealed class FixedHandler(string body, string mediaType) : HttpMessageHandler
{
protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) =>
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(body, Encoding.UTF8, mediaType)
});
}
private static OpenAiProvider Provider(string body, string mediaType = "application/json") =>
new(new LlmConnectionFactory { Provider = "deepseek", ModelId = "deepseek-v4-pro", ApiKey = "sk-test" },
new HttpClient(new FixedHandler(body, mediaType)));
private static LlmRequest Request() => new() { Messages = [LlmMessage.User("hi")] };
private static string Answer(string usage) => $$"""
{"id":"chatcmpl-1","choices":[{"index":0,"message":{"role":"assistant","content":"done"},"finish_reason":"stop"}],"usage":{{usage}}}
""";
[Fact]
public async Task DeepSeek_CachedPrefix_ReachesUsage()
{
// The numbers of the report: a ~170k system field served from cache, 63 tokens of it new. DeepSeek fills its
// own pair and leaves the OpenAI-shaped cached_tokens at zero, so the zero must not win.
var provider = Provider(Answer("""
{"prompt_tokens":172095,"completion_tokens":11,"total_tokens":172106,
"prompt_tokens_details":{"cached_tokens":0},
"prompt_cache_hit_tokens":172032,"prompt_cache_miss_tokens":63}
"""));
var usage = (await provider.CompleteAsync(Request())).Usage;
usage.CacheReadInputTokens.Should().Be(172032, "this is the number that says caching works");
usage.InputTokens.Should().Be(63, "InputTokens is what was billed at full price, not the whole prompt");
usage.CacheCreationInputTokens.Should().Be(0, "DeepSeek does not bill cache creation separately");
usage.OutputTokens.Should().Be(11);
}
[Fact]
public async Task OpenAi_CachedPrefix_ReachesUsage()
{
var provider = Provider(Answer("""
{"prompt_tokens":1000,"completion_tokens":20,"prompt_tokens_details":{"cached_tokens":896}}
"""));
var usage = (await provider.CompleteAsync(Request())).Usage;
usage.CacheReadInputTokens.Should().Be(896);
usage.InputTokens.Should().Be(104, "the prompt minus what came from cache");
}
[Fact]
public async Task WithoutCacheFields_TheWholePromptIsInput()
{
var provider = Provider(Answer("""{"prompt_tokens":38,"completion_tokens":5,"total_tokens":43}"""));
var usage = (await provider.CompleteAsync(Request())).Usage;
usage.InputTokens.Should().Be(38);
usage.CacheReadInputTokens.Should().Be(0);
}
[Fact]
public async Task StreamedCall_ReportsTheCachedPrefixToo()
{
var sse = string.Join("\n", [
"""data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{"content":"done"}}]}""",
"",
"""data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}""",
"",
"""data: {"id":"chatcmpl-1","choices":[],"usage":{"prompt_tokens":172095,"completion_tokens":11,"prompt_cache_hit_tokens":172032,"prompt_cache_miss_tokens":63}}""",
"",
"data: [DONE]"]) + "\n";
var provider = Provider(sse, "text/event-stream");
LlmResponse? answer = null;
await foreach (var chunk in provider.StreamAsync(Request()))
if (chunk.Response is not null) answer = chunk.Response;
answer!.Usage.CacheReadInputTokens.Should().Be(172032, "the streamed answer carries the same usage");
answer.Usage.InputTokens.Should().Be(63);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/ComponentSideTests.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/tests/redb.Route.Tests.Llm/ComponentSideTests.cs
----
using redb.Route.Core;
using redb.Route.Llm.Embeddings;
using redb.Route.Llm.Knowledge;
using redb.Route.Llm.Transcription;
namespace redb.Route.Tests.Llm;
/// The component declares the only side it has ([EndpointRole], Apache Camel's producerOnly / consumerOnly).
public sealed class ComponentSideTests
{
[Fact]
public void The_component_declares_its_only_side()
{
EndpointSides.Declaration(typeof(EmbedComponent))!.Role.Should().Be(EndpointRole.Producer);
EndpointSides.Declaration(typeof(KnowledgeComponent))!.Role.Should().Be(EndpointRole.Producer);
EndpointSides.Declaration(typeof(SttComponent))!.Role.Should().Be(EndpointRole.Producer);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/AnthropicCompatLiveTests.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/tests/redb.Route.Tests.Llm/DslShowcase/AnthropicCompatLiveTests.cs
----
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using redb.Route.Tests.Llm.TestHelpers;
using Xunit.Abstractions;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Phase 16.0b, on the interface that is actually reachable: DeepSeek serves the Anthropic Messages API
/// at https://api.deepseek.com/anthropic (x-api-key supported, type="thinking"
/// supported, redacted_thinking not), so can be exercised against
/// a live endpoint without an Anthropic key — which is the whole question 16.0b asks: does a thinking
/// block that came off the wire go back on it without a 400.
///
/// The run is recorded, not assumed. Both request bodies are captured as sent, and the artifact says
/// what came back (a block with a signature, a block without one, or none) — so a green run with no
/// returnable block is read as "the path works", never as "the replay was proven".
///
///
/// Nothing here prints the key or the thinking text: the artifact carries counts, lengths, field names
/// and the first 16 hex digits of the block's SHA-256.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class AnthropicCompatLiveTests
{
private const string EnvVar = "REDB_LLM_DEEPSEEK";
private const string BaseUrl = "https://api.deepseek.com/anthropic/";
private const string Model = "deepseek-flash";
private const string Artifact = "16-0b-anthropic-compat.json";
private readonly ITestOutputHelper _output;
/// Creates the probe with xUnit's output sink.
public AnthropicCompatLiveTests(ITestOutputHelper output) => _output = output;
/// Forwards a request untouched and keeps the body and address the provider sent.
private sealed class RecordingHandler : HttpMessageHandler
{
private readonly HttpClient _forward = new() { Timeout = TimeSpan.FromSeconds(120) };
/// Serialised request bodies, in the order the provider sent them.
public List SentBodies { get; } = new();
/// Request addresses, so the run proves which endpoint was spoken to.
public List SentUris { get; } = new();
protected override async Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = await request.Content!.ReadAsStringAsync(cancellationToken);
SentBodies.Add(body);
SentUris.Add(request.RequestUri!.ToString());
using var clone = new HttpRequestMessage(request.Method, request.RequestUri);
foreach (var header in request.Headers)
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
clone.Content = new StringContent(body, Encoding.UTF8, "application/json");
return await _forward.SendAsync(clone, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
}
protected override void Dispose(bool disposing)
{
if (disposing) _forward.Dispose();
base.Dispose(disposing);
}
}
private static string Fingerprint(string text)
{
var hash = System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(text));
return Convert.ToHexString(hash[..8]).ToLowerInvariant();
}
/// What came back on the thinking path — enough to compare two runs without reading thoughts.
private sealed record ThinkingShape(bool Present, bool HasSignature, bool IsRedacted, int TextLength, string TextFingerprint)
{
public static ThinkingShape Of(LlmThinkingBlock? block) => block is null
? new ThinkingShape(false, false, false, 0, string.Empty)
: new ThinkingShape(true, block.Signature is { Length: > 0 }, block.IsRedacted,
block.Text.Length, Fingerprint(block.Text));
}
private const string Question = "Where is order 4711 right now?";
private static readonly LlmToolCapability LookupTool = new()
{
Name = "order_lookup",
Description = "Looks up one order by id and returns its shipping status.",
InputSchema = """{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}"""
};
private static JsonObject ParseBody(string body) => JsonNode.Parse(body)!.AsObject();
/// A block the Anthropic wire can carry back: signed thinking, or a redacted payload.
private static bool HasAnthropicForm(LlmThinkingBlock? block) =>
block is not null && (block.IsRedacted || !string.IsNullOrEmpty(block.Signature));
private static IEnumerable BlocksOf(JsonObject body)
{
if (body["messages"] is not JsonArray messages) yield break;
foreach (var message in messages)
{
if (message?["content"] is not JsonArray blocks) continue;
foreach (var block in blocks)
if (block is JsonObject obj) yield return obj;
}
}
private static int ThinkingBlocksIn(JsonObject body) => BlocksOf(body)
.Count(b => b["type"]?.GetValue() is "thinking" or "redacted_thinking");
/// The signature (or redacted payload) of the first thinking block carried in a request.
private static string? SignaturePlayed(JsonObject body) => BlocksOf(body)
.FirstOrDefault(b => b["type"]?.GetValue() is "thinking" or "redacted_thinking") is { } first
? first["signature"]?.GetValue() ?? first["data"]?.GetValue()
: null;
///
/// The 16.0b question on an endpoint that is reachable today: against
/// DeepSeek's Anthropic-compatible interface, asked twice — once for an answer that may carry a thinking
/// block, then with that block and the tool turn it belongs to handed back.
///
[EnvFact(EnvVar)]
public async Task DeepSeek_AnthropicPath_TakesTheThinkingBlockBack()
{
var started = DateTimeOffset.UtcNow;
var factory = new LlmConnectionFactory
{
Name = "deepseek-anthropic-compat",
Provider = "anthropic",
ModelId = Model,
ApiKey = Environment.GetEnvironmentVariable(EnvVar)!,
BaseUrl = new Uri(BaseUrl),
MaxTokens = 512
};
using var recorder = new RecordingHandler();
var provider = new AnthropicProvider(factory, new HttpClient(recorder));
var first = await provider.CompleteAsync(new LlmRequest
{
SystemPrompt = "Call the order_lookup tool before answering the question.",
Messages = [LlmMessage.User(Question)],
Tools = [LookupTool]
});
var thinking = first.Content.OfType().FirstOrDefault();
var shape = ThinkingShape.Of(thinking);
var toolUses = first.Content.OfType().ToList();
// The transcript is rebuilt the way a run would: the block first, what the assistant said next,
// then the tool result the tool_use asked for — the shape that 400s if either half is lost.
var assistant = new List();
if (HasAnthropicForm(thinking)) assistant.Add(thinking!);
assistant.AddRange(first.Content.Where(b => b is not LlmThinkingBlock));
var transcript = new List { LlmMessage.User(Question) };
if (assistant.Count > 0)
transcript.Add(new LlmMessage { Role = "assistant", Content = assistant });
if (toolUses.Count > 0)
transcript.Add(new LlmMessage
{
Role = "user",
Content = toolUses
.Select(u => (LlmContentBlock)new LlmToolResultBlock(u.ToolUseId, """{"status":"in_transit"}"""))
.ToList()
});
var replay = await provider.CompleteAsync(new LlmRequest
{
Messages = transcript,
Tools = [LookupTool]
});
var sent = recorder.SentBodies.Select(ParseBody).ToList();
var carriedBack = ThinkingBlocksIn(sent[1]);
var verdict = shape switch
{
{ Present: false } => "no thinking block came back — the path holds, the replay is not proven",
{ IsRedacted: true } => "redacted block came back and was handed back verbatim",
{ HasSignature: true } => "signed block came back and was handed back verbatim",
_ => "unsigned block came back — this connector does not replay it (it would be rejected)"
};
recorder.SentUris.Should().HaveCount(2);
recorder.SentUris[0].Should().Be(BaseUrl + "v1/messages");
first.Content.Should().NotBeEmpty();
replay.Content.Should().NotBeEmpty();
// Decision 15 of the plan: this connector never asks for thinking, so a block that comes back is
// the model thinking on its own — asserted, because "we do not send it" is a promise a request
// body can keep.
sent[0].Should().NotContainKey("thinking", "the anthropic path must not send a top-level thinking field.");
sent[1].Should().NotContainKey("thinking");
if (HasAnthropicForm(thinking))
{
carriedBack.Should().Be(1);
SignaturePlayed(sent[1]).Should().Be(thinking!.IsRedacted ? thinking.RedactedData : thinking.Signature);
}
else
{
// Nothing returnable came back, so nothing could be replayed — said out loud rather than
// left for a reader to infer from a green run.
carriedBack.Should().Be(0);
}
var artifact = new
{
Phase = "16.0b — the anthropic path against DeepSeek's Anthropic-compatible interface",
Endpoint = recorder.SentUris[0],
Model,
StartedUtc = started,
FinishedUtc = DateTimeOffset.UtcNow,
FirstRequestHadThinkingField = sent[0].ContainsKey("thinking"),
ThinkingOnTheWire = ThinkingBlocksIn(sent[0]),
ThinkingParsed = shape,
ToolCalls = toolUses.Count,
BlocksHandedBack = carriedBack,
ReplayedSignatureFingerprint = SignaturePlayed(sent[1]) is { Length: > 0 } sig ? Fingerprint(sig) : null,
Verdict = verdict
};
var path = Path.Combine(AppContext.BaseDirectory, Artifact);
await File.WriteAllTextAsync(path,
JsonSerializer.Serialize(artifact, new JsonSerializerOptions { WriteIndented = true }));
_output.WriteLine($"artifact: {path}");
_output.WriteLine($"thinking on the wire={artifact.ThinkingOnTheWire} parsed={shape.Present} " +
$"signed={shape.HasSignature} redacted={shape.IsRedacted} " +
$"textLen={shape.TextLength} textSha256={shape.TextFingerprint}");
_output.WriteLine($"tool calls={toolUses.Count} blocks handed back={carriedBack}");
_output.WriteLine(verdict);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/BasicChatTests.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/tests/redb.Route.Tests.Llm/DslShowcase/BasicChatTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// The simplest live shape — an Apache Camel pattern reduced to one line:
/// From("direct:chat") → To("llm://...") → To("mock:result").
/// One direct: producer, one LLM hop, one assertion sink. Any junior
/// reader should grasp the shape on first sight.
///
/// Each test gates on the env var of the corresponding free-tier provider.
/// We don't pretend the cheapest free tiers are equally reliable — the suite
/// shows the connector works in principle across providers, not that
/// every provider is production-grade.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class BasicChatTests
{
///
/// Groq + Llama 3.3 70B is the most reliable free tier we have access to,
/// so it gets the strict assertion (the model must produce the literal word).
///
[EnvFact("REDB_LLM_GROQ_KEY")]
public async Task Groq_From_To_Mock_DeliversAnswer()
{
await using var host = LiveLlmHost.Build()
.AddFactory("groq", new LlmConnectionFactory
{
Provider = "groq",
ModelId = "llama-3.3-70b-versatile",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"),
Temperature = 0.0,
MaxTokens = 16
});
await host.StartAsync(r =>
{
r.From("direct:chat")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Reply with exactly one lowercase word: pong. No punctuation.")
.To(LlmDsl.Factory("groq").Temperature(0.0).MaxTokens(16).AsUri())
.To("mock:result");
});
await host.SendAsync("direct:chat", "Say the word.");
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");
// Headers stamped by LlmProducer must propagate down the route.
sink.ReceivedExchanges[0].In.Headers[LlmHeaders.ProviderId].Should().Be("groq");
((int)sink.ReceivedExchanges[0].In.Headers[LlmHeaders.TokensIn]!).Should().BeGreaterThan(0);
}
///
/// Gemini's free tier is rate-limited to 15 RPM; on a quiet repo it works,
/// but we keep the assertion philosophical: some non-empty reply
/// rather than a specific token. Demonstrates that switching provider is
/// just a registry entry change — no other DSL surface moves.
///
[EnvFact("REDB_LLM_GEMINI_KEY")]
public async Task Gemini_From_To_Mock_DeliversNonEmptyReply()
{
await using var host = LiveLlmHost.Build()
.AddFactory("gemini", new LlmConnectionFactory
{
Provider = "gemini",
ModelId = "gemini-2.0-flash",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GEMINI_KEY"),
Temperature = 0.0,
MaxTokens = 32
});
await host.StartAsync(r =>
{
r.From("direct:chat")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Reply with one short sentence in plain English.")
.To(LlmDsl.Factory("gemini").AsUri())
.To("mock:result");
});
await host.SendAsync("direct:chat", "Greet me.");
var sink = host.Mock("mock:result");
sink.ReceivedCount.Should().Be(1);
((string)sink.ReceivedExchanges[0].In.Body!).Should().NotBeNullOrWhiteSpace();
}
///
/// Mistral's small-latest is the second-most reliable free tier for
/// short-form replies. Same DSL — only the registry name changes.
///
[EnvFact("REDB_LLM_MISTRAL_KEY")]
public async Task Mistral_From_To_Mock_DeliversNonEmptyReply()
{
await using var host = LiveLlmHost.Build()
.AddFactory("mistral", new LlmConnectionFactory
{
Provider = "mistral",
ModelId = "mistral-small-latest",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_MISTRAL_KEY"),
Temperature = 0.0,
MaxTokens = 32
});
await host.StartAsync(r =>
{
r.From("direct:chat")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Reply with one short sentence in plain English.")
.To(LlmDsl.Factory("mistral").AsUri())
.To("mock:result");
});
await host.SendAsync("direct:chat", "Greet me.");
var sink = host.Mock("mock:result");
sink.ReceivedCount.Should().Be(1);
((string)sink.ReceivedExchanges[0].In.Body!).Should().NotBeNullOrWhiteSpace();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ChainedLlmTests.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/tests/redb.Route.Tests.Llm/DslShowcase/ChainedLlmTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Two LLM hops in a row. First hop summarizes, second hop translates the
/// summary. The route engine carries the body forward; no extra plumbing is
/// needed to chain models. Uses Groq twice with different system prompts —
/// the same factory, parameterized per call site.
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class ChainedLlmTests
{
[EnvFact("REDB_LLM_GROQ_KEY")]
public async Task Groq_TwoHopChain_SummarizeThenTranslate()
{
await using var host = LiveLlmHost.Build()
.AddFactory("groq", new LlmConnectionFactory
{
Provider = "groq",
ModelId = "llama-3.3-70b-versatile",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"),
Temperature = 0.0,
MaxTokens = 96
});
await host.StartAsync(r =>
{
r.From("direct:chain")
// Hop 1 — summarize.
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Summarize the user's text in one short English sentence.")
.To(LlmDsl.Factory("groq").Temperature(0.0).MaxTokens(64).AsUri())
// Hop 2 — translate the previous reply.
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Translate the user's text to French. Reply with the translation only, no preamble.")
.To(LlmDsl.Factory("groq").Temperature(0.0).MaxTokens(64).AsUri())
.To("mock:done");
});
await host.SendAsync("direct:chain",
"The quick brown fox jumps over the lazy dog every single morning before breakfast.");
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
var final = ((string)sink.ReceivedExchanges[0].In.Body!);
final.Should().NotBeNullOrWhiteSpace();
// Philosophical: French replies usually contain at least one of these tokens.
// We don't pin one specific word because models phrase things differently.
var lower = final.ToLowerInvariant();
var frenchish = new[] { "le ", "la ", "les ", "un ", "une ", "renard", "chien" };
frenchish.Any(tok => lower.Contains(tok)).Should().BeTrue(
"the second hop should yield French-shaped output, but got: {0}", final);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ClaudeChatTests.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/tests/redb.Route.Tests.Llm/DslShowcase/ClaudeChatTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Live tests against Anthropic's Claude family through the OpenAI-compatible
/// endpoint at https://api.anthropic.com/v1/. Same DSL shapes as the rest
/// of DslShowcase — a different vendor key, a different model, no other
/// changes to the route definitions. The one extension we made to support this
/// is wiring "anthropic" / "claude" into OpenAiProvider.ResolveDefaultBaseUrl.
///
/// Claude tends to be the most reliable closed-source model we have access to,
/// so this is the strict-assertion suite — the model must produce literal
/// tokens we ask for.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class ClaudeChatTests
{
[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",
"Haiku 4.5 reliably follows 'reply with the literal token X' instructions");
}
[EnvFact("REDB_LLM_ANT_API03_KEY")]
public async Task Claude_Haiku_45_Tools_LookupAgent_UsesTool()
{
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 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 = 128
});
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("Claude must call the lookup tool at least once");
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
var final = ((string)sink.ReceivedExchanges[0].In.Body!).ToLowerInvariant();
final.Should().Contain("rosebud", "the final reply must echo the tool result");
}
///
/// A larger model on a slightly fuzzier task — translate then summarize via two
/// LLM hops in one route. Loose assertion (French-shaped output) — Sonnet has
/// more degrees of freedom than Haiku and we don't want to pin specific tokens.
///
[EnvFact("REDB_LLM_ANT_API03_KEY")]
public async Task Claude_Sonnet_46_TwoHopChain_SummarizeThenTranslate()
{
await using var host = LiveLlmHost.Build()
.AddFactory("claude", new LlmConnectionFactory
{
Provider = "anthropic",
ModelId = "claude-sonnet-4-6",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"),
Temperature = 0.0,
MaxTokens = 96
});
await host.StartAsync(r =>
{
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");
});
await host.SendAsync("direct:chain",
"The quick brown fox jumps over the lazy dog every single morning before breakfast.");
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
var final = ((string)sink.ReceivedExchanges[0].In.Body!);
final.Should().NotBeNullOrWhiteSpace();
var lower = final.ToLowerInvariant();
var frenchish = new[] { "le ", "la ", "les ", "un ", "une ", "renard", "chien" };
frenchish.Any(tok => lower.Contains(tok)).Should().BeTrue(
"the second hop should yield French-shaped output, but got: {0}", final);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/DeepSeekGovernanceLiveTests.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/tests/redb.Route.Tests.Llm/DslShowcase/DeepSeekGovernanceLiveTests.cs
----
using System.Security.Claims;
using redb.Route.Abstractions;
using redb.Route.Llm.Abstractions.Tools;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Live governance: a real model, a real tool loop, a real claim check — the level every other live test
/// skips, because they prove the transport and this proves the policy. The key is DeepSeek's (the one
/// provider whose key is valid in this environment); the behaviour under test is provider-independent.
///
/// The caller's scope is put on the exchange the way a transport would (a property, see
/// ), and the tool declares what it needs — so the two runs below differ in
/// exactly one thing: whether the principal holds that scope.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class DeepSeekGovernanceLiveTests
{
private const string Schema =
"""{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}""";
private const string ToolName = "order_lookup";
private const string Claim = "orders:read";
private static LlmConnectionFactory DeepSeek() => new()
{
Provider = "deepseek",
ModelId = "deepseek-flash",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_DEEPSEEK"),
Temperature = 0.0,
MaxTokens = 256
};
private static ClaimsPrincipal Caller(string scope) =>
new(new ClaimsIdentity([new Claim("scope", scope)], authenticationType: "live-test"));
private static async Task<(ToolInvocationSpy Spy, EchoToolRoute Tool, LiveLlmHost Host)> RunAsync(string grantedScope)
{
var spy = new ToolInvocationSpy();
var tool = new EchoToolRoute(ToolName, "Look up an order by id and return its status.",
Schema, """{"status":"shipped"}""", requiredClaims: [Claim]);
var host = await LiveLlmHost.Build(spy, claimsSource: new ExchangePrincipalClaimsSource())
.AddFactory("deepseek", DeepSeek())
.StartAsync(tool, r => r.From("direct:agent")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
$"Use the {ToolName} tool to look up the order, then reply with only the status word.")
.To(LlmDsl.Factory("deepseek").Tools(ToolName).MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "What is the status of order 42?",
configure: ex => ExchangePrincipal.Set(ex, Caller(grantedScope)));
return (spy, tool, host);
}
[EnvFact("REDB_LLM_DEEPSEEK")]
public async Task DeepSeek_ClaimRequiredTool_RunsForACallerHoldingTheScope()
{
var (spy, tool, host) = await RunAsync(Claim);
await using var _ = host;
spy.ForTool(ToolName).Should().NotBeEmpty(
"the model must call the tool, and the caller's scope satisfies its requirement");
spy.ForTool(ToolName).Should().OnlyContain(o => !o.Skipped);
tool.CapturedInputs.Should().HaveCount(1, "the tool route actually ran");
tool.CapturedInputs[0].Should().Contain("42").And.Contain("orderId");
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("shipped",
"the answer the model produced carries the tool's output");
}
[EnvFact("REDB_LLM_DEEPSEEK")]
public async Task DeepSeek_ClaimRequiredTool_IsDeniedForACallerWithoutTheScope()
{
// The caller is authenticated and holds a different scope. The model still asks for the tool — and
// the engine refuses the call, so the tool route never runs; what the observer sees is a skip with a
// machine-readable reason, not an invocation.
var (spy, tool, host) = await RunAsync("billing:read");
await using var _ = host;
spy.ForTool(ToolName).Should().NotBeEmpty("the model asked for the tool — a refusal is not a silent drop");
spy.ForTool(ToolName).Should().OnlyContain(o => o.Skipped);
spy.ForTool(ToolName).Last().SkipReason.Should().StartWith(ToolSkipReasons.ClaimsMissing,
"the refusal carries the reason an audit dashboard filters on");
tool.CapturedInputs.Should().BeEmpty("refused means the tool route never executed");
host.Mock("mock:done").ReceivedCount.Should().Be(1,
"the run finishes and the model answers — a refusal is a tool_result, not a crash");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/DeepSeekStreamLiveTests.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/tests/redb.Route.Tests.Llm/DslShowcase/DeepSeekStreamLiveTests.cs
----
using System.Text;
using redb.Route.Llm.Engine.Observability;
using redb.Route.Tests.Llm.TestHelpers;
using Xunit.Abstractions;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// The streamed parsers and the cache counters against a live provider. One DeepSeek key reaches both parsers:
/// the OpenAI-compatible API at api.deepseek.com and the Anthropic Messages API at
/// api.deepseek.com/anthropic. The offline tests prove the parsers on recorded shapes; these prove them on the
/// wire, through the package's own transport (HTTP/2, keep-alive pings, call limits).
///
/// Nothing here prints the key or the model's text: the output carries counts and lengths.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class DeepSeekStreamLiveTests
{
private const string EnvVar = "REDB_LLM_DEEPSEEK";
private const string Model = "deepseek-flash";
private static readonly Uri AnthropicBaseUrl = new("https://api.deepseek.com/anthropic/");
private readonly ITestOutputHelper _output;
/// Creates the tests with xUnit's output sink.
public DeepSeekStreamLiveTests(ITestOutputHelper output) => _output = output;
private static string Key => Environment.GetEnvironmentVariable(EnvVar)!;
private static LlmConnectionFactory OpenAiFactory() => new()
{
Name = "deepseek-live",
Provider = "deepseek",
ModelId = Model,
ApiKey = Key,
MaxTokens = 1024
};
private static LlmConnectionFactory AnthropicFactory() => new()
{
Name = "deepseek-anthropic-live",
Provider = "anthropic",
ModelId = Model,
ApiKey = Key,
BaseUrl = AnthropicBaseUrl,
MaxTokens = 1024
};
private static LlmRequest Question(string? system = null) => new()
{
SystemPrompt = system,
Messages = [LlmMessage.User("What is 2 + 2? Answer with the digit only.")],
MaxTokens = 1024
};
/// Streams the question and checks the assembled answer against the pieces that made it.
private async Task StreamedAnswerMatchesItsPiecesAsync(ILlmProvider provider)
{
var text = new StringBuilder();
var thinking = new StringBuilder();
var pieces = 0;
LlmResponse? answer = null;
await foreach (var chunk in provider.StreamAsync(Question()))
{
foreach (var piece in chunk.Content)
{
if (chunk.Response is not null) break;
switch (piece)
{
case LlmTextBlock t: text.Append(t.Text); pieces++; break;
case LlmThinkingBlock th: thinking.Append(th.Text); pieces++; break;
}
}
if (chunk.Response is not null) answer = chunk.Response;
}
answer.Should().NotBeNull($"{provider.ProviderId}: the last chunk carries the assembled answer");
var assembledText = string.Concat(answer!.Content.OfType().Select(b => b.Text));
var assembledThinking = string.Concat(answer.Content.OfType().Select(b => b.Text));
_output.WriteLine(
$"{provider.ProviderId}: pieces={pieces}, text={assembledText.Length} chars, thinking={assembledThinking.Length} chars, "
+ $"blocks=[{string.Join(",", answer.Content.Select(b => b.GetType().Name))}], stop={answer.RawStopReason}, "
+ $"usage in/out/cacheRead={answer.Usage.InputTokens}/{answer.Usage.OutputTokens}/{answer.Usage.CacheReadInputTokens}");
pieces.Should().BeGreaterThan(1, "the answer arrived in pieces");
answer.StopReason.Should().Be(LlmStopReason.EndTurn);
text.ToString().Should().Be(assembledText, "the assembled text is exactly the text that streamed");
thinking.ToString().Should().Be(assembledThinking, "the assembled thinking is exactly the thinking that streamed");
assembledText.Should().Contain("4");
answer.Usage.OutputTokens.Should().BeGreaterThan(0, "the terminal usage reached the answer");
}
[EnvFact(EnvVar)]
public Task OpenAiPath_StreamedAnswer_MatchesItsPieces() =>
StreamedAnswerMatchesItsPiecesAsync(OpenAiProvider.Create(OpenAiFactory()));
[EnvFact(EnvVar)]
public Task AnthropicPath_StreamedAnswer_MatchesItsPieces() =>
StreamedAnswerMatchesItsPiecesAsync(new AnthropicProvider(AnthropicFactory()));
/// A prefix of a few thousand tokens that no earlier run has sent: it starts with this run's id.
private static string LongPrefix()
{
var sb = new StringBuilder($"Run {Guid.NewGuid():N}. You answer arithmetic questions with the digit only.\n");
for (var i = 1; i <= 300; i++)
sb.Append("Rule ").Append(i).Append(": keep the answer short, exact and free of any explanation.\n");
return sb.ToString();
}
[EnvFact(EnvVar)]
public async Task OpenAiPath_RepeatedPrefix_IsReadFromCache()
{
var provider = OpenAiProvider.Create(OpenAiFactory());
var request = Question(LongPrefix());
var first = await provider.CompleteAsync(request);
_output.WriteLine($"first: in={first.Usage.InputTokens}, cacheRead={first.Usage.CacheReadInputTokens}");
first.Usage.CacheReadInputTokens.Should().Be(0, "the prefix starts with this run's id, so nothing of it was cached");
// The provider stores the prefix after the first call; a later call reads it. Give it a few tries.
LlmUsage? cached = null;
for (var attempt = 1; attempt <= 4 && cached is null; attempt++)
{
await Task.Delay(TimeSpan.FromSeconds(2));
var again = await provider.CompleteAsync(request);
_output.WriteLine($"plain #{attempt}: in={again.Usage.InputTokens}, cacheRead={again.Usage.CacheReadInputTokens}");
if (again.Usage.CacheReadInputTokens > 0) cached = again.Usage;
}
cached.Should().NotBeNull("DeepSeek serves a repeated prefix from cache and says so in usage (issue #11)");
cached!.InputTokens.Should().BeLessThan(cached.CacheReadInputTokens,
"InputTokens is the remainder billed at full price, and most of this prompt came from cache");
LlmResponse? streamed = null;
await foreach (var chunk in provider.StreamAsync(request))
if (chunk.Response is not null) streamed = chunk.Response;
_output.WriteLine($"streamed: in={streamed!.Usage.InputTokens}, cacheRead={streamed.Usage.CacheReadInputTokens}");
streamed.Usage.CacheReadInputTokens.Should().BeGreaterThan(0, "the streamed call reports the cache the same way");
}
/// Counts the pieces the engine hands on.
private sealed class PieceCounter : IAgentObserver
{
private int _text;
private int _thinking;
public int Text => Volatile.Read(ref _text);
public int Thinking => Volatile.Read(ref _thinking);
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;
public Task OnDeltaAsync(AgentDeltaContext context, CancellationToken ct = default)
{
if (context.Kind == AgentDeltaKind.Text) Interlocked.Increment(ref _text);
else Interlocked.Increment(ref _thinking);
return Task.CompletedTask;
}
}
[EnvFact(EnvVar)]
public async Task StreamCalls_ToolLoop_EndToEnd()
{
const string schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
var tool = new EchoToolRoute("lookup", "Looks up the stored answer for a key. Always call it before answering.",
schema, """{"answer":"42"}""");
var counter = new PieceCounter();
await using var host = LiveLlmHost.Build(counter).AddFactory("ds", OpenAiFactory());
await host.StartAsync(tool, r => r.From("direct:agent")
.To("llm://ds?stream=calls&tools=lookup&maxIterations=4")
.To("mock:done"));
await host.SendAsync("direct:agent",
"Call the lookup tool with q = \"life\", then tell me the answer it returned, digits only.");
var answer = host.Mock("mock:done").ReceivedExchanges.Single().In.Body as string;
_output.WriteLine($"tool calls={tool.CapturedInputs.Count}, text pieces={counter.Text}, thinking pieces={counter.Thinking}, answer={answer?.Length} chars");
tool.CapturedInputs.Should().NotBeEmpty("the streamed tool loop dispatched the tool");
answer.Should().Contain("42", "the model answered with what the tool returned");
// A two-character answer may arrive as one text piece; the run as a whole still streams, thinking included.
counter.Text.Should().BeGreaterThan(0, "the answer reached the observer as it was written");
(counter.Text + counter.Thinking).Should().BeGreaterThan(1, "the run reached the observer in pieces, not as one block");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/EmbedSchemeTests.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/tests/redb.Route.Tests.Llm/DslShowcase/EmbedSchemeTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Llm;
using redb.Route.Llm.Embeddings;
using redb.Route.Llm.Providers;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// embed://<factory> scheme — embeds the exchange body via the named
/// connection factory. Driven with a stub
/// (no live endpoint): a single text → float[], a collection → float[][].
///
public sealed class EmbedSchemeTests
{
// Deterministic stub: vector = [text length, input index].
private sealed class StubEmb : IEmbeddingProvider
{
public string ProviderId => "stub";
public string ModelId => "stub-model";
public Task> EmbedAsync(IReadOnlyList inputs, CancellationToken ct = default)
=> Task.FromResult>(
inputs.Select((s, i) => new float[] { s.Length, i }).ToArray());
}
private static (RouteContext Ctx, ProducerTemplate Producer) Host(EmbedComponent component)
{
var sp = new ServiceCollection().BuildServiceProvider();
var ctx = new RouteContext(sp, contextId: "embed-scheme-test");
ctx.AddToRegistry("emb", new LlmConnectionFactory
{
Provider = "openai", ModelId = "text-embedding-3-small", ApiKey = "sk-test"
});
ctx.AddComponent(component);
var producer = new ProducerTemplate(ctx);
ctx.AddService(typeof(IProducerTemplate), producer);
return (ctx, producer);
}
[Fact]
public async Task SingleText_ProducesFloatVector()
{
var (ctx, producer) = Host(new EmbedComponent { ProviderFactory = _ => new StubEmb() });
ctx.AddRoutes(r => r.From("direct:e").To("embed://emb"));
await ctx.Start();
producer.Start();
var result = await producer.RequestBody("direct:e", "hello"); // 5 chars
result.Should().BeOfType();
((float[])result!).Should().Equal(5f, 0f);
await ctx.DisposeAsync();
}
[Fact]
public async Task ManyTexts_ProduceVectorArray_OrderPreserved()
{
var (ctx, producer) = Host(new EmbedComponent { ProviderFactory = _ => new StubEmb() });
ctx.AddRoutes(r => r.From("direct:e2").To("embed://emb"));
await ctx.Start();
producer.Start();
var result = await producer.RequestBody("direct:e2", new List { "ab", "cde" });
result.Should().BeOfType();
var vecs = (float[][])result!;
vecs.Should().HaveCount(2);
vecs[0].Should().Equal(2f, 0f); // "ab" → len 2, index 0
vecs[1].Should().Equal(3f, 1f); // "cde" → len 3, index 1
await ctx.DisposeAsync();
}
[Fact]
public async Task PerRoute_ResolvesNamedFactory()
{
LlmConnectionFactory? seen = null;
var (ctx, producer) = Host(new EmbedComponent { ProviderFactory = f => { seen = f; return new StubEmb(); } });
ctx.AddRoutes(r => r.From("direct:e3").To("embed://emb"));
await ctx.Start();
producer.Start();
await producer.RequestBody("direct:e3", "x");
seen.Should().NotBeNull();
seen!.ModelId.Should().Be("text-embedding-3-small"); // the factory named by embed://emb
await ctx.DisposeAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ExecShellToolTests.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/tests/redb.Route.Tests.Llm/DslShowcase/ExecShellToolTests.cs
----
using redb.Route.Configuration;
using redb.Route.Exec;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Live integration test: a Claude agent calls a shell tool that is wired through
/// the brand-new . The whole shape mirrors the existing
/// pattern — except that the tool's body is a real
/// exec://run producer with an allowlist on the host commands.
///
/// What this proves:
///
/// - The exec connector is reachable from direct: via .AsLlmTool.
/// - Claude correctly emits {"command":"...","args":[...]} and the producer
/// deserializes it without manual glue.
/// - The allowlist enforces the security envelope — a model trying to call
/// anything other than the listed commands would be rejected.
/// - The JSON response shape is what the agent loop expects, so the model can
/// read back stdout and reply to the user.
///
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class ExecShellToolTests
{
private static bool IsWindows => OperatingSystem.IsWindows();
[EnvFact("REDB_LLM_ANT_API03_KEY")]
public async Task Claude_Haiku_45_ShellTool_RunsAllowedCommand_AndEchoesStdout()
{
var shell = new ShellToolRoute();
await using var host = LiveLlmHost.Build();
// Mount the exec component on the live host context — the LiveLlmHost
// base build only registers the LLM component by default.
host.Context.AddComponent(new ExecComponent());
host.AddFactory("claude", new LlmConnectionFactory
{
Provider = "anthropic",
ModelId = "claude-haiku-4-5",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"),
Temperature = 0.0,
MaxTokens = 256
});
await host.StartAsync(shell, r =>
{
r.From("direct:agent")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Use the shell tool to print the literal token 'redb-shell-ok' to stdout. " +
"After receiving the tool's stdout, reply with that exact token and nothing else.")
.To(LlmDsl.Factory("claude").Tools("shell").MaxIterations(4).AsUri())
.To("mock:done");
});
await host.SendAsync("direct:agent", "Print 'redb-shell-ok'.");
// The model must have invoked the shell tool at least once.
shell.LastStdout.Should().NotBeNull("Claude must call the shell tool");
shell.LastStdout.Should().Contain("redb-shell-ok",
"the shell tool must have echoed our literal token");
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
var final = ((string)sink.ReceivedExchanges[0].In.Body!).ToLowerInvariant();
final.Should().Contain("redb-shell-ok",
"the agent's final reply must echo what the shell tool produced");
}
///
/// Tool route that dispatches to exec://run with a tight allowlist. The route
/// captures the producer's stdout for assertions — production usage would skip the
/// capture and just chain to whatever sink the route needs.
///
private sealed class ShellToolRoute : RouteBuilder
{
public string? LastStdout { get; private set; }
protected override void Configure()
{
// Same description-and-schema shape any LLM tool ABI expects.
// Allowlist is the security envelope — anything outside this list is rejected
// before the OS process ever starts.
From("direct:tool-shell")
.AsLlmTool("shell")
.Description(
"Run a small shell command. Input: {\"command\":\"\",\"args\":[\"...\"]}. " +
"Output: {\"stdout\":\"...\",\"stderr\":\"...\",\"exitCode\":N}. " +
$"Allowed commands: {(IsWindows ? "cmd" : "sh")}.")
.Input("""
{
"type": "object",
"properties": {
"command": { "type": "string" },
"args": { "type": "array", "items": { "type": "string" } }
},
"required": ["command"]
}
""")
.SideEffect(ToolSideEffect.ReadOnly)
.Cost(ToolCostClass.Cheap)
.Then()
.To(ExecDsl.Run()
.AllowedCommands(IsWindows ? "cmd" : "sh")
.TimeoutMs(5_000)
.MaxStdoutBytes(8_192)
.MaxStderrBytes(8_192))
.Process(e =>
{
// Capture for the test — never required in production tool routes.
// PipelineProcessor merges Out → In between steps, so the producer's
// headers land on e.In here, not e.Out.
if (e.In.Headers.TryGetValue(ExecHeaders.Stdout, out var s) && s is string str)
LastStdout = str;
});
}
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/HttpFetchToolTests.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/tests/redb.Route.Tests.Llm/DslShowcase/HttpFetchToolTests.cs
----
using redb.Route.Llm.Tools;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Demonstrates the canonical pre-built tool from redb.Route.Llm.Tools:
/// . The chat route is unchanged from the basic
/// shape; the only addition is registering http_fetch in the tool
/// filter.
///
/// We deliberately script the provider with here:
/// free-tier models call HTTP tools inconsistently (URLs get truncated, schemas
/// drift), and this suite is about DSL + tool wiring + real HTTP fetch,
/// not about whether a 7B free model copies a URL byte-for-byte.
/// covers the live tool-loop end-to-end.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class HttpFetchToolTests
{
[Fact]
public async Task HttpFetchTool_PluggedIntoRoute_FetchesAndReturnsBody()
{
// Local HTTP server stands in for an external API.
using var server = new LocalHttpServer
{
ResponseBody = """{"secret":"unicorn"}"""
};
var url = server.BaseUrl + "secrets";
// Scripted provider: turn 1 calls the tool, turn 2 returns the secret.
var fake = new FakeProvider()
.EnqueueToolUse("http_fetch", $"{{\"url\":\"{url}\"}}")
.EnqueueText("the secret is unicorn");
await using var host = LiveLlmHost.Build()
.AddFactory("scripted", new LlmConnectionFactory
{
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
var fetch = new HttpFetchTool(new HttpFetchOptions
{
HostAllowlist = new[] { server.Host },
Timeout = TimeSpan.FromSeconds(5)
});
await host.StartAsync(fetch, r =>
{
r.From("direct:agent")
.To(LlmDsl.Factory("scripted").Tools("http_fetch").MaxIterations(4).AsUri())
.To("mock:done");
});
await host.SendAsync("direct:agent", "Fetch the secret.");
// 1. Tool was registered.
host.ToolRegistry.Get("http_fetch").Should().NotBeNull();
// 2. The local HTTP server was hit by the tool.
server.RequestPaths.Should().ContainSingle().Which.Should().Contain("/secrets");
// 3. The tool result flowed back into the next provider call.
fake.CallCount.Should().Be(2);
fake.CapturedRequests[^1].Messages
.SelectMany(m => m.Content)
.OfType()
.Should().ContainSingle()
.Which.OutputJson.Should().Contain("unicorn");
// 4. The final assistant text rotated through to the mock sink.
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("unicorn");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/InlineLlmTests.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/tests/redb.Route.Tests.Llm/DslShowcase/InlineLlmTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Shows the second flavor of LLM step: an inline .Llm(name, b => ...)
/// fluent call instead of a llm:// URI. Functionally equivalent to
/// but reads more naturally when the route has a
/// strong opinion about parameters (system prompt, max iterations, etc.).
///
/// We keep one strict assertion (Groq must produce the literal token) and one
/// philosophical assertion (Mistral must produce some reply), mirroring
/// the spectrum of free-tier reliability we see in practice.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class InlineLlmTests
{
[EnvFact("REDB_LLM_GROQ_KEY")]
public async Task Groq_InlineLlm_Step_DeliversAnswer()
{
await using var host = LiveLlmHost.Build()
.AddFactory("groq", new LlmConnectionFactory
{
Provider = "groq",
ModelId = "llama-3.3-70b-versatile",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"),
Temperature = 0.0,
MaxTokens = 16
});
await host.StartAsync(r =>
{
r.From("direct:chat")
.Llm("groq", b => b
.WithSystemPrompt("Reply with exactly one lowercase word: pong. No punctuation.")
.WithTemperature(0.0)
.WithMaxTokens(16))
.To("mock:result");
});
await host.SendAsync("direct:chat", "Say the word.");
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");
}
[EnvFact("REDB_LLM_MISTRAL_KEY")]
public async Task Mistral_InlineLlm_Step_DeliversNonEmptyReply()
{
await using var host = LiveLlmHost.Build()
.AddFactory("mistral", new LlmConnectionFactory
{
Provider = "mistral",
ModelId = "mistral-small-latest",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_MISTRAL_KEY"),
Temperature = 0.0,
MaxTokens = 32
});
await host.StartAsync(r =>
{
r.From("direct:chat")
.Llm("mistral", b => b
.WithSystemPrompt("Reply with one short sentence in plain English.")
.WithMaxTokens(32))
.To("mock:result");
});
await host.SendAsync("direct:chat", "Greet me.");
var sink = host.Mock("mock:result");
sink.ReceivedCount.Should().Be(1);
((string)sink.ReceivedExchanges[0].In.Body!).Should().NotBeNullOrWhiteSpace();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeIngestTests.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/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeIngestTests.cs
----
using System.Text.Json;
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Llm.Knowledge;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// knowledge:// ingest producer — To("knowledge://coll") chunks the
/// document body and upserts into the resolved .
/// Driven through a bare + ,
/// no LLM provider.
///
public sealed class KnowledgeIngestTests
{
private static (RouteContext Ctx, ProducerTemplate Producer, IKnowledgeStore Store) BuildHost()
{
var sp = new ServiceCollection().BuildServiceProvider();
var ctx = new RouteContext(sp, contextId: "knowledge-ingest-test");
IKnowledgeStore store = new InMemoryKnowledgeStore();
ctx.AddService(typeof(IKnowledgeStore), store);
ctx.AddComponent(new KnowledgeComponent());
var producer = new ProducerTemplate(ctx);
ctx.AddService(typeof(IProducerTemplate), producer);
return (ctx, producer, store);
}
[Fact]
public async Task Ingest_ChunksDocument_UpsertsAndIsSearchable()
{
var (ctx, producer, store) = BuildHost();
ctx.AddRoutes(r => r.From("direct:ingest").To("knowledge://kb?chunkChars=40&overlap=0"));
await ctx.Start();
producer.Start();
const string text =
"The mask breaks the name and speech. The idol breeds the fear of death. The rift loses meaning.";
var reply = (string)(await producer.RequestBody("direct:ingest", text))!;
var summary = JsonDocument.Parse(reply).RootElement;
summary.GetProperty("collection").GetString().Should().Be("kb");
summary.GetProperty("chunks").GetInt32().Should().BeGreaterThan(1); // ~95 chars / 40 → 3 chunks
var hits = await store.SearchTextAsync("idol", 10, "kb");
hits.Should().NotBeEmpty();
hits[0].Chunk.Collection.Should().Be("kb");
await ctx.DisposeAsync();
}
[Fact]
public async Task Reingest_SameDocId_ReplacesChunksInPlace()
{
var (ctx, producer, store) = BuildHost();
// one chunk per doc (large chunkChars), stable docId → id "d1#0"
ctx.AddRoutes(r => r.From("direct:ingest2").To("knowledge://kb?chunkChars=1000&docId=d1"));
await ctx.Start();
producer.Start();
await producer.RequestBody("direct:ingest2", "first version about apples");
(await store.SearchTextAsync("apples", 10, "kb")).Should().ContainSingle();
await producer.RequestBody("direct:ingest2", "second version about bananas");
(await store.SearchTextAsync("apples", 10, "kb")).Should().BeEmpty(); // replaced
(await store.SearchTextAsync("bananas", 10, "kb")).Should().ContainSingle();
await ctx.DisposeAsync();
}
[Fact]
public void Chunker_WindowsWithOverlap()
{
KnowledgeChunker.Split("abcdefghij", chunkChars: 4, overlap: 0)
.Should().Equal("abcd", "efgh", "ij");
KnowledgeChunker.Split("abcdefghij", chunkChars: 4, overlap: 2)
.Should().Equal("abcd", "cdef", "efgh", "ghij");
KnowledgeChunker.Split("short", chunkChars: 100, overlap: 0)
.Should().Equal("short");
KnowledgeChunker.Split(" ", chunkChars: 10, overlap: 0)
.Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeRetrievalTests.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/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeRetrievalTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Llm;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Llm.Knowledge;
using redb.Route.Llm.Providers;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// .Knowledge(collection, k) — retrieves top-K chunks for the current message
/// and injects them into the system prompt before a downstream .To("llm://").
///
public sealed class KnowledgeRetrievalTests
{
private sealed class StubEmb(Dictionary map) : IEmbeddingProvider
{
public string ProviderId => "stub";
public string ModelId => "stub";
public Task> EmbedAsync(IReadOnlyList inputs, CancellationToken ct = default)
=> Task.FromResult>(
inputs.Select(i => map.TryGetValue(i, out var v) ? v : new float[] { 0f, 0f }).ToArray());
}
private static (RouteContext Ctx, ProducerTemplate Producer) Host()
{
var sp = new ServiceCollection().BuildServiceProvider();
var ctx = new RouteContext(sp, contextId: "knowledge-retrieval-test");
var producer = new ProducerTemplate(ctx);
ctx.AddService(typeof(IProducerTemplate), producer);
return (ctx, producer);
}
private static async Task Seed(params (string Id, string Text, float[]? Emb)[] chunks)
{
IKnowledgeStore store = new InMemoryKnowledgeStore();
await store.UpsertManyAsync(chunks.Select(c => new KnowledgeChunk
{
Id = c.Id, Text = c.Text, Collection = "kb", Embedding = c.Emb ?? Array.Empty()
}));
return store;
}
[Fact]
public async Task Keyword_InjectsRetrievedChunks_IntoSystemPrompt()
{
var store = await Seed(("1", "apples grow on trees", null), ("2", "bananas are yellow", null));
var (ctx, producer) = Host();
ctx.AddRoutes(r => r.From("direct:q")
.Knowledge(new KnowledgeRetrievalOptions { Collection = "kb", TopK = 3, Store = store })
.Process(e => e.In.Body = e.In.Headers.TryGetValue(LlmHeaders.SystemPrompt, out var sp) ? sp : "(none)"));
await ctx.Start();
producer.Start();
var result = (string)(await producer.RequestBody("direct:q", "apples"))!;
result.Should().Contain("apples grow on trees");
result.Should().NotContain("bananas");
await ctx.DisposeAsync();
}
[Fact]
public async Task Semantic_UsesEmbeddings_NotSubstring()
{
var store = await Seed(("cats", "about cats", new[] { 1f, 0f }), ("dogs", "about dogs", new[] { 0f, 1f }));
var emb = new StubEmb(new() { ["feline pets"] = new[] { 0.9f, 0.1f } });
var (ctx, producer) = Host();
ctx.AddRoutes(r => r.From("direct:q2")
.Knowledge(new KnowledgeRetrievalOptions { Collection = "kb", TopK = 1, Store = store, EmbeddingProvider = emb })
.Process(e => e.In.Body = e.In.Headers.TryGetValue(LlmHeaders.SystemPrompt, out var sp) ? sp : "(none)"));
await ctx.Start();
producer.Start();
var result = (string)(await producer.RequestBody("direct:q2", "feline pets"))!;
result.Should().Contain("about cats"); // semantic match, query shares no keyword
await ctx.DisposeAsync();
}
[Fact]
public async Task AugmentsExistingSystemPrompt()
{
var store = await Seed(("1", "apples grow on trees", null));
var (ctx, producer) = Host();
ctx.AddRoutes(r => r.From("direct:q3")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "You are helpful.")
.Knowledge(new KnowledgeRetrievalOptions { Collection = "kb", Store = store })
.Process(e => e.In.Body = e.In.Headers[LlmHeaders.SystemPrompt]));
await ctx.Start();
producer.Start();
var result = (string)(await producer.RequestBody("direct:q3", "apples"))!;
result.Should().StartWith("You are helpful.");
result.Should().Contain("apples grow on trees");
await ctx.DisposeAsync();
}
[Fact]
public async Task NoStore_IsNoOp()
{
var (ctx, producer) = Host();
ctx.AddRoutes(r => r.From("direct:q4")
.Knowledge(new KnowledgeRetrievalOptions { Collection = "kb" }) // no store, no DI
.Process(e => e.In.Body = e.In.Headers.ContainsKey(LlmHeaders.SystemPrompt) ? "injected" : "clean"));
await ctx.Start();
producer.Start();
((string)(await producer.RequestBody("direct:q4", "apples"))!).Should().Be("clean");
await ctx.DisposeAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeSearchToolTests.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/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeSearchToolTests.cs
----
using System.Text.Json;
using AwesomeAssertions;
using redb.Route.Llm.Abstractions.Tools;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Llm.Providers;
using redb.Route.Llm.Tools;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Drives the knowledge_search tool () straight
/// through the route pipeline — a direct: route mounted via .AsLlmTool(...)
/// over . No LLM provider involved.
///
public sealed class KnowledgeSearchToolTests
{
private static async Task SeededStore(params (string Id, string Text, string? Collection)[] chunks)
{
IKnowledgeStore store = new InMemoryKnowledgeStore();
await store.UpsertManyAsync(chunks.Select(c => new KnowledgeChunk
{
Id = c.Id,
Text = c.Text,
Collection = c.Collection,
Embedding = new float[] { 0f }
}));
return store;
}
[Fact]
public async Task RegistersDescriptor_AndReturnsRankedHits()
{
var store = await SeededStore(
("1", "Apples grow on trees.", "fruit"),
("2", "apple, apple, apple pie.", "fruit"),
("3", "The office is downtown.", "misc"));
await using var host = LiveLlmHost.Build();
await host.StartAsync(new KnowledgeSearchTool(new KnowledgeSearchOptions { Store = store }));
var descriptor = host.ToolRegistry.Get("knowledge_search");
descriptor.Should().NotBeNull();
descriptor!.Capability.Safety.SideEffect.Should().Be(ToolSideEffect.ReadOnly);
var ex = await host.SendAsync("direct:llm.knowledge_search", """{"query":"apple"}""");
var results = JsonDocument.Parse((string)ex.Out!.Body!).RootElement.GetProperty("results");
results.GetArrayLength().Should().Be(2); // #1 and #2 contain "apple"
results[0].GetProperty("id").GetString().Should().Be("2"); // 3 occurrences rank first
ex.Out.Headers["llm.knowledge_search.hits"].Should().Be(2);
}
[Fact]
public async Task PinnedCollection_IgnoresModelSuppliedCollection()
{
var store = await SeededStore(
("a", "a shared term", "alpha"),
("b", "a shared term", "beta"));
await using var host = LiveLlmHost.Build();
await host.StartAsync(new KnowledgeSearchTool(
new KnowledgeSearchOptions { Store = store, Collection = "beta" }));
// The model asks for alpha, but the tool is pinned to beta — pin wins.
var ex = await host.SendAsync("direct:llm.knowledge_search",
"""{"query":"shared","collection":"alpha"}""");
var results = JsonDocument.Parse((string)ex.Out!.Body!).RootElement.GetProperty("results");
results.GetArrayLength().Should().Be(1);
results[0].GetProperty("id").GetString().Should().Be("b");
}
private sealed class StubEmbeddingProvider(Dictionary map) : IEmbeddingProvider
{
public string ProviderId => "stub";
public string ModelId => "stub";
public Task> EmbedAsync(IReadOnlyList inputs, CancellationToken ct = default)
=> Task.FromResult>(
inputs.Select(i => map.TryGetValue(i, out var v) ? v : new float[] { 0f, 0f }).ToArray());
}
[Fact]
public async Task SemanticMode_RanksByCosine_NotKeyword()
{
IKnowledgeStore store = new InMemoryKnowledgeStore();
await store.UpsertManyAsync(new[]
{
new KnowledgeChunk { Id = "cats", Text = "about cats", Collection = "kb", Embedding = new float[] { 1f, 0f } },
new KnowledgeChunk { Id = "dogs", Text = "about dogs", Collection = "kb", Embedding = new float[] { 0f, 1f } },
});
// The query shares NO keyword with the chunk texts, but embeds near "cats".
var emb = new StubEmbeddingProvider(new() { ["feline pets"] = new[] { 0.9f, 0.1f } });
await using var host = LiveLlmHost.Build();
await host.StartAsync(new KnowledgeSearchTool(new KnowledgeSearchOptions
{
Store = store, Collection = "kb", EmbeddingProvider = emb
}));
var ex = await host.SendAsync("direct:llm.knowledge_search", """{"query":"feline pets","top_k":1}""");
var results = JsonDocument.Parse((string)ex.Out!.Body!).RootElement.GetProperty("results");
results.GetArrayLength().Should().Be(1);
results[0].GetProperty("id").GetString().Should().Be("cats"); // semantic, not substring
}
[Fact]
public async Task NoMatch_ReturnsEmptyResults()
{
var store = await SeededStore(("1", "apple and banana", null));
await using var host = LiveLlmHost.Build();
await host.StartAsync(new KnowledgeSearchTool(new KnowledgeSearchOptions { Store = store }));
var ex = await host.SendAsync("direct:llm.knowledge_search", """{"query":"zebra"}""");
JsonDocument.Parse((string)ex.Out!.Body!).RootElement.GetProperty("results")
.GetArrayLength().Should().Be(0);
ex.Out.Headers["llm.knowledge_search.hits"].Should().Be(0);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/LiveToolInvocationTests.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/tests/redb.Route.Tests.Llm/DslShowcase/LiveToolInvocationTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Live integration suite that drives every redb.Route.Llm.Tools utility tool
/// through a real provider's tool-use loop. Each test:
///
/// - Mounts the production tool route via new XxxTool(...).
/// - Hooks a so we can prove the model called the tool.
/// - Configures an agent that exposes only that one tool.
/// - Sends a question whose answer the model cannot reliably guess without the tool —
/// the prompt embeds a fact the model would otherwise have to fabricate or compute.
/// - Asserts both the invocation happened and the final reply carries the tool's output.
///
///
/// We use Groq llama-3.3-70b-versatile for the deterministic tools because its
/// free-tier tool-use is the most reliable mix we have. Tavily uses Claude — Anthropic
/// is the most consistent provider for chained tool-use that summarises external content.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class LiveToolInvocationTests
{
[EnvFact("REDB_LLM_GROQ_KEY")]
public async Task Groq_JsonPathTool_ExtractsValueFromEmbeddedJson()
{
var spy = new ToolInvocationSpy();
await using var host = LiveLlmHost.Build(spy)
.AddFactory("groq", new LlmConnectionFactory
{
Provider = "groq",
ModelId = "llama-3.3-70b-versatile",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"),
Temperature = 0.0,
MaxTokens = 256
});
await host.StartAsync(new JsonPathTool(), r =>
{
r.From("direct:agent")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Use the json_path tool when you need to read a specific value from a JSON document. " +
"Reply with only the extracted value, no quotes, no extra words.")
.To(LlmDsl.Factory("groq").Tools("json_path").MaxIterations(4).AsUri())
.To("mock:done");
});
var question =
"Given this JSON: {\"order\":{\"items\":[{\"sku\":\"X-1\",\"qty\":3},{\"sku\":\"Z-9\",\"qty\":11}]}}. " +
"What is the SKU of the second item? Use the json_path tool with path $.order.items[1].sku.";
await host.SendAsync("direct:agent", question);
spy.ForTool("json_path").Should().NotBeEmpty("the model must call json_path");
var lastOutput = spy.ForTool("json_path").Last().OutputJson ?? "";
lastOutput.Should().Contain("Z-9");
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("Z-9");
}
[EnvFact("REDB_LLM_GROQ_KEY")]
public async Task Groq_XPathTool_ExtractsValueFromEmbeddedXml()
{
var spy = new ToolInvocationSpy();
await using var host = LiveLlmHost.Build(spy)
.AddFactory("groq", new LlmConnectionFactory
{
Provider = "groq",
ModelId = "llama-3.3-70b-versatile",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"),
Temperature = 0.0,
MaxTokens = 512
});
await host.StartAsync(new XPathTool(), r =>
{
r.From("direct:agent")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"You must use the xpath tool to read values from XML. " +
"After the tool returns its result, you MUST send a final assistant text message " +
"containing only the extracted value. Never end the conversation without that final message.")
.To(LlmDsl.Factory("groq").Tools("xpath").MaxIterations(6).AsUri())
.To("mock:done");
});
var question =
"Given this XML: Dune" +
"Foundation. " +
"Use the xpath tool with the expression string(//book[@id='2']/title) to read the title of book #2, " +
"then reply with just the title.";
await host.SendAsync("direct:agent", question);
spy.ForTool("xpath").Should().NotBeEmpty("the model must call xpath");
spy.ForTool("xpath").Last().OutputJson.Should().Contain("Foundation");
var sink = host.Mock("mock:done");
((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("Foundation");
}
[EnvFact("REDB_LLM_GROQ_KEY")]
public async Task Groq_MathEvalTool_ComputesNonTrivialExpression()
{
var spy = new ToolInvocationSpy();
await using var host = LiveLlmHost.Build(spy)
.AddFactory("groq", new LlmConnectionFactory
{
Provider = "groq",
ModelId = "llama-3.3-70b-versatile",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"),
Temperature = 0.0,
MaxTokens = 256
});
await host.StartAsync(new MathEvalTool(), r =>
{
r.From("direct:agent")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Always use the math_eval tool for arithmetic — never compute it yourself. " +
"Reply with only the numeric result.")
.To(LlmDsl.Factory("groq").Tools("math_eval").MaxIterations(4).AsUri())
.To("mock:done");
});
// 31337 * 271 = 8 492 327 — a value the model is unlikely to memorize, but
// ExpressionResolver computes deterministically.
await host.SendAsync("direct:agent", "What is 31337 multiplied by 271? Use the math_eval tool.");
spy.ForTool("math_eval").Should().NotBeEmpty("the model must call math_eval");
spy.ForTool("math_eval").Last().OutputJson.Should().Contain("8492327");
var sink = host.Mock("mock:done");
((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("8492327");
}
[EnvFact("REDB_LLM_GROQ_KEY")]
public async Task Groq_RegexExtractTool_ExtractsPatternFromText()
{
var spy = new ToolInvocationSpy();
await using var host = LiveLlmHost.Build(spy)
.AddFactory("groq", new LlmConnectionFactory
{
Provider = "groq",
ModelId = "llama-3.3-70b-versatile",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"),
Temperature = 0.0,
MaxTokens = 256
});
await host.StartAsync(new RegexExtractTool(), r =>
{
r.From("direct:agent")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"Use the regex_extract tool to pull a value out of a string. " +
"Reply with only the extracted value.")
.To(LlmDsl.Factory("groq").Tools("regex_extract").MaxIterations(4).AsUri())
.To("mock:done");
});
var question =
"Given the text 'order id ORD-7421 was placed at 14:55', extract the order id " +
"(matches the pattern ORD-\\d+) using the regex_extract tool.";
await host.SendAsync("direct:agent", question);
spy.ForTool("regex_extract").Should().NotBeEmpty("the model must call regex_extract");
spy.ForTool("regex_extract").Last().OutputJson.Should().Contain("ORD-7421");
var sink = host.Mock("mock:done");
((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("ORD-7421");
}
[EnvFact("REDB_LLM_ANT_API03_KEY", "REDB_LLM_TAVILY_KEY")]
public async Task Claude_TavilyWebSearchTool_AnswersFromLiveSearch()
{
var spy = new ToolInvocationSpy();
await using var host = LiveLlmHost.Build(spy)
.AddFactory("claude", new LlmConnectionFactory
{
Provider = "anthropic",
ModelId = "claude-haiku-4-5",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"),
Temperature = 0.0,
MaxTokens = 384
});
await host.StartAsync(new TavilyWebSearchTool(new TavilyWebSearchOptions
{
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_TAVILY_KEY")!,
MaxResults = 3,
Timeout = TimeSpan.FromSeconds(15)
}), r =>
{
r.From("direct:agent")
.Process(e => e.In.Headers[LlmHeaders.SystemPrompt] =
"When the user asks for current real-world facts, call the web_search tool with a focused " +
"query, then summarise the findings in one short sentence.")
.To(LlmDsl.Factory("claude").Tools("web_search").MaxIterations(4).AsUri())
.To("mock:done");
});
// A factual query whose answer is stable enough to assert on — Tavily's
// 'answer' field for capital-of-France queries reliably mentions Paris.
await host.SendAsync("direct:agent", "What is the capital city of France?");
spy.ForTool("web_search").Should().NotBeEmpty("the model must call web_search");
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
var reply = ((string)sink.ReceivedExchanges[0].In.Body!).ToLowerInvariant();
reply.Should().Contain("paris");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/RegistryDrivenPromptTests.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/tests/redb.Route.Tests.Llm/DslShowcase/RegistryDrivenPromptTests.cs
----
using redb.Route.Llm.Engine.Storage;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// The #name registry-ref is a framework-wide convention in redb.Route:
/// connection factories, processors, and now prompts use the same shape.
///
/// A leading # on ?systemPromptRef= or ?initialBodyRef= turns
/// the URI parameter into a registry lookup. Resolution order:
///
/// - (latest version of the named template)
/// - 's named-object registry (a plain string)
///
/// Plain values are still treated as literal prompts.
///
///
/// The point: any other route — running on its own schedule — can rewrite the
/// referenced key, and the next agent invocation picks up the fresh prompt
/// without a route redeploy. Decoupling source-of-truth from caller is the
/// same trick we already use for Kafka/S3 connection factories.
///
/// We use the scripted here so the assertions can
/// focus on which system prompt arrived at the provider — that is the
/// behavior under test, not the model's reply quality.
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class RegistryDrivenPromptTests
{
[Fact]
public async Task SystemPromptRef_HashName_ResolvesFromRouteContextRegistry()
{
var fake = new FakeProvider().EnqueueText("ok").EnqueueText("ok");
await using var host = LiveLlmHost.Build()
.AddFactory("scripted", new LlmConnectionFactory
{
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
// Step 1 — populate the prompt by name. Any route, processor, or
// bootstrap step in the application could do this.
host.Context.AddToRegistry("style.terse", "Reply in fewer than 5 words.");
await host.StartAsync(r =>
{
r.From("direct:chat")
.To("llm://scripted?systemPromptRef=#style.terse")
.To("mock:done");
});
await host.SendAsync("direct:chat", "Hi.");
fake.CapturedRequests[0].SystemPrompt.Should().Be("Reply in fewer than 5 words.");
// Step 2 — a different actor mutates the same key; the next call sees
// the new value with no changes to the LLM route.
host.Context.AddToRegistry("style.terse", "Reply in French only.");
await host.SendAsync("direct:chat", "Hi again.");
fake.CapturedRequests[1].SystemPrompt.Should().Be("Reply in French only.");
}
[Fact]
public async Task SystemPromptRef_HashName_PrefersPromptTemplateRegistry()
{
var fake = new FakeProvider().EnqueueText("ok");
var templates = new InMemoryPromptTemplateRegistry();
await templates.SetAsync(new PromptTemplate
{
Name = "watchdog",
Version = "v1",
Body = "You are a watchdog. Respond with PASS or FAIL only."
});
await using var host = LiveLlmHost.Build()
.AddFactory("scripted", new LlmConnectionFactory
{
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
host.Context.AddService(typeof(IPromptTemplateRegistry), templates);
// Decoy in the generic registry — must be *ignored* in favour of the
// versioned IPromptTemplateRegistry hit. This is what makes the prompt
// ref versionable and replayable in eval runs.
host.Context.AddToRegistry("watchdog", "WRONG — should not be used.");
await host.StartAsync(r =>
{
r.From("direct:chat")
.To("llm://scripted?systemPromptRef=#watchdog")
.To("mock:done");
});
await host.SendAsync("direct:chat", "ping");
fake.CapturedRequests[0].SystemPrompt.Should().Be(
"You are a watchdog. Respond with PASS or FAIL only.");
}
[Fact]
public async Task SystemPromptRef_PlainValue_StaysLiteral()
{
var fake = new FakeProvider().EnqueueText("ok");
await using var host = LiveLlmHost.Build()
.AddFactory("scripted", new LlmConnectionFactory
{
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
// Even though "literal" exists in the registry, the URI ref has no
// leading '#' — so it must arrive unchanged at the provider.
host.Context.AddToRegistry("literal", "WRONG.");
await host.StartAsync(r =>
{
r.From("direct:chat")
.To("llm://scripted?systemPromptRef=literal")
.To("mock:done");
});
await host.SendAsync("direct:chat", "ping");
fake.CapturedRequests[0].SystemPrompt.Should().Be("literal");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/SttSchemeTests.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/tests/redb.Route.Tests.Llm/DslShowcase/SttSchemeTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Llm;
using redb.Route.Llm.Providers;
using redb.Route.Llm.Transcription;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// stt://<factory> scheme — transcribes the exchange body via the named
/// connection factory. Driven with a stub
/// (no live endpoint): recorded audio in, text out.
///
public sealed class SttSchemeTests
{
/// Deterministic stub: reports back what it was handed.
private sealed class StubStt(string text = "распознанный текст") : ITranscriptionProvider
{
public TranscriptionRequest? Last { get; private set; }
public string ProviderId => "stub";
public string ModelId => "stub-speech";
public Task TranscribeAsync(TranscriptionRequest request, CancellationToken ct = default)
{
Last = request;
return Task.FromResult(new TranscriptionResult(text, Language: "ru"));
}
}
private static (RouteContext Ctx, ProducerTemplate Producer) Host(SttComponent component)
{
var sp = new ServiceCollection().BuildServiceProvider();
var ctx = new RouteContext(sp, contextId: "stt-scheme-test");
ctx.AddToRegistry("speech", new LlmConnectionFactory
{
Provider = "local",
ModelId = "large-v3",
BaseUrl = new Uri("http://127.0.0.1:8083/v1/")
});
ctx.AddComponent(component);
var producer = new ProducerTemplate(ctx);
ctx.AddService(typeof(IProducerTemplate), producer);
return (ctx, producer);
}
/// Drives one exchange through and hands back what came out.
private static async Task RunAsync(
ProducerTemplate producer, string uri, Action prepare)
{
var exchange = new Exchange(new Message(null));
prepare(exchange);
return await producer.RequestAsync(uri, exchange);
}
private static IMessage Result(IExchange exchange) => exchange.Out ?? exchange.In;
[Fact]
public async Task RecordedBytes_BecomeText()
{
var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => new StubStt() });
ctx.AddRoutes(r => r.From("direct:v1").To("stt://speech"));
await ctx.Start();
producer.Start();
var result = await producer.RequestBody("direct:v1", new byte[] { 1, 2, 3 });
result.Should().Be("распознанный текст");
await ctx.DisposeAsync();
}
[Fact]
public async Task AStreamBodyIsBufferedForTheUpload()
{
// Multipart needs a length; a chunked body is not something a speech endpoint takes.
var stub = new StubStt();
var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => stub });
ctx.AddRoutes(r => r.From("direct:v2").To("stt://speech"));
await ctx.Start();
producer.Start();
await producer.RequestBody("direct:v2", new MemoryStream([9, 8, 7]));
stub.Last!.Value.Audio.ToArray().Should().Equal(9, 8, 7);
await ctx.DisposeAsync();
}
[Fact]
public async Task TheFileNameFollowsTheContentType()
{
// The transport that delivered the recording already knows the format. Deriving the
// upload name from it is what lets a voice route work with no configuration at all —
// and getting it wrong is a decode error, not a worse transcription.
var stub = new StubStt();
var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => stub });
ctx.AddRoutes(r => r.From("direct:v3").To("stt://speech"));
await ctx.Start();
producer.Start();
await RunAsync(producer, "direct:v3", exchange =>
{
exchange.In.Body = new byte[] { 1 };
exchange.In.ContentType = "audio/ogg";
});
stub.Last!.Value.FileName.Should().Be("audio.oga");
await ctx.DisposeAsync();
}
[Fact]
public async Task HeadersOverrideTheEndpointOptions()
{
var stub = new StubStt();
var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => stub });
ctx.AddRoutes(r => r.From("direct:v4").To("stt://speech?language=en&fileName=fixed.wav"));
await ctx.Start();
producer.Start();
await RunAsync(producer, "direct:v4", exchange =>
{
exchange.In.Body = new byte[] { 1 };
exchange.In.Headers[LlmHeaders.TranscriptionLanguage] = "ru";
exchange.In.Headers[LlmHeaders.TranscriptionFileName] = "voice.oga";
});
stub.Last!.Value.Language.Should().Be("ru");
stub.Last!.Value.FileName.Should().Be("voice.oga");
await ctx.DisposeAsync();
}
[Fact]
public async Task TheAnswerIsDescribedByLength_NeverByContent()
{
const string recognised = "шесть слов, а может и меньше";
var stub = new StubStt(recognised);
var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => stub });
ctx.AddRoutes(r => r.From("direct:v5").To("stt://speech"));
await ctx.Start();
producer.Start();
var result = Result(await RunAsync(producer, "direct:v5", e => e.In.Body = new byte[] { 1 }));
result.Headers[LlmHeaders.TranscriptionChars].Should().Be(recognised.Length);
result.Headers[LlmHeaders.TranscriptionModel].Should().Be("stub-speech");
result.Headers[LlmHeaders.TranscriptionProvider].Should().Be("stub");
result.Headers[LlmHeaders.TranscriptionLanguage].Should().Be("ru");
// A header travels into logs, audits and dead letters; a transcription is the
// speaker's own words. Nothing here repeats them.
result.Headers.Values
.Select(v => v?.ToString() ?? string.Empty)
.Should().NotContain(s => s.Contains("слов"));
await ctx.DisposeAsync();
}
[Fact]
public async Task ANonAudioBodySaysWhatToPutThere()
{
var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => new StubStt() });
ctx.AddRoutes(r => r.From("direct:v6").To("stt://speech"));
await ctx.Start();
producer.Start();
var act = async () => await producer.RequestBody("direct:v6", "это текст, а не запись");
(await act.Should().ThrowAsync()).And.ToString().Should().Contain("telegram://download");
await ctx.DisposeAsync();
}
[Fact]
public void TheSchemeIsProducerOnly()
{
var component = new SttComponent();
var endpoint = component.CreateEndpoint(EndpointUriParser.Parse("stt://speech"));
var act = () => endpoint.CreateConsumer(Substitute.For());
act.Should().Throw();
}
[Fact]
public void AnEndpointWithoutAFactoryRefusesToStart()
{
var component = new SttComponent();
var act = () => component.CreateEndpoint(EndpointUriParser.Parse("stt://"));
act.Should().Throw().WithMessage("*connection factory*");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/TavilyWebSearchToolTests.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/tests/redb.Route.Tests.Llm/DslShowcase/TavilyWebSearchToolTests.cs
----
using AwesomeAssertions;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Drives against a local HTTP server that mimics the Tavily
/// search API. Verifies the request shape (POST + api_key + query) and that the tool reshapes
/// the response to {answer, results} for the model.
///
public sealed class TavilyWebSearchToolTests
{
[Fact]
public async Task TavilyWebSearchTool_PostsQueryAndShapesResponse()
{
using var server = new LocalHttpServer
{
ResponseBody = """
{
"answer": "Paris is the capital of France.",
"results": [
{ "title": "France", "url": "https://en.wikipedia.org/wiki/France", "content": "Paris is the capital city.", "score": 0.9 },
{ "title": "Paris", "url": "https://en.wikipedia.org/wiki/Paris", "content": "Capital of France.", "score": 0.8 }
]
}
"""
};
await using var host = LiveLlmHost.Build();
await host.StartAsync(new TavilyWebSearchTool(new TavilyWebSearchOptions
{
ApiKey = "test-key",
Endpoint = server.BaseUrl + "search",
MaxResults = 2,
Timeout = TimeSpan.FromSeconds(5)
}));
host.ToolRegistry.Get("web_search").Should().NotBeNull();
var ex = await host.SendAsync("direct:llm.web_search",
"""{"query":"capital of France"}""");
var body = (string)ex.Out!.Body!;
body.Should().Contain("\"answer\":\"Paris is the capital of France.\"");
body.Should().Contain("https://en.wikipedia.org/wiki/France");
body.Should().Contain("https://en.wikipedia.org/wiki/Paris");
body.Should().NotContain("score");
ex.Out.Headers["llm.web_search.results"].Should().Be(2);
server.RequestPaths.Should().ContainSingle().Which.Should().Contain("/search");
}
[Fact]
public void TavilyWebSearchTool_RequiresApiKey()
{
var act = () => new TavilyWebSearchTool(new TavilyWebSearchOptions());
act.Should().Throw();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ThinkingProbeLiveTests.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/tests/redb.Route.Tests.Llm/DslShowcase/ThinkingProbeLiveTests.cs
----
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using redb.Route.Llm.Providers;
using redb.Route.Tests.Llm.TestHelpers;
using Xunit.Abstractions;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Phase 16.0a — the live half of the provider matrix: what the wire actually carries for the model's
/// thinking block, and what happens when that block is missing from a tool turn.
///
/// The probes speak raw HTTP instead of going through on purpose:
/// until 16.1 the connector neither returns a thinking block nor can be asked to send one back, so a
/// connector test could not report the defect — it would only report the connector. The provider is the
/// evidence here, and the probes are the smallest shape that asks it the questions 16.0 exists for:
/// what comes back, what must be sent back, what happens when the block is dropped, and whether a
/// conversation whose tool turns never carried one can still be continued.
///
///
/// Nothing here prints a secret or the thinking text. The artifact records field names, lengths, the
/// first 16 hex digits of the block's SHA-256 (two runs can be compared without reading thoughts) and
/// the provider's error text. Findings land in 16-0a-probe.json next to the test binary.
///
///
/// A probe whose history already carries the tool result expects an answer; only the opening turns
/// expect a call. The verdicts are read that way, and the artifact records both the shapes sent and
/// what came back, so a reader can disagree with the reading.
///
///
/// tool_choice is deliberately absent from the tool probes: the first live run of this wave
/// (2026-09-14) showed thinking mode answering 400 invalid_request_error: Thinking mode does not
/// support this tool_choice for "required", which would have masked every other finding. The
/// system prompt asks for the tool instead, and one probe keeps the pinned form on purpose so the
/// constraint stays proven rather than remembered.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class ThinkingProbeLiveTests
{
private const string EnvVar = "REDB_LLM_DEEPSEEK";
private const string Provider = "deepseek";
private const string ToolName = "order_lookup";
private const int MaxTokens = 512;
///
/// Aliases DeepSeek documents but no longer lists. Probed on their own, because "documented" and
/// "still routed" stopped being the same thing: on 2026-09-14 GET /models offers
/// deepseek-flash and deepseek-v4-pro and nothing else.
///
private static readonly string[] LegacyAliases = ["deepseek-reasoner", "deepseek-chat"];
private readonly ITestOutputHelper _output;
/// Creates the probe with xUnit's output sink.
public ThinkingProbeLiveTests(ITestOutputHelper output) => _output = output;
[EnvFact(EnvVar)]
public async Task DeepSeek_Probes_RecordWhatTheThinkingPathDoes()
{
var key = Environment.GetEnvironmentVariable(EnvVar)!;
var baseUrl = OpenAiProvider.ResolveDefaultBaseUrl(Provider);
var report = new ProbeReport
{
Provider = Provider,
Endpoint = new Uri(baseUrl, "chat/completions").ToString(),
StartedUtc = DateTimeOffset.UtcNow
};
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(120) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
try
{
var available = await ListModelsAsync(http, baseUrl, report);
// Whatever the endpoint lists is what gets probed: "ask /models first" is step zero of 16.0,
// and the reason this wave discovered that the models its plan named no longer exist.
foreach (var model in available.Where(IsChatModel))
{
var withBlock = await ProbeWithBlockAsync(http, baseUrl, model, report);
await ProbeWithBlockReplayAsync(http, baseUrl, model, withBlock, report);
await ProbeWithoutBlockAsync(http, baseUrl, model, withBlock, report, withTools: true);
await ProbeWithoutBlockWithContentAsync(http, baseUrl, model, withBlock, report);
await ProbeWithoutBlockAsync(http, baseUrl, model, withBlock, report, withTools: false);
await ProbeOldHistoryAsync(http, baseUrl, model, report);
await ProbeToolChoiceAsync(http, baseUrl, model, report);
}
// Aliases the endpoint no longer lists get one question: does the name still route at all?
foreach (var alias in LegacyAliases.Where(a => !available.Any(id => id.Equals(a, StringComparison.OrdinalIgnoreCase))))
await SendAsync(http, baseUrl, ProbeId.AliasWithBlock,
ChatBody(alias, new JsonArray(SystemPrompt(), UserQuestion()), withTools: true),
expectToolCall: true, report);
}
finally
{
report.FinishedUtc = DateTimeOffset.UtcNow;
WriteArtifact(report);
}
_output.WriteLine($"16.0a artifact: {ArtifactPath}");
report.ModelListStatus.Should().Be(200, "GET /models is the cheapest proof that the key is live");
report.ModelsAvailable.Should().NotBeEmpty("the endpoint must list at least one model to probe");
report.Probes.Should().NotBeEmpty();
report.Probes.Where(p => p.Verdict != ProbeVerdict.NotApplicable)
.Should().OnlyContain(p => p.Status > 0 && p.Status < 500, "a 5xx is infrastructure, not a provider verdict");
report.Probes.Should().OnlyContain(p => p.Verdict != ProbeVerdict.Unknown,
"every probe must end in a recorded verdict — that record is the deliverable of 16.0a");
report.Probes.Count(p => p.Probe == ProbeId.WithBlock && p.Status == 200).Should().BePositive(
"at least one candidate model must answer a tool turn, or nothing was learned");
File.Exists(ArtifactPath).Should().BeTrue("the artifact is what the matrix is filled from");
}
/// Asks the endpoint which models exist, so the probes run on names that are real.
private static async Task> ListModelsAsync(HttpClient http, Uri baseUrl, ProbeReport report)
{
var ids = new List();
using var response = await http.GetAsync(new Uri(baseUrl, "models"));
var body = await response.Content.ReadAsStringAsync();
report.ModelListStatus = (int)response.StatusCode;
if (response.IsSuccessStatusCode && TryParse(body) is JsonObject root && root["data"] is JsonArray data)
foreach (var entry in data)
if (entry?["id"]?.GetValue() is { Length: > 0 } id && !ids.Contains(id, StringComparer.OrdinalIgnoreCase))
ids.Add(id);
report.ModelsAvailable = ids.ToArray();
return ids;
}
/// Embedding and other non-chat entries are listed too; probing them would only add noise.
private static bool IsChatModel(string id) => !id.Contains("embed", StringComparison.OrdinalIgnoreCase);
/// First question: a tool turn with nothing replayed — what does the answer carry?
private static async Task ProbeWithBlockAsync(
HttpClient http, Uri baseUrl, string model, ProbeReport report)
{
var body = ChatBody(model, new JsonArray(SystemPrompt(), UserQuestion()), withTools: true);
return await SendAsync(http, baseUrl, ProbeId.WithBlock, body, expectToolCall: true, report);
}
///
/// Second question: replay the block we just received — the shape 16.2 must be able to reproduce.
/// Skipped, with a reason, when the model returned nothing to replay.
///
private static async Task ProbeWithBlockReplayAsync(
HttpClient http, Uri baseUrl, string model, ProbeOutcome? withBlock, ProbeReport report)
{
if (withBlock?.ThinkingText is not { Length: > 0 } thinking || withBlock.ToolCalls.Count == 0)
{
report.Probes.Add(new ProbeOutcome
{
Probe = ProbeId.WithBlockReplay,
Model = model,
Verdict = ProbeVerdict.NotApplicable,
VerdictDetail = string.IsNullOrEmpty(withBlock?.ThinkingText)
? "the model returned no thinking block, so there is nothing to replay"
: "the model returned no tool call to attach the block to"
});
return;
}
var call = withBlock.ToolCalls[0];
var messages = new JsonArray(
SystemPrompt(), UserQuestion(),
AssistantTurn(call, thinking, withBlock.ContentText),
ToolResult(call, "shipped"));
await SendAsync(http, baseUrl, ProbeId.WithBlockReplay,
ChatBody(model, messages, withTools: true), expectToolCall: false, report);
}
///
/// Third question, the K4 test: the same tool turn with the block dropped — exactly what the connector
/// sends today. Three shapes, because the answer turned out to depend on the turn rather than on
/// tools: as the model returned it minus the block, with a non-empty content, and with no
/// tool surface declared at all (the control for the documented "the 400 needs tools" rule).
///
private static async Task ProbeWithoutBlockAsync(
HttpClient http, Uri baseUrl, string model, ProbeOutcome? withBlock, ProbeReport report, bool withTools)
{
var call = withBlock?.ToolCalls.FirstOrDefault() ?? SyntheticCall();
var messages = new JsonArray(
SystemPrompt(), UserQuestion(),
AssistantTurn(call, thinking: null, withBlock?.ContentText),
ToolResult(call, "shipped"));
await SendAsync(http, baseUrl,
withTools ? ProbeId.WithoutBlockTools : ProbeId.WithoutBlockNoTools,
ChatBody(model, messages, withTools), expectToolCall: false, report);
}
///
/// The same dropped-block turn, but with the visible content the model produced kept in place:
/// if the provider validates the block only when the assistant turn has text, this is where it says so.
///
private static async Task ProbeWithoutBlockWithContentAsync(
HttpClient http, Uri baseUrl, string model, ProbeOutcome? withBlock, ProbeReport report)
{
var call = withBlock?.ToolCalls.FirstOrDefault() ?? SyntheticCall();
var messages = new JsonArray(
SystemPrompt(), UserQuestion(),
AssistantTurn(call, thinking: null, withBlock?.ContentText ?? "Let me look that up."),
ToolResult(call, "shipped"));
await SendAsync(http, baseUrl, ProbeId.WithoutBlockContent,
ChatBody(model, messages, withTools: true), expectToolCall: false, report);
}
///
/// Fourth question: a conversation created before the phase — its tool turns never carried a block.
/// Continuing it is the class of the 2026-09-07 incident.
///
private static async Task ProbeOldHistoryAsync(HttpClient http, Uri baseUrl, string model, ProbeReport report)
{
var call = SyntheticCall();
var messages = new JsonArray(
SystemPrompt(), UserQuestion(),
AssistantTurn(call, thinking: null),
ToolResult(call, "shipped"),
AssistantText("shipped"),
new JsonObject { ["role"] = "user", ["content"] = "And what about order 43?" });
await SendAsync(http, baseUrl, ProbeId.OldHistory,
ChatBody(model, messages, withTools: true), expectToolCall: true, report);
}
///
/// Fifth question, learned the hard way on the first run: thinking mode refuses a pinned tool_choice.
/// Kept as a probe so the constraint stays proven — the connector must never send
/// tool_choice: "required" to a thinking model.
///
private static async Task ProbeToolChoiceAsync(HttpClient http, Uri baseUrl, string model, ProbeReport report)
{
var body = ChatBody(model, new JsonArray(SystemPrompt(), UserQuestion()), withTools: true);
body["tool_choice"] = "required";
await SendAsync(http, baseUrl, ProbeId.ToolChoiceRequired, body, expectToolCall: true, report);
}
/// Sends one probe and records everything the matrix needs — and nothing it must not carry.
private static async Task SendAsync(
HttpClient http, Uri baseUrl, string probeId, JsonObject body, bool expectToolCall, ProbeReport report)
{
var outcome = new ProbeOutcome
{
Probe = probeId,
Model = body["model"]!.GetValue(),
Request = Describe(body)
};
using var content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");
using var response = await http.PostAsync(new Uri(baseUrl, "chat/completions"), content);
var text = await response.Content.ReadAsStringAsync();
outcome.Status = (int)response.StatusCode;
if (response.IsSuccessStatusCode) Capture(outcome, TryParse(text), expectToolCall);
else Reject(outcome, text);
report.Probes.Add(outcome);
return outcome;
}
/// Builds the request body in the shape the connector sends, minus everything it does not send.
private static JsonObject ChatBody(string model, JsonArray messages, bool withTools)
{
var body = new JsonObject
{
["model"] = model,
["messages"] = messages,
["max_tokens"] = MaxTokens,
["stream"] = false
};
if (!withTools) return body;
// No tool_choice: thinking mode refuses the pinned form (see the class remarks), and the prompt
// already asks for the tool by name.
body["tools"] = ToolDefinitions();
return body;
}
/// Roles of the request plus whether the tool surface was declared — the "what we sent" column.
private static string Describe(JsonObject body)
{
var messages = (JsonArray)body["messages"]!;
var roles = messages.Select(m =>
{
var role = m?["role"]?.GetValue() ?? "?";
if (m?["tool_calls"] is not null)
role += m?["reasoning_content"] is not null ? "(tool_calls+thinking)" : "(tool_calls)";
return role;
});
return $"{string.Join(",", roles)} | tools={(body["tools"] is null ? "no" : "yes")}";
}
private static void Capture(ProbeOutcome outcome, JsonNode? json, bool expectToolCall)
{
if (json?["choices"] is not JsonArray { Count: > 0 } choices || choices[0]?["message"]?.AsObject() is not { } message)
{
outcome.Verdict = ProbeVerdict.Unknown;
outcome.VerdictDetail = "200 without a message to read";
return;
}
var first = choices[0]!.AsObject();
outcome.ResponseModel = json["model"]?.GetValue();
outcome.SystemFingerprint = json["system_fingerprint"]?.GetValue();
outcome.FinishReason = first["finish_reason"]?.GetValue();
outcome.MessageKeys = message.Select(p => p.Key).OrderBy(k => k, StringComparer.Ordinal).ToArray();
var thinking = message["reasoning_content"]?.GetValue();
if (thinking is not null) outcome.ThinkingField = "reasoning_content";
else if (message["reasoning"] is JsonValue other) { outcome.ThinkingField = "reasoning"; thinking = other.GetValue(); }
outcome.ThinkingPresent = !string.IsNullOrEmpty(thinking);
outcome.ThinkingLength = thinking?.Length ?? 0;
outcome.ThinkingSha256 = thinking is { Length: > 0 } ? Sha256(thinking) : null;
outcome.ThinkingText = thinking;
outcome.ContentLength = message["content"]?.GetValue()?.Length ?? 0;
outcome.ContentText = message["content"]?.GetValue();
if (message["tool_calls"] is JsonArray calls)
{
outcome.ToolCallCount = calls.Count;
foreach (var call in calls)
{
if (call?["function"] is not JsonObject fn) continue;
outcome.ToolCalls.Add(new ToolCallShape
{
Id = call["id"]?.GetValue() ?? string.Empty,
Name = fn["name"]?.GetValue() ?? string.Empty,
Arguments = fn["arguments"]?.GetValue() ?? string.Empty
});
}
}
if (json["usage"] is JsonObject usage)
{
outcome.PromptTokens = usage["prompt_tokens"]?.GetValue();
outcome.CompletionTokens = usage["completion_tokens"]?.GetValue();
outcome.ReasoningTokens = usage["completion_tokens_details"]?["reasoning_tokens"]?.GetValue();
}
var degraded = expectToolCall && outcome.ToolCallCount == 0;
outcome.Verdict = degraded ? ProbeVerdict.AcceptedDegraded : ProbeVerdict.Accepted;
outcome.VerdictDetail = degraded
? "answered without calling the tool the prompt asked for"
: "answered";
}
private static void Reject(ProbeOutcome outcome, string body)
{
var error = TryParse(body)?["error"] as JsonObject;
outcome.ErrorType = Truncate(error?["type"]?.GetValue(), 120);
outcome.ErrorMessage = Truncate(error?["message"]?.GetValue() ?? body, 400);
outcome.Verdict = ProbeVerdict.Rejected;
outcome.VerdictDetail = $"HTTP {outcome.Status}: {outcome.ErrorType ?? outcome.ErrorMessage}";
}
private static JsonObject SystemPrompt() => new()
{
["role"] = "system",
["content"] = $"Use the {ToolName} tool to look up the order, then reply with only the status word."
};
private static JsonObject UserQuestion() => new()
{
["role"] = "user",
["content"] = "What is the status of order 42?"
};
/// An assistant tool turn — with the thinking block only when the probe means to send one.
private static JsonObject AssistantTurn(ToolCallShape call, string? thinking, string? content = null)
{
var message = new JsonObject
{
["role"] = "assistant",
["content"] = content,
["tool_calls"] = new JsonArray(new JsonObject
{
["id"] = call.Id,
["type"] = "function",
["function"] = new JsonObject { ["name"] = call.Name, ["arguments"] = call.Arguments }
})
};
if (thinking is { Length: > 0 })
message["reasoning_content"] = thinking;
return message;
}
private static JsonObject ToolResult(ToolCallShape call, string status) => new()
{
["role"] = "tool",
["tool_call_id"] = call.Id,
["content"] = $"{{\"status\":\"{status}\"}}"
};
private static JsonObject AssistantText(string text) => new()
{
["role"] = "assistant",
["content"] = text
};
/// A tool call the answer did not supply, so every probe still runs when the first one fails.
private static ToolCallShape SyntheticCall() => new()
{
Id = "call_probe_1",
Name = ToolName,
Arguments = "{\"orderId\":\"42\"}"
};
private static JsonArray ToolDefinitions() => new(
new JsonObject
{
["type"] = "function",
["function"] = new JsonObject
{
["name"] = ToolName,
["description"] = "Look up an order by id and return its status.",
["parameters"] = JsonNode.Parse(
"""{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}""")
}
});
private static JsonNode? TryParse(string text)
{
try { return JsonNode.Parse(text); }
catch (JsonException) { return null; }
}
/// First 16 hex digits of SHA-256 — enough to compare two runs without carrying the thought.
private static string Sha256(string text) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant()[..16];
private static string? Truncate(string? text, int max) =>
text is null ? null : text.Length <= max ? text : text[..max] + "...";
/// Where the findings land: next to the test binary, so bin keeps them out of the repo.
private static string ArtifactPath => Path.Combine(AppContext.BaseDirectory, "16-0a-probe.json");
private static void WriteArtifact(ProbeReport report)
{
var json = JsonSerializer.Serialize(report, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
File.WriteAllText(ArtifactPath, json);
}
}
/// Ids of the probes; the matrix cites these, so they are stable strings, not enum numbers.
internal static class ProbeId
{
/// A tool turn with nothing replayed.
public const string WithBlock = "with-block";
/// The block we received, sent back on the next tool turn.
public const string WithBlockReplay = "with-block-replay";
/// The K4 probe: tool turn without its block, tool surface declared.
public const string WithoutBlockTools = "without-block-tools";
/// Control for K4: same turn, no tool surface declared.
public const string WithoutBlockNoTools = "without-block-no-tools";
/// Same turn with its visible content kept, block still dropped.
public const string WithoutBlockContent = "without-block-content";
/// A conversation created before the phase, continued.
public const string OldHistory = "old-history";
/// An alias the endpoint no longer lists, asked the first question only.
public const string AliasWithBlock = "alias-with-block";
/// A tool turn with tool_choice: "required" — the form thinking mode refuses.
public const string ToolChoiceRequired = "tool-choice-required";
}
/// Verdict vocabulary shared by the artifact and the matrix.
internal static class ProbeVerdict
{
/// Nothing was learned — the probe must not end here.
public const string Unknown = "unknown";
/// 2xx and the expected shape came back.
public const string Accepted = "accepted";
/// 2xx but thinner than the request pinned — the "degraded answer" outcome.
public const string AcceptedDegraded = "accepted-degraded";
/// Provider refused the request; the error text is in the outcome.
public const string Rejected = "rejected";
/// The probe could not be asked (nothing to replay) — a recorded answer, not a gap.
public const string NotApplicable = "not-applicable";
}
/// The tool call of an assistant turn, in the shape it travels on the wire.
internal sealed class ToolCallShape
{
/// Provider-assigned call id.
public string Id { get; set; } = string.Empty;
/// Function name.
public string Name { get; set; } = string.Empty;
/// Function arguments as a JSON string.
public string Arguments { get; set; } = string.Empty;
}
/// One probe: what was sent, what came back, what it means.
internal sealed class ProbeOutcome
{
/// Probe id — see .
public string Probe { get; set; } = string.Empty;
/// Model the probe ran on.
public string Model { get; set; } = string.Empty;
/// Model id the provider says it served — how an alias resolves.
public string? ResponseModel { get; set; }
/// Backend fingerprint, when the provider exposes one.
public string? SystemFingerprint { get; set; }
/// HTTP status of the response.
public int Status { get; set; }
/// Verdict — see .
public string Verdict { get; set; } = ProbeVerdict.Unknown;
/// One line explaining the verdict.
public string? VerdictDetail { get; set; }
/// Roles and tool surface of the request we sent.
public string Request { get; set; } = string.Empty;
/// Provider's finish_reason.
public string? FinishReason { get; set; }
/// Keys present on the assistant message — how the provider names its fields.
public string[] MessageKeys { get; set; } = [];
/// Name of the field carrying the thinking block, when one came.
public string? ThinkingField { get; set; }
/// Whether a non-empty thinking block came back.
public bool ThinkingPresent { get; set; }
/// Length of the thinking block in characters.
public int ThinkingLength { get; set; }
/// Short hash of the thinking block, for run-to-run comparison.
public string? ThinkingSha256 { get; set; }
/// Length of the visible answer.
public int ContentLength { get; set; }
/// Number of tool calls in the answer.
public int ToolCallCount { get; set; }
/// The tool calls themselves, reused when a later probe replays this turn.
public List ToolCalls { get; set; } = [];
/// Prompt tokens reported by the provider.
public int? PromptTokens { get; set; }
/// Completion tokens reported by the provider.
public int? CompletionTokens { get; set; }
/// Reasoning tokens, when the provider splits them out.
public int? ReasoningTokens { get; set; }
/// Provider error type, when the request was refused.
public string? ErrorType { get; set; }
/// Provider error text, truncated.
public string? ErrorMessage { get; set; }
///
/// The block itself, kept in memory so the replay probe can send it back. Never written to the
/// artifact: thoughts are the model's, and this file is meant to be committed as evidence.
///
[JsonIgnore]
public string? ThinkingText { get; set; }
/// The visible answer of the turn, kept in memory so the dropped-block probe can keep it.
[JsonIgnore]
public string? ContentText { get; set; }
}
/// The whole 16.0a run: which models answered, and every probe's outcome.
internal sealed class ProbeReport
{
/// Provider alias probed.
public string Provider { get; set; } = string.Empty;
/// Chat Completions endpoint the probes used.
public string Endpoint { get; set; } = string.Empty;
/// When the run started.
public DateTimeOffset StartedUtc { get; set; }
/// When the run finished.
public DateTimeOffset FinishedUtc { get; set; }
/// HTTP status of GET /models.
public int ModelListStatus { get; set; }
/// Model ids the endpoint offers.
public string[] ModelsAvailable { get; set; } = [];
/// Every probe the run performed, in order.
public List Probes { get; set; } = [];
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ToolRouteTests.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/tests/redb.Route.Tests.Llm/DslShowcase/ToolRouteTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// The point of redb.Route.Llm is that a tool is just a route. This
/// suite proves it end-to-end against a live provider: an
/// is mounted with .AsLlmTool, then a chat route asks the model to call
/// it and return the payload. The agent loop runs entirely inside the route
/// engine — no manual JSON shuffling.
///
/// We only run this against Groq because Groq's tool-use on Llama 3.3 70B is
/// the most reliable free tier we have. Other providers either rate-limit
/// aggressively (Gemini), tool-use is gated behind a paid plan (OpenAI),
/// or the free model refuses tool calls some fraction of the time
/// (Mistral small). Adding more providers here is just an extra
/// — the DSL doesn't change.
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class ToolRouteTests
{
[EnvFact("REDB_LLM_GROQ_KEY")]
public async Task Groq_ToolLoop_RoutedTool_DeliversPayload()
{
await using var host = LiveLlmHost.Build()
.AddFactory("groq", new LlmConnectionFactory
{
Provider = "groq",
ModelId = "llama-3.3-70b-versatile",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"),
Temperature = 0.0,
MaxTokens = 256
});
// Tool: takes {"q": string}, returns {"answer": ""}.
var echo = new EchoToolRoute(
toolName: "lookup",
description: "Look up a fact for the given query and return JSON {\"answer\": ...}.",
inputSchema: """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""",
replyJson: """{"answer":"the magic word is rosebud"}""");
await host.StartAsync(echo, 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 word verbatim and nothing else.")
.To(LlmDsl.Factory("groq").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done");
});
await host.SendAsync("direct:agent", "What is the magic word?");
// The agent must have called the tool at least once.
echo.CapturedInputs.Should().NotBeEmpty();
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
var reply = ((string)sink.ReceivedExchanges[0].In.Body!).ToLowerInvariant();
reply.Should().Contain("rosebud");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/UtilityToolTests.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/tests/redb.Route.Tests.Llm/DslShowcase/UtilityToolTests.cs
----
using AwesomeAssertions;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm.DslShowcase;
///
/// Exercises the framework-backed utility tools shipped in redb.Route.Llm.Tools.
/// Each tool is a thin wrapper over a redb.Route primitive —
/// over JsonPathExpression, over XPathExpression,
/// over ExpressionResolver,
/// over System.Text.RegularExpressions.Regex with a ReDoS guard.
///
/// The tools mount direct: routes via .AsLlmTool(...), so we can drive them
/// straight through the route pipeline without involving an LLM provider.
///
///
public sealed class UtilityToolTests
{
[Fact]
public async Task JsonPathTool_RegistersDescriptor_AndExtractsValue()
{
await using var host = LiveLlmHost.Build();
await host.StartAsync(new JsonPathTool(new JsonPathOptions()));
var descriptor = host.ToolRegistry.Get("json_path");
descriptor.Should().NotBeNull();
descriptor!.Capability.Safety.SideEffect.Should().Be(ToolSideEffect.ReadOnly);
descriptor.Capability.Safety.Cost.Should().Be(ToolCostClass.Cheap);
var input = """{"json":"{\"items\":[{\"name\":\"alpha\"},{\"name\":\"beta\"}]}","path":"$.items[1].name"}""";
var ex = await host.SendAsync("direct:llm.json_path", input);
((string)ex.Out!.Body!).Should().Be("\"beta\"");
ex.Out.Headers["llm.json_path.matched"].Should().Be(true);
var miss = """{"json":"{\"x\":1}","path":"$.y"}""";
var exMiss = await host.SendAsync("direct:llm.json_path", miss);
((string)exMiss.Out!.Body!).Should().Be("null");
exMiss.Out.Headers["llm.json_path.matched"].Should().Be(false);
}
[Fact]
public async Task JsonPathTool_SupportsRecursiveDescentAndFilters()
{
await using var host = LiveLlmHost.Build();
await host.StartAsync(new JsonPathTool());
// Recursive descent — pick all 'name' properties anywhere in the tree.
var rec = """{"json":"{\"a\":{\"name\":\"x\"},\"b\":[{\"name\":\"y\"}]}","path":"$..name"}""";
var exRec = await host.SendAsync("direct:llm.json_path", rec);
((string)exRec.Out!.Body!).Should().Be("[\"x\",\"y\"]");
// Filter — items priced over 10.
var filt = """{"json":"{\"items\":[{\"p\":5},{\"p\":12},{\"p\":20}]}","path":"$.items[?(@.p > 10)].p"}""";
var exFilt = await host.SendAsync("direct:llm.json_path", filt);
((string)exFilt.Out!.Body!).Should().Be("[12,20]");
}
[Fact]
public async Task XPathTool_ExtractsValueFromXmlDocument()
{
await using var host = LiveLlmHost.Build();
await host.StartAsync(new XPathTool());
host.ToolRegistry.Get("xpath").Should().NotBeNull();
var input = """{"xml":"DuneFoundation","xpath":"string(//book[1]/title)"}""";
var ex = await host.SendAsync("direct:llm.xpath", input);
((string)ex.Out!.Body!).Should().Be("Dune");
ex.Out.Headers["llm.xpath.matched"].Should().Be(true);
var miss = """{"xml":"","xpath":"string(//missing)"}""";
var exMiss = await host.SendAsync("direct:llm.xpath", miss);
// XPath string() on no-match returns empty string, not null — but our tool
// surfaces it as an empty string body (matched=true, value="").
((string)exMiss.Out!.Body!).Should().Be("");
}
[Fact]
public async Task RegexExtractTool_ReturnsFirstAndAllMatches()
{
await using var host = LiveLlmHost.Build();
await host.StartAsync(new RegexExtractTool(new RegexExtractOptions()));
host.ToolRegistry.Get("regex_extract").Should().NotBeNull();
var first = """{"text":"order 42 and 7","pattern":"\\d+"}""";
var ex1 = await host.SendAsync("direct:llm.regex_extract", first);
((string)ex1.Out!.Body!).Should().Be("\"42\"");
var all = """{"text":"order 42 and 7","pattern":"\\d+","all":true}""";
var exAll = await host.SendAsync("direct:llm.regex_extract", all);
((string)exAll.Out!.Body!).Should().Be("[\"42\",\"7\"]");
var named = """{"text":"name=alice","pattern":"name=(?\\w+)","group":"who"}""";
var exNamed = await host.SendAsync("direct:llm.regex_extract", named);
((string)exNamed.Out!.Body!).Should().Be("\"alice\"");
var miss = """{"text":"abc","pattern":"\\d+"}""";
var exMiss = await host.SendAsync("direct:llm.regex_extract", miss);
((string)exMiss.Out!.Body!).Should().Be("null");
}
[Fact]
public async Task MathEvalTool_DelegatesToExpressionResolver()
{
await using var host = LiveLlmHost.Build();
await host.StartAsync(new MathEvalTool(new MathEvalOptions()));
host.ToolRegistry.Get("math_eval").Should().NotBeNull();
async Task EvalAsync(string expr)
{
var body = $"{{\"expression\":\"{expr}\"}}";
var ex = await host.SendAsync("direct:llm.math_eval", body);
return (string)ex.Out!.Body!;
}
(await EvalAsync("2 * (3 + 4)")).Should().Be("14");
(await EvalAsync("100 / 4")).Should().Be("25");
(await EvalAsync("42")).Should().Be("42");
(await EvalAsync("'hello'")).Should().Be("\"hello\"");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/EmbeddingProviderTests.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/tests/redb.Route.Tests.Llm/EmbeddingProviderTests.cs
----
using System.Net;
using System.Text;
using System.Text.Json;
using AwesomeAssertions;
using redb.Route.Llm;
using redb.Route.Llm.Providers;
namespace redb.Route.Tests.Llm;
///
/// request/response mapping, driven through a
/// stub — no live key, deterministic.
///
public sealed class EmbeddingProviderTests
{
private sealed class StubHandler(string responseJson, HttpStatusCode status = HttpStatusCode.OK) : HttpMessageHandler
{
public HttpRequestMessage? LastRequest { get; private set; }
public string? LastBody { get; private set; }
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct)
{
LastRequest = request;
LastBody = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct);
return new HttpResponseMessage(status)
{
Content = new StringContent(responseJson, Encoding.UTF8, "application/json")
};
}
}
private static LlmConnectionFactory Factory(string provider = "openai", string model = "text-embedding-3-small") =>
new() { Provider = provider, ModelId = model, ApiKey = "sk-test" };
[Fact]
public async Task EmbedAsync_ParsesVectors_HonoursIndexOrder_AndShapesRequest()
{
// data arrives out of order (index 1 before index 0) — must be reordered to match inputs.
var handler = new StubHandler(
"""{"data":[{"index":1,"embedding":[0.3,0.4]},{"index":0,"embedding":[0.1,0.2]}]}""");
var provider = new OpenAiEmbeddingProvider(Factory(), new HttpClient(handler));
var vectors = await provider.EmbedAsync(new[] { "alpha", "beta" });
vectors.Should().HaveCount(2);
vectors[0].Should().Equal(0.1f, 0.2f); // index 0 → first input
vectors[1].Should().Equal(0.3f, 0.4f); // index 1 → second input
handler.LastRequest!.RequestUri!.ToString().Should().Be("https://api.openai.com/v1/embeddings");
handler.LastRequest.Headers.Authorization!.ToString().Should().Be("Bearer sk-test");
var body = JsonDocument.Parse(handler.LastBody!).RootElement;
body.GetProperty("model").GetString().Should().Be("text-embedding-3-small");
body.GetProperty("input").GetArrayLength().Should().Be(2);
}
[Fact]
public async Task EmbedOneAsync_ReturnsFirstVector()
{
var handler = new StubHandler("""{"data":[{"index":0,"embedding":[1,2,3]}]}""");
IEmbeddingProvider provider = new OpenAiEmbeddingProvider(Factory(), new HttpClient(handler));
(await provider.EmbedOneAsync("hi")).Should().Equal(1f, 2f, 3f);
}
[Fact]
public async Task EmbedAsync_EmptyInputs_ReturnsEmpty_WithoutHttpCall()
{
var handler = new StubHandler("{}");
var provider = new OpenAiEmbeddingProvider(Factory(), new HttpClient(handler));
(await provider.EmbedAsync(Array.Empty())).Should().BeEmpty();
handler.LastRequest.Should().BeNull();
}
[Fact]
public void Endpoint_ResolvesPerProvider()
{
new OpenAiEmbeddingProvider(Factory("mistral"), new HttpClient(new StubHandler("{}")))
.ProviderId.Should().Be("mistral");
// base-url resolution is shared with OpenAiProvider; a smoke check that the
// provider id is lower-cased and carried through.
}
[Fact]
public async Task EmbedAsync_HttpError_Throws()
{
var handler = new StubHandler("""{"error":"bad model"}""", HttpStatusCode.BadRequest);
var provider = new OpenAiEmbeddingProvider(Factory(), new HttpClient(handler));
var act = async () => await provider.EmbedAsync(new[] { "x" });
await act.Should().ThrowAsync();
}
/// Stub that also sets Retry-After, which only the 429 path reads.
private sealed class RetryAfterHandler(HttpStatusCode status, int? retryAfterSeconds) : HttpMessageHandler
{
protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct)
{
var response = new HttpResponseMessage(status)
{
Content = new StringContent("""{"error":"slow down"}""", Encoding.UTF8, "application/json")
};
if (retryAfterSeconds is { } seconds)
response.Headers.Add("Retry-After", seconds.ToString(System.Globalization.CultureInfo.InvariantCulture));
return Task.FromResult(response);
}
}
[Fact]
public async Task EmbedAsync_RateLimited_ThrowsTypedRateLimit_WithRetryAfter()
{
// Retrieval degrades to keyword on ANY embedder failure, so an expired key and a busy
// server used to look identical to the caller. 429 has to be its own kind, with the
// provider's own wait time, or "retry" is guesswork.
var provider = new OpenAiEmbeddingProvider(
Factory(), new HttpClient(new RetryAfterHandler(HttpStatusCode.TooManyRequests, 7)));
var error = await Assert.ThrowsAsync(
() => provider.EmbedAsync(new[] { "x" }));
error.ProviderId.Should().Be("openai");
error.RetryAfter.Should().Be(TimeSpan.FromSeconds(7));
}
[Fact]
public async Task EmbedAsync_ServerError_ThrowsTypedTransient_ButClientErrorDoesNot()
{
var transient = new OpenAiEmbeddingProvider(
Factory(), new HttpClient(new RetryAfterHandler(HttpStatusCode.ServiceUnavailable, null)));
var error = await Assert.ThrowsAsync(
() => transient.EmbedAsync(new[] { "x" }));
error.StatusCode.Should().Be(503);
// 401 stays a plain HttpRequestException on purpose: a wrong key is not worth retrying,
// and lumping it in with "transient" would spin forever on a dead credential.
var unauthorized = new OpenAiEmbeddingProvider(
Factory(), new HttpClient(new RetryAfterHandler(HttpStatusCode.Unauthorized, null)));
var act = async () => await unauthorized.EmbedAsync(new[] { "x" });
(await act.Should().ThrowAsync())
.And.Should().NotBeOfType();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/GlobalUsings.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/tests/redb.Route.Tests.Llm/GlobalUsings.cs
----
global using redb.Route.Abstractions;
global using redb.Route.Core;
global using redb.Route.Extensions;
global using redb.Route.Llm;
global using redb.Route.Llm.Abstractions.Tools;
global using redb.Route.Llm.Engine;
global using redb.Route.Llm.Extensions;
global using redb.Route.Llm.Providers;
global using redb.Route.Llm.Tools;
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/ApprovalDefaultsTests.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/tests/redb.Route.Tests.Llm/Governance/ApprovalDefaultsTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Llm.Engine.Governance;
namespace redb.Route.Tests.Llm.Governance;
///
/// Lock, not red. Records the shipped default that the governance docs talk about: a container
/// built by AddRedbRouteLlm() resolves , i.e. the approval flag
/// alone does not stop a tool call.
///
/// This stays true after wave 6 by decision: discovered MCP tools now declare
/// RequiresApproval = true, which with this gate produces an audit row
/// (ApprovalId = "auto"), not a blocked call. A host that wants approval to be a control point
/// registers its own gate — and AddRedbLlmStorage() leaves that registration alone.
///
///
[Trait("Category", "Governance")]
public sealed class ApprovalDefaultsTests
{
[Fact]
public void AddRedbRouteLlm_ResolvesAutoApproveGateByDefault()
{
var services = new ServiceCollection();
services.AddRedbRouteLlm();
using var provider = services.BuildServiceProvider();
var gate = provider.GetRequiredService();
gate.Should().BeOfType(
"the shipped default gate auto-approves; a real control point requires replacing it");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/BudgetTests.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/tests/redb.Route.Tests.Llm/Governance/BudgetTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Llm.Engine.Governance;
using redb.Route.Llm.Extensions;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.Governance;
///
/// Budgets (wave 4). Before this wave AgentRequest.Budget was filled nowhere, so every route
/// ran unbounded, and the cost dimension was a structural zero. These tests pin the three things that
/// make the feature real: the ceiling reaches the engine, a run that crosses it stops with a reason,
/// and a cost ceiling nobody can price fails fast instead of being silently ignored.
///
[Trait("Category", "Governance")]
public sealed class BudgetTests
{
private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
private const string Input = """{"q":"x"}""";
private const string Reply = """{"answer":"42"}""";
[Fact]
public async Task RouteWithTokenBudget_StopsWithBudgetReason()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1", tokensIn: 10, tokensOut: 1)
.EnqueueText("first answer", tokensIn: 500, tokensOut: 1)
.EnqueueText("never asked for", tokensIn: 500, tokensOut: 1);
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply);
var budgetSpy = new SpyBudgetEnforcer();
await using var host = LiveLlmHost.Build(budget: budgetSpy)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).Budget(inputTokens: 100).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
tool.CapturedInputs.Should().HaveCount(1, "the first iteration stayed inside the ceiling");
provider.CallCount.Should().Be(2, "the run stopped after the iteration that crossed the ceiling");
host.Mock("mock:done").ReceivedExchanges[0].In.Headers[LlmHeaders.ToolIterations]
.Should().Be(2, "two iterations completed; the third provider call never happened");
budgetSpy.StopReasons.Should().Contain(r => r != null && r.Contains("input-token budget exceeded"));
}
[Fact]
public async Task RouteWithCostBudget_WithoutCostCalculator_FailsFast()
{
var provider = new FakeProvider().EnqueueText("never reached");
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Budget(costUsd: 0.5m).AsUri())
.To("mock:done"));
var thrown = await Record.ExceptionAsync(() => host.SendAsync("direct:agent", "hello"));
thrown.Should().BeOfType()
.Which.Message.Should().Contain("ICostCalculator",
"the message must name what is missing, not just that something is wrong");
provider.CallCount.Should().Be(0, "an unpriceable cost ceiling must be refused before any spend");
}
[Fact]
public async Task RouteWithCostBudget_WithCalculator_StopsWithBudgetReason()
{
var provider = new FakeProvider()
.EnqueueText("first answer", tokensIn: 1000, tokensOut: 1000)
.EnqueueText("never asked for", tokensIn: 1000, tokensOut: 1000);
var budgetSpy = new SpyBudgetEnforcer();
await using var host = LiveLlmHost.Build(budget: budgetSpy, costCalculator: new FlatCostCalculator(0.01m))
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Budget(costUsd: 0.005m).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "hello");
provider.CallCount.Should().Be(1, "the priced iteration crossed the ceiling, so the loop stopped");
budgetSpy.StopReasons.Should().Contain(r => r != null && r.Contains("cost budget exceeded"));
}
[Fact]
public void BudgetBuilder_EmitsOnlyTheDimensionsItWasGiven()
{
var outputOnly = LlmDsl.Factory("demo").Budget(outputTokens: 50).AsUri();
outputOnly.Should().Contain("budgetOutputTokens=50");
outputOnly.Should().NotContain("budgetInputTokens",
"an unset dimension must stay absent — zero and \"not set\" must not become one state in the URI");
outputOnly.Should().NotContain("budgetCostUsd");
LlmDsl.Factory("demo").AsUri().Should().NotContain("budget",
"a route that asked for no budget carries none");
}
[Fact]
public void CustomBudgetEnforcer_SurvivesAddRedbLlmStorage()
{
var services = new ServiceCollection();
services.AddSingleton(new RouteContext());
services.AddRedbRouteLlm();
var mine = new SpyBudgetEnforcer();
services.AddSingleton(mine);
services.AddRedbLlmStorage();
using var sp = services.BuildServiceProvider();
sp.GetRequiredService().Should().BeSameAs(mine,
"AddRedbLlmStorage must never take away a governance implementation the host registered");
}
[Fact]
public void ShippedBudgetEnforcer_IsReplacedByStoreEnforcer()
{
var services = new ServiceCollection();
services.AddSingleton(new RouteContext());
services.AddRedbRouteLlm();
services.AddRedbLlmStorage();
using var sp = services.BuildServiceProvider();
sp.GetRequiredService().Should().BeOfType(
"with a store present the shipped per-run default is replaced — otherwise usage is never accumulated");
}
///
/// A zero ceiling means "no ceiling": the enforcer only enforces positive limits, and the option docs
/// now say so. Pinned here so the documentation cannot drift back into promising a stop sign that the
/// code does not implement.
///
[Fact]
public async Task ZeroBudget_MeansNoCeiling()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1", tokensIn: 500, tokensOut: 1)
.EnqueueText("done", tokensIn: 500, tokensOut: 1);
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply);
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).Budget(inputTokens: 0).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
provider.CallCount.Should().Be(2,
"a zero ceiling does not stop the run — 500 tokens per iteration and the loop still reaches the model's own stop reason");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/EngineCompositionTests.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/tests/redb.Route.Tests.Llm/Governance/EngineCompositionTests.cs
----
using System.Security.Claims;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.Governance;
///
/// The composition path, which is not the tests' path: every other test here hand-wires the engine
/// (new AgentEngine(...)), while a real host lets AddRedbRouteLlm() build it. If that path
/// loses a governance seam, every promise of this phase holds only inside the test suite — so the
/// container's engine is exercised end-to-end here.
///
[Trait("Category", "Governance")]
public sealed class EngineCompositionTests
{
private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
private const string Input = """{"q":"x"}""";
private const string Claim = "orders:read";
///
/// A claims-required tool through the container's engine: the tool fires only if the engine the
/// container built carries the registered claims source and a producer template.
///
[Fact]
public async Task EngineFromDi_DispatchesAClaimRequiredTool()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("done");
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
requiredClaims: [Claim]);
await using var host = LiveLlmHost.Build(engineFromDi: true)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
var principal = new ClaimsPrincipal(
new ClaimsIdentity([new Claim("scope", Claim)], authenticationType: "test"));
await host.SendAsync("direct:agent", "Call the tool.",
configure: ex => ExchangePrincipal.Set(ex, principal));
var sinkBody = host.Mock("mock:done").ReceivedExchanges[0].In.Body?.ToString() ?? "(no body)";
tool.CapturedInputs.Should().HaveCount(1,
$"AddRedbRouteLlm() registers the default claims source — the engine it builds must be the one using it. Sink said: {sinkBody}");
}
///
/// A read-only, Persist-cached tool through the container's engine: the second identical call inside
/// one run is answered from the cache, which only happens if the container wired the cache layer into
/// the engine it built.
///
[Fact]
public async Task EngineFromDi_AnswersARepeatedCallFromTheCache()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueToolUse("lookup", Input, "tu_2")
.EnqueueText("done");
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
caching: ToolCachingPolicy.Memoize);
await using var host = LiveLlmHost.Build(engineFromDi: true)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool twice.");
tool.CapturedInputs.Should().HaveCount(1,
"the container's engine must consult the cache it registered, not only the hand-wired one");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/IdempotencyGateTests.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/tests/redb.Route.Tests.Llm/Governance/IdempotencyGateTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.Governance;
///
/// Idempotency gate (wave 5). The spec gates the idempotency store on the declared side-effect class:
/// a mutating tool is reserved before it runs and a replay of the same tool_use id returns the
/// stored result, while a read-only tool is never reserved — it has no side effect to de-duplicate and
/// a reservation would cost store round-trips on every call.
///
/// Both tests set a conversation id (via ?conversation=header); without one the engine's
/// idempotency branch has nowhere to store anything.
///
///
[Trait("Category", "Governance")]
public sealed class IdempotencyGateTests
{
private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
private const string ConversationId = "c-1";
private const string Input = """{"q":"x"}""";
private const string Reply = """{"answer":"42"}""";
[Fact]
public async Task ReadOnlyTool_DoesNotConsultIdempotencyStore()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1")
.EnqueueText("done");
var idempotency = new SpyIdempotencyStore();
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
sideEffect: ToolSideEffect.ReadOnly);
await using var host = LiveLlmHost.Build(idempotency: idempotency)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").ConversationFromHeader().Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.",
new Dictionary { [LlmHeaders.ConversationId] = ConversationId });
tool.CapturedInputs.Should().HaveCount(1, "the tool itself still runs");
idempotency.Reservations.Should().BeEmpty(
"a read-only tool has no side effect to deduplicate — reserving it costs a store round-trip for nothing");
}
[Fact]
public async Task MutatingTool_ReservesAndCompletesOnce()
{
var provider = new FakeProvider()
.EnqueueToolUse("write", """{"q":"x"}""", "tu_1")
.EnqueueText("done");
var idempotency = new SpyIdempotencyStore();
var tool = new EchoToolRoute("write", "Mutate something.", Schema, """{"answer":"ok"}""",
sideEffect: ToolSideEffect.Mutating);
await using var host = LiveLlmHost.Build(idempotency: idempotency)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").ConversationFromHeader().Tools("write").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Mutate.",
new Dictionary { [LlmHeaders.ConversationId] = ConversationId });
tool.CapturedInputs.Should().HaveCount(1);
idempotency.Reservations.Should().HaveCount(1, "a mutating tool is reserved before it runs");
idempotency.Completions.Should().HaveCount(1, "and completed after it succeeded");
}
[Fact]
public async Task MutatingTool_Replay_IsServedFromStoreAndReportedAsIdempotencyHit()
{
var provider = new FakeProvider()
.EnqueueToolUse("write", Input, "tu_1")
.EnqueueText("done")
.EnqueueToolUse("write", Input, "tu_1")
.EnqueueText("done");
var idempotency = new SpyIdempotencyStore();
var spy = new ToolInvocationSpy();
var tool = new EchoToolRoute("write", "Mutate something.", Schema, Reply,
sideEffect: ToolSideEffect.Mutating);
await using var host = LiveLlmHost.Build(spy, idempotency: idempotency)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").ConversationFromHeader().Tools("write").MaxIterations(4).AsUri())
.To("mock:done"));
var headers = new Dictionary { [LlmHeaders.ConversationId] = ConversationId };
await host.SendAsync("direct:agent", "Mutate.", headers);
await host.SendAsync("direct:agent", "Mutate.", headers);
tool.CapturedInputs.Should().HaveCount(1,
"the replayed tool_use id is answered from the store instead of mutating a second time");
idempotency.Reservations.Should().HaveCount(2,
"the engine still asks the store on the replay — that question is the protection");
spy.ForTool("write").Should().Contain(i => i.Skipped && i.SkipReason == ToolSkipReasons.IdempotencyHit,
"the replay is reported to observers under its own reason, not as a cache hit");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/InMemoryStoresInTransactionWarningTests.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/tests/redb.Route.Tests.Llm/Governance/InMemoryStoresInTransactionWarningTests.cs
----
using System.Transactions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Processors;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm.Governance;
///
/// The in-memory conversation and tool idempotency stores do not take part in an ambient transaction, so a run
/// inside one warns, once per route and connection factory: after a rollback the transcript keeps the rolled-back
/// run's tool calls. The run itself goes on. No warning outside a transaction, with the redb stores, or with a
/// host's own store.
///
[Trait("Category", "Governance")]
public sealed class InMemoryStoresInTransactionWarningTests
{
private sealed class ListLogger : ILogger
{
private readonly List<(LogLevel Level, string Message)> _entries = new();
public IReadOnlyList Warnings
{
get { lock (_entries) return _entries.Where(e => e.Level == LogLevel.Warning).Select(e => e.Message).ToArray(); }
}
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func formatter)
{
lock (_entries) _entries.Add((logLevel, formatter(state, exception)));
}
}
/// A host's own conversation store; it happens to keep its rows in memory, which is its own business.
private sealed class HostConversationStore : IConversationStore
{
private readonly InMemoryConversationStore _inner = new();
public Task AppendAsync(string conversationId, string? parentId, LlmMessage message,
ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default)
=> _inner.AppendAsync(conversationId, parentId, message, meta, exchange, ct);
public Task> LoadPathAsync(string conversationId, string? leafId = null,
IExchange? exchange = null, CancellationToken ct = default)
=> _inner.LoadPathAsync(conversationId, leafId, exchange, ct);
public Task> LoadTreeAsync(string conversationId, IExchange? exchange = null,
CancellationToken ct = default)
=> _inner.LoadTreeAsync(conversationId, exchange, ct);
}
private static AgentEngine Engine(ILogger logger, IConversationStore? conversation,
IToolIdempotencyStore? idempotency) => new(
logger: logger,
producerTemplate: null,
observer: null,
budget: null,
approval: null,
redaction: null,
shadow: null,
conversation: conversation,
idempotency: idempotency,
approvalStore: null);
private static AgentRequest Request(string route, bool withTools = false)
{
var provider = new FakeProvider().EnqueueText("done");
return new AgentRequest
{
Factory = new LlmConnectionFactory { Name = "support", Provider = "fake", ModelId = provider.ModelId, PrebuiltProvider = provider },
Exchange = new Exchange(new Message("hello")) { RouteId = route },
UserContent = [new LlmTextBlock("hello")],
ConversationId = "conv-1",
Tools = withTools ? [new TenantScopedToolDescriptor()] : []
};
}
private static async Task RunInTransactionAsync(AgentEngine engine, AgentRequest request)
{
using var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
var response = await engine.RunAsync(request);
response.Content.OfType().Single().Text.Should().Be("done", "the run goes on as before");
tx.Complete();
}
[Fact]
public async Task InMemoryStores_InsideATransaction_WarnOncePerRouteAndFactory()
{
var logger = new ListLogger();
var engine = Engine(logger, new InMemoryConversationStore(),
new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository()));
await RunInTransactionAsync(engine, Request("orders", withTools: true));
await RunInTransactionAsync(engine, Request("orders", withTools: true));
logger.Warnings.Should().ContainSingle();
var warning = logger.Warnings[0];
warning.Should().Contain("llm:support").And.Contain("'orders'")
.And.Contain("InMemoryConversationStore and InMemoryToolIdempotencyStore")
.And.Contain("do not take part in the transaction")
.And.Contain("may not call the tool again")
.And.Contain("AddRedbLlmStorage()").And.Contain(".Transacted()");
await RunInTransactionAsync(engine, Request("billing"));
logger.Warnings.Should().HaveCount(2, "another route is another step, warned once on its own");
logger.Warnings[1].Should().Contain("'billing'").And.Contain("InMemoryConversationStore keep state")
.And.NotContain("InMemoryToolIdempotencyStore", "a run without tools never touches the idempotency store");
}
[Fact]
public async Task InMemoryStores_OutsideATransaction_DoNotWarn()
{
var logger = new ListLogger();
var engine = Engine(logger, new InMemoryConversationStore(),
new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository()));
await engine.RunAsync(Request("orders", withTools: true));
logger.Warnings.Should().BeEmpty();
}
[Fact]
public async Task AHostsOwnStore_InsideATransaction_IsNotWarnedAbout()
{
var logger = new ListLogger();
var engine = Engine(logger, new HostConversationStore(), idempotency: null);
await RunInTransactionAsync(engine, Request("orders", withTools: true));
logger.Warnings.Should().BeEmpty();
}
[Fact]
public void AddRedbLlmStorage_ReplacesBothInMemoryStores()
{
// The warning looks at the store instances the engine holds; with AddRedbLlmStorage() neither of them is an
// in-memory one, so a transacted run is not warned about. A run against the redb stores is covered by the
// storage suites, which need a database.
var services = new ServiceCollection();
services.AddSingleton(new RouteContext());
services.AddRedbRouteLlm();
services.AddRedbLlmStorage();
using var sp = services.BuildServiceProvider();
sp.GetRequiredService().Should().NotBeOfType();
sp.GetRequiredService().Should().NotBeOfType();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/RequiredClaimsTests.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/tests/redb.Route.Tests.Llm/Governance/RequiredClaimsTests.cs
----
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Llm.Extensions;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.Governance;
///
/// Claims enforcement (wave 2). A tool that declares .RequireClaim(...) may only fire when the
/// run's principal provably holds the claim; without a verifiable principal it is denied, and the
/// model is told the error code only.
///
/// The realistic runtime shape is exercised with the shipped default source, which reads the caller
/// from the exchange properties (never a header). A tool that declares claims with no source
/// registered does not even build — see .
///
///
[Trait("Category", "Governance")]
public sealed class RequiredClaimsTests
{
private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
private const string Claim = "orders:read";
/// An authenticated caller carrying each of as its own scope claim.
private static ClaimsPrincipal Principal(params string[] scopeValues)
=> PrincipalWithClaimType("scope", scopeValues);
/// An authenticated caller whose values arrive under .
private static ClaimsPrincipal PrincipalWithClaimType(string claimType, params string[] values)
=> new(new ClaimsIdentity(values.Select(v => new Claim(claimType, v)), authenticationType: "test"));
///
/// Runs a claim-required tool through the shipped default source, with
/// placed on the exchange the way a transport would (a property, before the route runs).
///
private static async Task<(EchoToolRoute Tool, ToolInvocationSpy Spy, IExchange Exchange)> RunWithPrincipalAsync(
ClaimsPrincipal? principal)
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1")
.EnqueueText("done");
var spy = new ToolInvocationSpy();
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
requiredClaims: [Claim]);
await using var host = LiveLlmHost.Build(spy, claimsSource: new ExchangePrincipalClaimsSource())
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
var exchange = await host.SendAsync("direct:agent", "Call the tool.", configure: ex =>
{
if (principal is not null) ExchangePrincipal.Set(ex, principal);
});
return (tool, spy, exchange);
}
[Fact]
public async Task RequiredClaimsTool_WithoutPrincipal_IsDenied()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1")
.EnqueueText("done");
var spy = new ToolInvocationSpy();
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
requiredClaims: [Claim]);
await using var host = LiveLlmHost.Build(spy, claimsSource: new DelegateToolClaimsSource(_ => null))
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
tool.CapturedInputs.Should().BeEmpty(
"a tool whose claims cannot be verified must never be invoked (fail closed)");
spy.ForTool("lookup").Should().NotBeEmpty("the denial is reported to observers")
.And.OnlyContain(i => i.Skipped && i.SkipReason != null && i.SkipReason.StartsWith("claims_missing"));
}
[Fact]
public async Task RequiredClaimsTool_WithUserHeaderButNoPrincipal_IsDenied()
{
// The header is the *audit identity* fallback, not an authorization source: a client-supplied
// string must not be enough to satisfy a declared claim.
var provider = new FakeProvider()
.EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1")
.EnqueueText("done");
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
requiredClaims: [Claim]);
await using var host = LiveLlmHost.Build(claimsSource: new DelegateToolClaimsSource(_ => null))
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.",
new Dictionary { [LlmHeaders.UserId] = "user-1" });
tool.CapturedInputs.Should().BeEmpty(
"an unverified client-supplied identity must not satisfy RequiredClaims");
}
[Fact]
public async Task RequiredClaimsTool_WithAllClaims_IsInvoked()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1")
.EnqueueText("done");
var spy = new ToolInvocationSpy();
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
requiredClaims: [Claim]);
await using var host = LiveLlmHost.Build(spy,
claimsSource: new DelegateToolClaimsSource(_ => [Claim, "orders:write"]))
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
tool.CapturedInputs.Should().HaveCount(1, "a principal holding the claim runs the tool");
spy.ForTool("lookup").Should().Contain(i => !i.Skipped, "and the invocation is not a skip");
}
[Fact]
public async Task RequireClaim_WithoutClaimsSource_FailsRouteBuild()
{
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
requiredClaims: [Claim]);
// No claims source on purpose: the tool could never fire, so the route must not build.
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub" });
var thrown = await Record.ExceptionAsync(() => host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done")));
thrown.Should().BeOfType()
.Which.Message.Should().Contain("IToolClaimsSource",
"the message must name the missing registration so the fix is obvious");
}
///
/// The positive path through the shipped default source: the caller proved itself to a transport,
/// the principal sits on the exchange, and the required scope is there.
///
[Fact]
public async Task RequiredClaimsTool_WithVerifiedPrincipalScope_IsInvoked()
{
var (tool, spy, _) = await RunWithPrincipalAsync(Principal(Claim));
tool.CapturedInputs.Should().HaveCount(1, "the caller holds the required scope");
spy.ForTool("lookup").Should().Contain(i => !i.Skipped);
}
/// Microsoft Entra ID spells the same vocabulary under scp; the default source reads both.
[Fact]
public async Task RequiredClaimsTool_ScpClaimType_IsHonoured()
{
var (tool, _, _) = await RunWithPrincipalAsync(PrincipalWithClaimType("scp", Claim));
tool.CapturedInputs.Should().HaveCount(1);
}
///
/// Real issuers split one logical set into several claims and pad the values; neither may turn a
/// satisfied requirement into a denial.
///
[Fact]
public async Task RequiredClaimsTool_PaddedAndRepeatedScopes_AreNormalized()
{
var (tool, _, _) = await RunWithPrincipalAsync(
PrincipalWithClaimType("scope", $"{Claim} orders:write ", Claim, " orders:write "));
tool.CapturedInputs.Should().HaveCount(1, "padding and repetition are formatting, not a different claim");
}
/// A verified caller who simply does not hold the scope is denied — with the audit reason.
[Fact]
public async Task RequiredClaimsTool_PrincipalWithoutTheScope_IsDenied()
{
var (tool, spy, _) = await RunWithPrincipalAsync(Principal("orders:write"));
tool.CapturedInputs.Should().BeEmpty("holding another scope is not holding this one");
spy.ForTool("lookup").Should().OnlyContain(i => i.Skipped
&& i.SkipReason != null && i.SkipReason.StartsWith(ToolSkipReasons.ClaimsMissing));
}
///
/// An identity that is not authenticated is not a principal: a transport that passes through an
/// anonymous placeholder must not be able to satisfy a requirement.
///
[Fact]
public async Task RequiredClaimsTool_UnauthenticatedPrincipal_IsDenied()
{
var anonymous = new ClaimsPrincipal(new ClaimsIdentity([new Claim("scope", Claim)]));
var (tool, _, _) = await RunWithPrincipalAsync(anonymous);
tool.CapturedInputs.Should().BeEmpty(
"claims on an unauthenticated identity are a claim about nothing");
}
///
/// The caller reaches the exchange the tool itself runs on — the identity survives the linked child
/// the agent dispatches into, which is what makes a claims check meaningful inside a tool route.
///
[Fact]
public async Task Principal_ReachesTheToolExchange()
{
var principal = Principal(Claim);
var (tool, _, _) = await RunWithPrincipalAsync(principal);
tool.CapturedProperties.Should().Contain(
p => p.ContainsKey(ExchangePrincipal.PropertyKey)
&& ReferenceEquals(p[ExchangePrincipal.PropertyKey], principal),
"a tool route reads the caller from its own exchange, not from a translation of the request");
}
///
/// Scope values are space-delimited (RFC 6749 §3.3); a comma is a legal character inside a
/// scope token. Treating it as a separator would turn one granted scope — orders:read,orders:write
/// — into two grants, which is the one direction a security check must never fail in.
///
[Fact]
public async Task RequiredClaimsTool_CommaIsNotAScopeSeparator()
{
var (tool, spy, _) = await RunWithPrincipalAsync(Principal($"{Claim},orders:write"));
tool.CapturedInputs.Should().BeEmpty(
"the value is a single scope token containing a comma, not two scopes");
spy.ForTool("lookup").Should().OnlyContain(i => i.Skipped);
}
///
/// The default source on its own: which claim types it reads, and the two states it must keep apart
/// — "no principal" and "a principal that holds nothing".
///
[Fact]
public void ExchangePrincipalClaimsSource_ReadsScopeClaimTypes_AndRefusesAnonymous()
{
var source = new ExchangePrincipalClaimsSource();
var exchange = Exchange.Create(new Message("x"), scopeFactory: null);
source.GetClaims(exchange).Should().BeNull("an exchange with no principal proves nothing");
ExchangePrincipal.Set(exchange, PrincipalWithClaimType(
"http://schemas.microsoft.com/identity/claims/scope", $"{Claim} orders:write"));
source.GetClaims(exchange).Should().BeEquivalentTo([Claim, "orders:write"],
"the Entra ID v1 scope claim type carries the same vocabulary");
ExchangePrincipal.Set(exchange,
new ClaimsPrincipal(new ClaimsIdentity([new Claim("scope", Claim)])));
source.GetClaims(exchange).Should().BeNull(
"an identity that is not authenticated is not a principal, so an anonymous placeholder cannot satisfy a requirement");
ExchangePrincipal.Set(exchange, Principal());
source.GetClaims(exchange).Should().BeEmpty(
"a principal holding nothing differs from no principal — both deny, but only one is diagnosable");
}
///
/// Claims work out of the box: the shipped container resolves the caller-based source, so a tool
/// route can declare a requirement without the host wiring anything.
///
[Fact]
public void AddRedbRouteLlm_RegistersPrincipalClaimsSourceByDefault()
{
var services = new ServiceCollection();
services.AddRedbRouteLlm();
using var provider = services.BuildServiceProvider();
provider.GetRequiredService().Should().BeOfType(
"the caller's principal is the default answer to \"what may this run do\"");
}
/// A host with its own vocabulary keeps it: the default registration must not win over it.
[Fact]
public void HostRegisteredClaimsSource_WinsOverTheDefault()
{
var services = new ServiceCollection();
var mine = new DelegateToolClaimsSource(_ => ["host:everything"]);
services.AddSingleton(mine);
services.AddRedbRouteLlm();
using var provider = services.BuildServiceProvider();
provider.GetRequiredService().Should().BeSameAs(mine);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/RouteTransactionTests.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/tests/redb.Route.Tests.Llm/Governance/RouteTransactionTests.cs
----
using System.Transactions;
using redb.Route.Llm.Engine.Governance;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.Governance;
///
/// The agent inside a route transaction (a route's .Transacted()). Its database work and deferred
/// sends, its tools' included, belong to that transaction and roll back with it. Three things do not: an
/// external tool, whose action no rollback can take back, is not run there; the budget, whose tokens are
/// paid whatever happens to the transaction, is recorded outside it; and the shadow run stays out of it.
///
[Trait("Category", "Governance")]
public sealed class RouteTransactionTests
{
private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
private const string Input = """{"q":"x"}""";
private static LlmConnectionFactory Factory(FakeProvider provider) => new()
{
Provider = "fake",
ModelId = provider.ModelId,
PrebuiltProvider = provider
};
private static AgentEngine Engine(IBudgetEnforcer? budget = null, IShadowRunner? shadow = null) => new(
logger: null,
producerTemplate: null,
observer: null,
budget: budget,
approval: null,
redaction: null,
shadow: shadow,
conversation: null,
idempotency: null,
approvalStore: null);
private static AgentRequest Request(FakeProvider provider) => new()
{
Factory = Factory(provider),
Exchange = new Exchange(new Message("status?")),
UserContent = [new LlmTextBlock("status?")]
};
[Fact]
public async Task ExternalTool_InsideTransactedRoute_IsNotRun()
{
var provider = new FakeProvider()
.EnqueueToolUse("send_mail", Input, "tu_1")
.EnqueueText("done");
var spy = new ToolInvocationSpy();
var tool = new EchoToolRoute("send_mail", "Send an e-mail.", Schema, """{"sent":true}""",
sideEffect: ToolSideEffect.External);
var routeWasTransacted = false;
await using var host = LiveLlmHost.Build(spy)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.Transacted()
.Process(_ => routeWasTransacted = Transaction.Current is not null)
.To(LlmDsl.Factory("demo").Tools("send_mail").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Mail the report.");
routeWasTransacted.Should().BeTrue("the agent step must run inside the route's transaction, or this test proves nothing");
tool.CapturedInputs.Should().BeEmpty(
"an irreversible action does not run inside a transaction that can still roll back");
spy.ForTool("send_mail").Should().ContainSingle(
i => i.Skipped && i.SkipReason == ToolSkipReasons.ExternalInTransaction,
"the audit channel records why the tool did not run");
var result = provider.SentMessages.Should().HaveCount(2).And.Subject.ElementAt(1)
.SelectMany(m => m.Content).OfType().Should().ContainSingle().Subject;
result.IsError.Should().BeTrue();
result.OutputJson.Should().Contain(ToolResultErrors.ExternalInTransaction,
"the model is told the tool could not run, so it can answer without it");
}
[Fact]
public async Task ExternalTool_WithoutTransaction_Runs()
{
var provider = new FakeProvider()
.EnqueueToolUse("send_mail", Input, "tu_1")
.EnqueueText("done");
var tool = new EchoToolRoute("send_mail", "Send an e-mail.", Schema, """{"sent":true}""",
sideEffect: ToolSideEffect.External);
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("send_mail").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Mail the report.");
tool.CapturedInputs.Should().HaveCount(1, "outside a transaction nothing can roll back under the action");
}
[Fact]
public async Task MutatingTool_InsideTransactedRoute_Runs()
{
var provider = new FakeProvider()
.EnqueueToolUse("write", Input, "tu_1")
.EnqueueText("done");
var tool = new EchoToolRoute("write", "Mutate something.", Schema, """{"answer":"ok"}""",
sideEffect: ToolSideEffect.Mutating);
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.Transacted()
.To(LlmDsl.Factory("demo").Tools("write").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Mutate.");
tool.CapturedInputs.Should().HaveCount(1,
"a mutating tool's writes roll back with the transaction, so it belongs inside it");
}
[Fact]
public async Task Budget_InsideTransaction_IsRecordedOutsideIt()
{
var sawTransactionAtProvider = false;
var provider = new FakeProvider
{
OnCall = (_, _) =>
{
sawTransactionAtProvider = Transaction.Current is not null;
return Task.CompletedTask;
}
}.EnqueueText("done");
var budget = new SpyBudgetEnforcer();
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await Engine(budget: budget).RunAsync(Request(provider));
scope.Complete();
}
sawTransactionAtProvider.Should().BeTrue("the run itself is inside the transaction, or this test proves nothing");
budget.PreChecks.Should().Be(1);
budget.PostChecks.Should().Be(1);
budget.SawAmbientTransaction.Should().HaveCount(2).And.OnlyContain(seen => !seen,
"tokens are paid when the provider answers; a rollback must not un-count them");
}
/// Reports whether the shadow run saw an ambient transaction.
private sealed class ShadowSpy : IShadowRunner
{
public TaskCompletionSource SawTransaction { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public bool Enabled => true;
public Task RunAsync(ILlmProvider primary, LlmRequest request, LlmResponse primaryResponse, CancellationToken ct = default)
{
SawTransaction.TrySetResult(Transaction.Current is not null);
return Task.CompletedTask;
}
}
[Fact]
public async Task ShadowRun_DoesNotInheritTheTransaction()
{
var provider = new FakeProvider().EnqueueText("done");
var shadow = new ShadowSpy();
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await Engine(shadow: shadow).RunAsync(Request(provider));
scope.Complete();
}
(await shadow.SawTransaction.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().BeFalse(
"the shadow runs beside the primary run: it must not write into its transaction");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/StreamingToolPolicyTests.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/tests/redb.Route.Tests.Llm/Governance/StreamingToolPolicyTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.Governance;
///
/// Streaming × tools. Both modes run the agent engine with its tools: stream=calls inside the route
/// (StreamCallsTests), stream=body when the body is read (LazyStreamTests). So the combination is allowed when
/// the endpoint is created; the one placement rule left is stream=body inside .Transacted(), refused at
/// run time because the block would commit before the answer exists.
///
[Trait("Category", "Governance")]
public sealed class StreamingToolPolicyTests
{
[Theory]
[InlineData(LlmStreamMode.Calls)]
[InlineData(LlmStreamMode.Body)]
public async Task StreamingWithTools_IsAllowed(LlmStreamMode mode)
{
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory
{
Provider = "stub",
PrebuiltProvider = new FakeProvider().EnqueueText("done")
});
await host.StartAsync(r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Stream(mode).Tools("*").AsUri()));
IExchange? exchange = null;
var thrown = await Record.ExceptionAsync(async () => exchange = await host.SendAsync("direct:agent", "hello"));
if (exchange is not null) await exchange.DisposeAsync();
thrown.Should().BeNull("a tool-using agent streams in either mode");
exchange!.Exception.Should().BeNull();
}
[Fact]
public async Task StreamingWithoutTools_IsStillAllowed()
{
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = new FakeProvider() });
var started = await Record.ExceptionAsync(() => host.StartAsync(r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Stream(LlmStreamMode.Body).AsUri())
.To("mock:done")));
started.Should().BeNull("streaming plain completions is untouched");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/ThinkingProviderSwitchTests.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/tests/redb.Route.Tests.Llm/Governance/ThinkingProviderSwitchTests.cs
----
using redb.Route.Llm.Engine.Storage;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm.Governance;
///
/// A stored conversation can be continued on another provider: switching the factory is the caller's
/// decision, and the history goes to the new provider as it was written, thinking blocks included.
/// Each provider's request path sends what its wire can express (the provider request tests pin
/// that); the engine does not sort blocks by who produced them.
///
public sealed class ThinkingProviderSwitchTests
{
private const string Prompt = "status of order 42?";
private static AgentEngine Engine(IConversationStore store) => new(
logger: null,
producerTemplate: null,
observer: null,
budget: null,
approval: null,
redaction: null,
shadow: null,
conversation: store,
idempotency: null,
approvalStore: null);
private static ConversationMessageMeta Meta(string providerId, int iteration) => new()
{
CreatedAtUtc = DateTime.UtcNow,
Iteration = iteration,
ProviderId = providerId,
Usage = new LlmUsage(1, 1)
};
[Fact]
public async Task ProviderSwitch_StoredThinkingTravelsWithTheHistory()
{
var store = new InMemoryConversationStore();
const string ConvId = "conv-switch";
var promptId = await store.AppendAsync(ConvId, null, LlmMessage.User(Prompt), Meta("anthropic", 0));
await store.AppendAsync(ConvId, promptId, new LlmMessage
{
Role = "assistant",
Content = [new LlmThinkingBlock("anthropic reasoning", "sig-1"), new LlmTextBlock("shipped")]
}, Meta("anthropic", 1));
// The conversation was written by Anthropic; this run asks DeepSeek.
var provider = new FakeProvider();
await Engine(store).RunAsync(new AgentRequest
{
Factory = new LlmConnectionFactory
{
Provider = "deepseek",
ModelId = provider.ModelId,
PrebuiltProvider = provider
},
Exchange = new Exchange(new Message(Prompt)),
UserContent = [new LlmTextBlock(Prompt)],
ConversationId = ConvId
});
var sent = provider.SentMessages.Should().ContainSingle().Subject;
sent.Should().HaveCount(3, "the stored prompt, the stored turn and this run's prompt");
var turn = sent[1].Content;
turn.Should().HaveCount(2, "the stored turn goes to the new provider as it was written");
turn[0].Should().BeOfType().Which.Signature.Should().Be("sig-1");
turn[1].Should().BeOfType().Which.Text.Should().Be("shipped");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/ToolCacheTests.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/tests/redb.Route.Tests.Llm/Governance/ToolCacheTests.cs
----
using System.Security.Claims;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.Governance;
///
/// Tool-result cache (wave 3). Two layers, one question — "do I already have an output for this exact
/// input?": Memoize is answered by a run-scoped in-process memo, Persist by the
/// configured store. A hit is a skipped invocation reported to observers, never a silent optimisation.
///
/// The last two tests are locks on the boundaries: a memo must not survive its run, and a mutating
/// tool must not be cacheable at all (a hit would suppress the side effect it stands for).
///
///
[Trait("Category", "Governance")]
public sealed class ToolCacheTests
{
private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
private const string Input = """{"q":"x"}""";
private const string Reply = """{"answer":"42"}""";
[Fact]
public async Task CachingMemoize_TwoIdenticalCalls_SecondIsServedFromCache()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueToolUse("lookup", Input, "tu_2")
.EnqueueText("done");
var spy = new ToolInvocationSpy();
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Memoize);
await using var host = LiveLlmHost.Build(spy)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool twice.");
tool.CapturedInputs.Should().HaveCount(1,
"Memoize answers the second identical call from the run-scoped cache instead of dispatching it");
spy.ForTool("lookup").Should().Contain(i => i.Skipped && i.SkipReason == ToolSkipReasons.CacheHit,
"a hit is reported as a skipped invocation, not as an invisible optimisation");
}
[Fact]
public async Task CachingNone_TwoIdenticalCalls_BothDispatch()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueToolUse("lookup", Input, "tu_2")
.EnqueueText("done");
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""");
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool twice.");
tool.CapturedInputs.Should().HaveCount(2,
"with caching off every call must reach the tool — the cache must not invent memoisation");
}
[Fact]
public async Task CachingPersist_SurvivesNewEngineInstance()
{
var store = new SpyToolCacheStore();
var toolInFirstHost = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Persist);
var firstRun = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("done");
await using (var host = LiveLlmHost.Build(toolCache: store)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = firstRun }))
{
await host.StartAsync(toolInFirstHost, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
}
toolInFirstHost.CapturedInputs.Should().HaveCount(1);
store.Sets.Should().HaveCount(1, "Persist writes the output to the store");
// A second host means a second engine instance: only the store carries state across.
var toolInSecondHost = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Persist);
var secondRun = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_2")
.EnqueueText("done");
await using (var host = LiveLlmHost.Build(toolCache: store)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = secondRun }))
{
await host.StartAsync(toolInSecondHost, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
}
toolInSecondHost.CapturedInputs.Should().BeEmpty(
"the persisted entry answers the identical call from a new engine instance");
}
[Fact]
public async Task Cache_TwoTenantsSameInput_TwoEntries()
{
var store = new SpyToolCacheStore();
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("done")
.EnqueueToolUse("lookup", Input, "tu_2")
.EnqueueText("done")
.EnqueueToolUse("lookup", Input, "tu_3")
.EnqueueText("done");
var routes = new TenantScopedToolRoutes();
await using var host = LiveLlmHost.Build(toolCache: store)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
host.ToolRegistry.Register(new TenantScopedToolDescriptor());
await host.StartAsync(routes, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools(TenantScopedToolDescriptor.ToolName).MaxIterations(4).AsUri())
.To("mock:done"));
await SendAsTenant(host, "a");
await SendAsTenant(host, "b");
await SendAsTenant(host, "a");
routes.CountFor("a").Should().Be(1,
"the identical call from the same tenant is answered from its own entry");
routes.CountFor("b").Should().Be(1,
"tenant b sends the same input, but its resolved address differs — the cache must never serve one tenant's output to another");
store.Sets.Should().HaveCount(2, "one entry per resolved address");
store.Sets.Should().OnlyHaveUniqueItems("the two entries carry different keys");
}
[Fact]
public async Task Memoize_EntriesDoNotOutliveTheRun()
{
var store = new SpyToolCacheStore();
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("done")
.EnqueueToolUse("lookup", Input, "tu_2")
.EnqueueText("done");
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Memoize);
await using var host = LiveLlmHost.Build(toolCache: store)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
await host.SendAsync("direct:agent", "Call the tool.");
tool.CapturedInputs.Should().HaveCount(2,
"the memo belongs to one run — a later run must dispatch the identical call again");
store.Sets.Should().BeEmpty("Memoize is served in process: it never reaches the store");
store.Gets.Should().BeEmpty("and the store is never read for it either");
}
[Fact]
public async Task MutatingTool_WithCaching_IsRejectedAtBuild()
{
var tool = new EchoToolRoute("lookup", "Send an invoice.", Schema, Reply,
sideEffect: ToolSideEffect.Mutating, caching: ToolCachingPolicy.Persist);
await using var host = LiveLlmHost.Build()
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub" });
var thrown = await Record.ExceptionAsync(() => host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done")));
thrown.Should().BeOfType()
.Which.Message.Should().Contain("Caching",
"a cache hit would suppress the side effect, so the route must not build at all");
}
private static Task SendAsTenant(LiveLlmHost host, string tenant)
=> host.SendAsync("direct:agent", "Call the tool.",
new Dictionary { [TenantScopedToolDescriptor.TenantHeader] = tenant });
///
/// A cached entry belongs to the policy the tool had when the entry was written. Tightening the
/// policy (here: adding a required claim) must not be answered by that entry — otherwise data
/// fetched while the tool was open to everyone keeps flowing after it was closed down.
///
[Fact]
public async Task CachingPolicyChange_DoesNotServeAnEntryWrittenUnderTheOldPolicy()
{
var store = new SpyToolCacheStore();
var lax = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Persist);
var firstRun = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("done");
await using (var host = LiveLlmHost.Build(toolCache: store)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = firstRun }))
{
await host.StartAsync(lax, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
}
lax.CapturedInputs.Should().HaveCount(1);
store.Sets.Should().HaveCount(1, "the entry was written while the tool had no requirement");
var stricter = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Persist, requiredClaims: ["orders:read"]);
var secondRun = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_2")
.EnqueueText("done");
var spy = new ToolInvocationSpy();
var principal = new ClaimsPrincipal(
new ClaimsIdentity([new Claim("scope", "orders:read")], authenticationType: "test"));
await using (var host = LiveLlmHost.Build(spy,
claimsSource: new ExchangePrincipalClaimsSource(), toolCache: store)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = secondRun }))
{
await host.StartAsync(stricter, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.",
configure: ex => ExchangePrincipal.Set(ex, principal));
}
stricter.CapturedInputs.Should().HaveCount(1,
"a stricter policy is a different cache entry, not a hit on the laxer one");
spy.ForTool("lookup").Should().Contain(i => !i.Skipped);
store.Sets.Should().HaveCount(2, "the new policy writes its own entry");
}
///
/// The tool route sees the caller's principal, so "same input" is not "same answer": an entry
/// fetched for one caller must not be served to another, even when both hold the same rights.
///
[Fact]
public async Task Cache_PersistedEntry_IsNotServedAcrossCallers()
{
var store = new SpyToolCacheStore();
async Task RunAsAsync(string subject)
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("done");
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Persist);
await using var host = LiveLlmHost.Build(toolCache: store)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
var principal = new ClaimsPrincipal(
new ClaimsIdentity([new Claim(ClaimTypes.Name, subject)], authenticationType: "test"));
await host.SendAsync("direct:agent", "Call the tool.",
configure: ex => ExchangePrincipal.Set(ex, principal));
return tool.CapturedInputs.Count;
}
(await RunAsAsync("alice")).Should().Be(1);
(await RunAsAsync("bob")).Should().Be(1,
"another caller asking the same question is a different question — the entry belongs to alice");
store.Sets.Should().HaveCount(2, "one entry per caller");
}
///
/// Headers the route opted into propagating (.PropagateToolHeaders(...)) reach the tool, so
/// they are part of what it answers.
///
[Fact]
public async Task Cache_PersistedEntry_IsNotServedAcrossPropagatedHeaderValues()
{
var store = new SpyToolCacheStore();
async Task RunWithTenantAsync(string tenant)
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("done");
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Persist);
await using var host = LiveLlmHost.Build(toolCache: store)
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").PropagateToolHeaders("x-tenant-id")
.Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.",
new Dictionary { ["x-tenant-id"] = tenant });
return tool.CapturedInputs.Count;
}
(await RunWithTenantAsync("acme")).Should().Be(1);
(await RunWithTenantAsync("globex")).Should().Be(1,
"the header the route chose to pass on is part of the tool's input");
store.Sets.Should().HaveCount(2, "one entry per propagated header value");
}
///
/// An unavailable cache costs a hit, never the run: the tool still executes, the model still gets a
/// normal result, and the failure is logged rather than thrown at the model.
///
[Fact]
public async Task CacheStoreFailure_DoesNotFailTheRun()
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("done");
var spy = new ToolInvocationSpy();
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply,
caching: ToolCachingPolicy.Persist);
await using var host = LiveLlmHost.Build(spy, toolCache: new ThrowingToolCacheStore())
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.");
tool.CapturedInputs.Should().HaveCount(1, "a broken cache must not stop the tool from running");
spy.ForTool("lookup").Should().OnlyContain(i => !i.Skipped && i.Exception == null,
"the model receives a normal tool result, not a cache error");
}
///
/// The read-only rule is enforced where every descriptor path converges — the registry — so
/// LlmTool.Define(...).Build(), the [ExposeAsLlmTool] attribute and MCP discovery are
/// covered as well, not just the route DSL.
///
[Fact]
public void MutatingTool_WithCaching_IsRejectedByRegistration()
{
var descriptor = LlmTool.Define("send_invoice")
.EndpointUri("direct:send-invoice")
.Description("Send an invoice.")
.Input(Schema)
.SideEffect(ToolSideEffect.Mutating)
.Caching(ToolCachingPolicy.Persist)
.Build();
var act = () => new ToolDescriptorRegistry().Register(descriptor);
act.Should().Throw()
.Which.Message.Should().Contain("Caching",
"a cache hit would suppress the side effect — enforced for every registration path");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/Governance/ToolSetHashTests.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/tests/redb.Route.Tests.Llm/Governance/ToolSetHashTests.cs
----
using redb.Route.Llm.Engine.Storage;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm.Governance;
///
/// Wave 0 — red before the fix. MessageProps.ToolSetHash exists so an auditor can answer
/// "did the same prompt see a different tool surface?"; today the hash is computed from
/// name + description + input schema only, so a changed LlmToolSafety (a weaker gate)
/// leaves the hash untouched and the drift is invisible.
///
/// The test runs the same tool twice with different side-effect declarations and compares the
/// persisted hash — the observable auditors work with.
///
///
[Trait("Category", "Governance")]
public sealed class ToolSetHashTests
{
private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
private const string ConversationId = "c-hash";
[Fact]
public async Task ToolSetHash_DiffersWhenSafetyDiffers()
{
var readOnlyHash = await RunAndReadHashAsync(ToolSideEffect.ReadOnly);
var mutatingHash = await RunAndReadHashAsync(ToolSideEffect.Mutating);
readOnlyHash.Should().NotBeNull("the assistant message persists the tool surface hash");
mutatingHash.Should().NotBeNull();
mutatingHash.Should().NotBe(readOnlyHash,
"a policy change is part of the tool surface an auditor compares between runs");
}
[Fact]
public async Task ToolSetHash_DistinguishesClaimSplitting()
{
var singleClaim = await RunAndReadHashAsync(ToolSideEffect.ReadOnly, "a,b");
var twoClaims = await RunAndReadHashAsync(ToolSideEffect.ReadOnly, "a", "b");
singleClaim.Should().NotBeNull();
twoClaims.Should().NotBe(singleClaim,
"one claim named \"a,b\" and two claims \"a\",\"b\" are different requirements — a comma-joined hash would confuse them");
}
private static async Task RunAndReadHashAsync(ToolSideEffect sideEffect, params string[] claims)
{
var provider = new FakeProvider()
.EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1")
.EnqueueText("done");
var store = new InMemoryConversationStore();
var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""",
sideEffect: sideEffect, requiredClaims: claims);
// A claims source is required for a claim-declaring tool to build at all; the hash is computed
// from the declaration, so the run may still be denied the call.
await using var host = LiveLlmHost.Build(
conversation: store,
claimsSource: new DelegateToolClaimsSource(_ => null))
.AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider });
await host.StartAsync(tool, r => r.From("direct:agent")
.To(LlmDsl.Factory("demo").ConversationFromHeader().Tools("lookup").MaxIterations(4).AsUri())
.To("mock:done"));
await host.SendAsync("direct:agent", "Call the tool.",
new Dictionary { [LlmHeaders.ConversationId] = ConversationId });
var path = await store.LoadPathAsync(ConversationId);
return path.Select(m => m.Meta.ToolSetHash).FirstOrDefault(hash => hash is not null);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/InMemoryToolIdempotencyStoreTests.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/tests/redb.Route.Tests.Llm/InMemoryToolIdempotencyStoreTests.cs
----
using redb.Route.Llm.Engine.Storage;
using redb.Route.Llm.Extensions;
using redb.Route.Processors;
namespace redb.Route.Tests.Llm;
///
/// The expiry of : a completed call is forgotten ttl after it completed, on a
/// later reservation; a reservation in flight is never aged out. The clock is a test clock, so no test waits.
///
public sealed class InMemoryToolIdempotencyStoreTests
{
private sealed class ManualTime : TimeProvider
{
public DateTimeOffset Now { get; set; } = new(2026, 11, 25, 12, 0, 0, TimeSpan.Zero);
public override DateTimeOffset GetUtcNow() => Now;
}
private static readonly TimeSpan Ttl = TimeSpan.FromHours(24);
[Fact]
public async Task ACompletedCall_IsAHit_UntilTheTtlHasPassed()
{
var time = new ManualTime();
var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), Ttl, time);
(await store.TryReserveAsync("c", "tu-1")).IsNew.Should().BeTrue();
await store.CompleteAsync("c", "tu-1", """{"sent":true}""");
time.Now += Ttl - TimeSpan.FromMinutes(1);
var hit = await store.TryReserveAsync("c", "tu-1");
hit.IsNew.Should().BeFalse();
hit.CachedOutputJson.Should().Be("""{"sent":true}""");
}
[Fact]
public async Task ACompletedCall_IsForgotten_OnceTheTtlHasPassed()
{
var time = new ManualTime();
var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), Ttl, time);
(await store.TryReserveAsync("c", "tu-1")).IsNew.Should().BeTrue();
await store.CompleteAsync("c", "tu-1", """{"sent":true}""");
time.Now += Ttl + TimeSpan.FromMinutes(1);
var again = await store.TryReserveAsync("c", "tu-1");
again.IsNew.Should().BeTrue("the call completed more than the ttl ago, so it is forgotten");
}
[Fact]
public async Task AnotherCall_ForgetsTheExpiredOnes_SoTheStoreDoesNotGrowWithoutBound()
{
var time = new ManualTime();
var repository = new InMemoryIdempotentRepository();
var store = new InMemoryToolIdempotencyStore(repository, Ttl, time);
for (var i = 0; i < 5; i++)
{
(await store.TryReserveAsync("c", $"tu-{i}")).IsNew.Should().BeTrue();
await store.CompleteAsync("c", $"tu-{i}", "{}");
}
time.Now += Ttl + TimeSpan.FromMinutes(1);
(await store.TryReserveAsync("c", "tu-new")).IsNew.Should().BeTrue();
repository.Count.Should().Be(1, "only the new reservation is left");
}
[Fact]
public async Task AReservationInFlight_IsNotAgedOut_SoASecondRunCannotStart()
{
var time = new ManualTime();
var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), Ttl, time);
(await store.TryReserveAsync("c", "tu-long")).IsNew.Should().BeTrue(); // the tool is running, not completed
time.Now += Ttl * 3;
var second = await store.TryReserveAsync("c", "tu-long");
second.IsNew.Should().BeFalse("the first run has neither completed nor released, however long it takes");
second.CachedOutputJson.Should().Be("{}");
}
[Fact]
public async Task AReservationInFlight_ThatCompletesLate_IsKeptForTheTtlFromItsCompletion()
{
var time = new ManualTime();
var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), Ttl, time);
(await store.TryReserveAsync("c", "tu-long")).IsNew.Should().BeTrue();
time.Now += Ttl * 2;
await store.CompleteAsync("c", "tu-long", """{"late":true}""");
time.Now += Ttl - TimeSpan.FromMinutes(1);
var hit = await store.TryReserveAsync("c", "tu-long");
hit.IsNew.Should().BeFalse();
hit.CachedOutputJson.Should().Be("""{"late":true}""");
}
[Fact]
public async Task WithoutATtl_NothingExpires()
{
var time = new ManualTime();
var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), ttl: null, time);
(await store.TryReserveAsync("c", "tu-1")).IsNew.Should().BeTrue();
await store.CompleteAsync("c", "tu-1", "{}");
time.Now += TimeSpan.FromDays(365);
(await store.TryReserveAsync("c", "tu-1")).IsNew.Should().BeFalse();
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void ANonPositiveTtl_IsRefused(int seconds)
{
var act = () => new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), TimeSpan.FromSeconds(seconds));
act.Should().Throw();
}
[Fact]
public void TheDefaultRegistration_RemembersACompletedCallFor24Hours()
{
LlmServiceCollectionExtensions.DefaultToolIdempotencyTtl.Should().Be(TimeSpan.FromHours(24));
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LazyStreamTests.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/tests/redb.Route.Tests.Llm/LazyStreamTests.cs
----
using System.Net;
using System.Net.Sockets;
using redb.Route.Http;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// stream=body: the agent run, tools and all, happens when the body is read — after the route, as a streamed SQL
/// result is read — and the text of every model call streams into Out.Body as the model writes it. The body
/// belongs to its exchange: it reads the exchange's resources, so it is read once, released with the exchange, refused
/// by RequestBody (which ends the exchange before it returns), and refused inside .Transacted(), whose block
/// would commit before the answer exists.
///
public sealed class LazyStreamTests
{
private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""";
private const string Input = """{"q":"x"}""";
private const string Reply = """{"answer":"42"}""";
private static FakeProvider ToolThenAnswer() => new FakeProvider()
.EnqueueToolUse("lookup", Input, "tu_1")
.EnqueueText("The answer is 42.");
/// A one-call answer: for the tests about the body itself, where a tool would only add noise.
private static FakeProvider PlainAnswer() => new FakeProvider().EnqueueText("The answer is 42.");
private static LlmConnectionFactory Factory(ILlmProvider provider) =>
new() { Provider = "stub", PrebuiltProvider = provider };
private static async Task HostAsync(
ILlmProvider provider, EchoToolRoute tool, bool transacted = false, string options = "&tools=lookup")
{
var host = LiveLlmHost.Build().AddFactory("demo", Factory(provider));
var uri = $"llm://demo?stream=body&maxIterations=4{options}";
await host.StartAsync(tool, r =>
{
var from = r.From("direct:agent");
if (transacted) from.Transacted().To(uri);
else from.To(uri);
});
return host;
}
private static EchoToolRoute Lookup() => new("lookup", "Look up a fact.", Schema, Reply);
private static IAsyncEnumerable BodyOf(IExchange exchange) =>
(IAsyncEnumerable)(exchange.Out?.Body ?? exchange.In.Body)!;
private static async Task> ReadAsync(IAsyncEnumerable body)
{
var pieces = new List();
await foreach (var piece in body) pieces.Add(piece);
return pieces;
}
[Fact]
public async Task Body_WithTools_StreamsTheAnswerWhenRead()
{
var provider = new StreamingFakeProvider(ToolThenAnswer());
var tool = Lookup();
await using var host = await HostAsync(provider, tool);
var exchange = await host.SendAsync("direct:agent", "What is the answer?");
try
{
provider.StreamCalls.Should().Be(0, "nothing runs until the body is read");
var pieces = await ReadAsync(BodyOf(exchange));
string.Concat(pieces).Should().Be("The answer is 42.");
pieces.Should().HaveCountGreaterThan(1, "the text streams as the model writes it");
tool.CapturedInputs.Should().ContainSingle("the tool runs in the loop");
provider.StreamCalls.Should().Be(2, "both model calls are streamed");
exchange.Out!.Headers[LlmHeaders.ToolIterations].Should().Be(2, "the summary arrives after the run");
exchange.Out.Headers[LlmHeaders.StopReason].Should().Be(nameof(LlmStopReason.EndTurn));
}
finally
{
await exchange.DisposeAsync();
}
}
[Fact]
public async Task Body_ThinkingStaysOutOfTheBody()
{
var script = new FakeProvider().Enqueue(new LlmResponse
{
Content = [new LlmThinkingBlock("Let me look it up."), new LlmTextBlock("The answer is 42.")],
StopReason = LlmStopReason.EndTurn
});
await using var host = await HostAsync(new StreamingFakeProvider(script), Lookup(), options: "");
var exchange = await host.SendAsync("direct:agent", "What is the answer?");
try
{
string.Concat(await ReadAsync(BodyOf(exchange))).Should().Be("The answer is 42.",
"thinking is not a reply and never reaches the body");
}
finally
{
await exchange.DisposeAsync();
}
}
[Fact]
public async Task Body_InsideTransacted_IsRefused()
{
var provider = new StreamingFakeProvider(PlainAnswer());
await using var host = await HostAsync(provider, Lookup(), transacted: true, options: "");
IExchange? exchange = null;
var thrown = await Record.ExceptionAsync(async () => exchange = await host.SendAsync("direct:agent", "What is the answer?"));
var failure = thrown ?? exchange?.Exception;
if (exchange is not null) await exchange.DisposeAsync();
failure.Should().NotBeNull(
"the run would happen after the block committed, its tools outside the transaction the route declared");
failure!.ToString().Should().Contain(".Transacted()", "the message says what the placement is wrong about")
.And.Contain("stream=calls", "and names the mode that stays inside the transaction");
provider.StreamCalls.Should().Be(0);
}
[Fact]
public async Task Body_ReadAfterTheExchangeEnded_Fails()
{
var provider = new StreamingFakeProvider(PlainAnswer());
await using var host = await HostAsync(provider, Lookup(), options: "");
var exchange = await host.SendAsync("direct:agent", "What is the answer?");
var body = BodyOf(exchange);
await exchange.DisposeAsync();
var thrown = await Record.ExceptionAsync(() => ReadAsync(body));
thrown.Should().BeOfType("the run reads the exchange's resources, which are gone");
provider.StreamCalls.Should().Be(0, "nothing ran for a body nobody can read");
}
[Fact]
public async Task Body_ReadTwice_Fails()
{
await using var host = await HostAsync(new StreamingFakeProvider(PlainAnswer()), Lookup(), options: "");
var exchange = await host.SendAsync("direct:agent", "What is the answer?");
try
{
var body = BodyOf(exchange);
await ReadAsync(body);
var thrown = await Record.ExceptionAsync(() => ReadAsync(body));
thrown.Should().BeOfType("one read is one agent run; a second read would run it again");
}
finally
{
await exchange.DisposeAsync();
}
}
[Fact]
public async Task Body_ThroughRequestBody_IsRefused()
{
await using var host = await HostAsync(new StreamingFakeProvider(PlainAnswer()), Lookup(), options: "");
var thrown = await Record.ExceptionAsync(() => host.ProducerTemplate.RequestBody("direct:agent", "What is the answer?"));
thrown.Should().BeOfType(
"RequestBody ends the exchange before it returns, and this body reads the exchange's resources");
thrown!.Message.Should().Contain("RequestAsync");
}
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
[Fact]
public async Task Body_OverHttp_IsServerSentEvents_WithTheSummaryLast()
{
var port = FreePort();
var provider = new StreamingFakeProvider(ToolThenAnswer());
var tool = Lookup();
await using var host = LiveLlmHost.Build(httpHosting: new HttpHostingOptions(), httpPort: port)
.AddFactory("demo", Factory(provider));
await host.StartAsync(tool, r => r.From($"http:127.0.0.1:{port}/agent?inOut=true")
.To("llm://demo?stream=body&tools=lookup&maxIterations=4"));
using var http = new HttpClient();
using var response = await http.PostAsync($"http://127.0.0.1:{port}/agent", new StringContent("What is the answer?"));
var text = await response.Content.ReadAsStringAsync();
response.Content.Headers.ContentType!.MediaType.Should().Be("text/event-stream",
"the reply is a stream of events, whatever type the request carried");
var data = text.Split('\n')
.Where(l => l.StartsWith("data: ", StringComparison.Ordinal) && !l.Contains("llm.tool.iterations"))
.Select(l => l["data: ".Length..]);
string.Concat(data).Should().Be("The answer is 42.");
text.Should().Contain("event: done", "the summary of the run comes last, after the text");
text.Should().Contain("\"llm.tool.iterations\":2",
"two model calls, the tool call and the answer, and the summary carries numbers as JSON numbers");
tool.CapturedInputs.Should().ContainSingle();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LiveProviderTests.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/tests/redb.Route.Tests.Llm/LiveProviderTests.cs
----
using System.Net;
using System.Net.Http;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// Live integration tests against real free-tier OpenAI-compatible providers.
///
/// Each test is gated by an environment variable. If the key is missing the test
/// is skipped (no failure) so CI runs stay green without secrets. On 429
/// (rate-limit) responses each call retries up to 3 times with exponential
/// backoff that respects Retry-After.
///
///
/// Local setup (any subset works — others auto-skip):
///
/// $env:REDB_LLM_GITHUB_KEY = "ghp_..." # GitHub PAT — GitHub Models, free
/// $env:REDB_LLM_GROQ_KEY = "gsk_..." # console.groq.com
/// $env:REDB_LLM_GROK_KEY = "xai-..." # console.x.ai (xAI Grok)
/// $env:REDB_LLM_CEREBRAS_KEY = "csk-..." # cloud.cerebras.ai
/// $env:REDB_LLM_OPENROUTER_KEY = "sk-or-..." # openrouter.ai (:free models)
/// $env:REDB_LLM_GEMINI_KEY = "AIza..." # aistudio.google.com
/// $env:REDB_LLM_MISTRAL_KEY = "..." # console.mistral.ai
///
/// Run only the live suite:
/// dotnet test --filter "Category=LiveLlm"
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")] // disables intra-class parallelism — important for 429-prone free tiers
public sealed class LiveProviderTests
{
private static readonly HttpClient SharedHttp = new() { Timeout = TimeSpan.FromSeconds(60) };
private static LlmConnectionFactory MakeFactory(string name, string provider, string modelId, string envVar)
=> new()
{
Name = name,
Provider = provider,
ModelId = modelId,
ApiKey = Environment.GetEnvironmentVariable(envVar),
Temperature = 0.0,
MaxTokens = 64
};
private static async Task CompleteWithRetryAsync(OpenAiProvider provider, LlmRequest request)
{
const int maxAttempts = 4;
for (var attempt = 1; ; attempt++)
{
try
{
return await provider.CompleteAsync(request).ConfigureAwait(false);
}
catch (HttpRequestException ex) when (attempt < maxAttempts && Is429(ex.Message))
{
// Free tiers (Gemini 15 RPM, OpenRouter shared upstream) need long backoff.
var delay = TimeSpan.FromSeconds(5 * attempt);
await Task.Delay(delay).ConfigureAwait(false);
}
}
}
private static bool Is429(string message) =>
message.Contains("429") || message.Contains("Too Many Requests", StringComparison.OrdinalIgnoreCase);
// ===================================================================
// Reusable scenarios — each takes a factory and runs a real call.
// ===================================================================
private static async Task SmokeAsync(LlmConnectionFactory factory)
{
var provider = new OpenAiProvider(factory, SharedHttp);
var request = new LlmRequest
{
SystemPrompt = "You are a calculator. Answer with the number only, no words.",
Messages = [LlmMessage.User("What is 2+2?")],
Temperature = 0.0,
// Reasoning models (Cerebras gpt-oss-120b, zai-glm-4.7) emit a long
// chain-of-thought before the visible answer; small caps truncate it.
MaxTokens = 512
};
var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false);
response.Content.Should().NotBeEmpty();
var text = response.Content.OfType().FirstOrDefault()?.Text ?? "";
text.Should().NotBeNullOrWhiteSpace($"{factory.Provider} returned empty content");
text.Should().Contain("4");
}
// Note for maintainers: this suite is English-only so it is portable across
// contributors and CI runners regardless of locale. If you want to verify
// a particular non-English language (e.g. Russian, Chinese, Arabic) for
// your own deployment, run a private fork of this test with a localized
// prompt and a script-specific assertion.
private static async Task NonAsciiAsync(LlmConnectionFactory factory)
{
var provider = new OpenAiProvider(factory, SharedHttp);
var request = new LlmRequest
{
SystemPrompt =
"Reply with EXACTLY one short sentence in plain English. " +
"Then on a new line write the same sentence using only é, è, à, ü, ö, ß accents " +
"(use any reasonable European spelling).",
Messages = [LlmMessage.User("Say hello.")],
Temperature = 0.0,
MaxTokens = 64
};
var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false);
var text = response.Content.OfType().FirstOrDefault()?.Text ?? "";
text.Should().NotBeNullOrWhiteSpace();
// Sanity check: non-empty multi-line UTF-8 round-trip.
text.Length.Should().BeGreaterThan(2, $"{factory.Provider} returned suspiciously short text: '{text}'");
}
private static async Task ToolUseAsync(LlmConnectionFactory factory)
{
var provider = new OpenAiProvider(factory, SharedHttp);
var request = new LlmRequest
{
SystemPrompt =
"You MUST call the get_weather tool with city='Berlin'. Do not answer from memory.",
Messages = [LlmMessage.User("What is the weather in Berlin?")],
Temperature = 0.0,
MaxTokens = 256,
Tools =
[
new LlmToolCapability
{
Name = "get_weather",
Description = "Returns the current weather for a given city.",
InputSchema = """
{
"type": "object",
"properties": { "city": { "type": "string" } },
"required": ["city"]
}
"""
}
]
};
var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false);
var toolUses = response.Content.OfType().ToList();
var texts = response.Content.OfType().ToList();
(toolUses.Count > 0 || texts.Count > 0).Should().BeTrue(
$"{factory.Provider} returned no content blocks at all");
if (toolUses.Count > 0)
{
toolUses[0].Name.Should().Be("get_weather");
toolUses[0].InputJson.Should().Contain("Berlin");
}
}
private static async Task UsageReportedAsync(LlmConnectionFactory factory)
{
var provider = new OpenAiProvider(factory, SharedHttp);
var request = new LlmRequest
{
Messages = [LlmMessage.User("Say 'ok' and nothing else.")],
Temperature = 0.0,
MaxTokens = 8
};
var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false);
response.Usage.InputTokens.Should().BeGreaterThan(0, $"{factory.Provider} should report input tokens");
response.Usage.OutputTokens.Should().BeGreaterThan(0, $"{factory.Provider} should report output tokens");
}
private static async Task StopReasonAsync(LlmConnectionFactory factory)
{
var provider = new OpenAiProvider(factory, SharedHttp);
var request = new LlmRequest
{
Messages = [LlmMessage.User("Reply with the single word: ok")],
Temperature = 0.0,
MaxTokens = 8
};
var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false);
response.RawStopReason.Should().NotBeNullOrEmpty();
}
// ===================================================================
// Per-provider tests. One row per (provider, scenario) — when the env
// var is missing the row is skipped.
// ===================================================================
// ---------- GitHub Models ----------
[EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_Smoke() => SmokeAsync(GH());
[EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_NonAscii() => NonAsciiAsync(GH());
[EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_ToolUse() => ToolUseAsync(GH());
[EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_Usage() => UsageReportedAsync(GH());
[EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_Stop() => StopReasonAsync(GH());
private static LlmConnectionFactory GH() => MakeFactory("github", "github-models", "gpt-4o-mini", "REDB_LLM_GITHUB_KEY");
// ---------- Groq ----------
[EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_Smoke() => SmokeAsync(Groq());
[EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_NonAscii() => NonAsciiAsync(Groq());
[EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_ToolUse() => ToolUseAsync(Groq());
[EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_Usage() => UsageReportedAsync(Groq());
[EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_Stop() => StopReasonAsync(Groq());
private static LlmConnectionFactory Groq() => MakeFactory("groq", "groq", "llama-3.3-70b-versatile", "REDB_LLM_GROQ_KEY");
// ---------- xAI Grok ----------
[EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_Smoke() => SmokeAsync(Grok());
[EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_NonAscii() => NonAsciiAsync(Grok());
[EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_ToolUse() => ToolUseAsync(Grok());
[EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_Usage() => UsageReportedAsync(Grok());
[EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_Stop() => StopReasonAsync(Grok());
private static LlmConnectionFactory Grok() => MakeFactory("grok", "grok", "grok-3-mini", "REDB_LLM_GROK_KEY");
// ---------- Cerebras (current free models: gpt-oss-120b, zai-glm-4.7) ----------
[EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_Smoke() => SmokeAsync(Cerebras());
[EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_NonAscii() => NonAsciiAsync(Cerebras());
[EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_ToolUse() => ToolUseAsync(Cerebras());
[EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_Usage() => UsageReportedAsync(Cerebras());
private static LlmConnectionFactory Cerebras() => MakeFactory("cerebras", "cerebras", "gpt-oss-120b", "REDB_LLM_CEREBRAS_KEY");
// ---------- OpenRouter (use Gemma — most stable :free upstream) ----------
[EnvFact("REDB_LLM_OPENROUTER_KEY")] public Task OpenRouter_Smoke() => SmokeAsync(OR());
[EnvFact("REDB_LLM_OPENROUTER_KEY")] public Task OpenRouter_NonAscii() => NonAsciiAsync(OR());
[EnvFact("REDB_LLM_OPENROUTER_KEY")] public Task OpenRouter_ToolUse() => ToolUseAsync(OR());
private static LlmConnectionFactory OR() => MakeFactory("openrouter", "openrouter",
"meta-llama/llama-3.3-70b-instruct:free", "REDB_LLM_OPENROUTER_KEY");
// ---------- Google Gemini (OpenAI-compat) ----------
[EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_Smoke() => SmokeAsync(Gemini());
[EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_NonAscii() => NonAsciiAsync(Gemini());
[EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_ToolUse() => ToolUseAsync(Gemini());
[EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_Usage() => UsageReportedAsync(Gemini());
private static LlmConnectionFactory Gemini() => MakeFactory("gemini", "gemini", "gemini-2.0-flash", "REDB_LLM_GEMINI_KEY");
// ---------- Mistral ----------
[EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_Smoke() => SmokeAsync(Mistral());
[EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_NonAscii() => NonAsciiAsync(Mistral());
[EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_ToolUse() => ToolUseAsync(Mistral());
[EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_Usage() => UsageReportedAsync(Mistral());
private static LlmConnectionFactory Mistral() => MakeFactory("mistral", "mistral", "mistral-small-latest", "REDB_LLM_MISTRAL_KEY");
}
Path: redb-route/tests/redb.Route.Tests.Llm/LiveStreamingTests.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/tests/redb.Route.Tests.Llm/LiveStreamingTests.cs
----
using System.Net.Http;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// Live integration tests for provider-level streaming ().
/// Each test is env-gated and auto-skips when the corresponding key is missing.
///
/// What we assert (per provider):
///
/// - more than one chunk arrives — proves the wire is truly streaming, not a single
/// buffered response delivered in one frame;
/// - at least one chunk carries a text delta;
/// - the concatenated answer contains the expected substring ("4" for "2+2");
/// - some chunk reports a non-null StopReason (the terminal frame).
///
///
///
[Trait("Category", "LiveLlm")]
[Collection("LiveLlmSerial")]
public sealed class LiveStreamingTests
{
private static readonly HttpClient SharedHttp = new() { Timeout = TimeSpan.FromSeconds(60) };
private static LlmConnectionFactory MakeFactory(string name, string provider, string modelId, string envVar)
=> new()
{
Name = name,
Provider = provider,
ModelId = modelId,
ApiKey = Environment.GetEnvironmentVariable(envVar),
Temperature = 0.0,
MaxTokens = 64
};
private static LlmRequest MathRequest() => new()
{
SystemPrompt = "You are a calculator. Answer with the number only, no words.",
Messages = [LlmMessage.User("What is 2+2?")],
Temperature = 0.0,
MaxTokens = 512
};
private sealed record StreamSummary(
int ChunkCount,
int TextDeltaCount,
string Text,
bool SawStopReason,
LlmUsage? LastUsage);
private static async Task CollectAsync(ILlmProvider provider, LlmRequest request)
{
const int maxAttempts = 4;
for (var attempt = 1; ; attempt++)
{
try
{
return await CollectOnceAsync(provider, request).ConfigureAwait(false);
}
catch (HttpRequestException ex) when (attempt < maxAttempts && Is429(ex.Message))
{
await Task.Delay(TimeSpan.FromSeconds(5 * attempt)).ConfigureAwait(false);
}
}
}
private static async Task CollectOnceAsync(ILlmProvider provider, LlmRequest request)
{
var chunkCount = 0;
var textCount = 0;
var sb = new System.Text.StringBuilder();
var sawStop = false;
LlmUsage? lastUsage = null;
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60));
await foreach (var chunk in provider.StreamAsync(request, cts.Token).ConfigureAwait(false))
{
chunkCount++;
foreach (var block in chunk.Content)
{
if (block is LlmTextBlock text)
{
textCount++;
sb.Append(text.Text);
}
}
if (chunk.StopReason is not null) sawStop = true;
if (chunk.Usage is not null) lastUsage = chunk.Usage;
}
return new StreamSummary(chunkCount, textCount, sb.ToString(), sawStop, lastUsage);
}
private static bool Is429(string message) =>
message.Contains("429") || message.Contains("Too Many Requests", StringComparison.OrdinalIgnoreCase);
private static async Task SmokeStreamAsync(ILlmProvider provider)
{
var summary = await CollectAsync(provider, MathRequest()).ConfigureAwait(false);
summary.ChunkCount.Should().BeGreaterThan(1,
$"{provider.ProviderId}: streaming must yield more than one chunk, got {summary.ChunkCount}");
summary.TextDeltaCount.Should().BeGreaterThan(0,
$"{provider.ProviderId}: at least one text delta expected");
summary.Text.Should().Contain("4",
$"{provider.ProviderId}: accumulated text should contain the answer, got '{summary.Text}'");
summary.SawStopReason.Should().BeTrue(
$"{provider.ProviderId}: terminal chunk must carry a StopReason");
}
// ---------- Anthropic Claude Haiku (true SSE) ----------
[EnvFact("REDB_LLM_ANT_API03_KEY")]
public Task Anthropic_ClaudeHaiku_Stream() => SmokeStreamAsync(
new AnthropicProvider(
new LlmConnectionFactory
{
Name = "anthropic-haiku",
Provider = "anthropic",
ModelId = "claude-haiku-4-5",
ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"),
Temperature = 0.0,
MaxTokens = 64
},
SharedHttp));
// ---------- Groq (OpenAI-compatible SSE) ----------
[EnvFact("REDB_LLM_GROQ_KEY")]
public Task Groq_Stream() => SmokeStreamAsync(
new OpenAiProvider(
MakeFactory("groq", "groq", "llama-3.3-70b-versatile", "REDB_LLM_GROQ_KEY"),
SharedHttp));
// ---------- Cerebras ----------
[EnvFact("REDB_LLM_CEREBRAS_KEY")]
public Task Cerebras_Stream() => SmokeStreamAsync(
new OpenAiProvider(
MakeFactory("cerebras", "cerebras", "gpt-oss-120b", "REDB_LLM_CEREBRAS_KEY"),
SharedHttp));
// ---------- Google Gemini (OpenAI-compat) ----------
[EnvFact("REDB_LLM_GEMINI_KEY")]
public Task Gemini_Stream() => SmokeStreamAsync(
new OpenAiProvider(
MakeFactory("gemini", "gemini", "gemini-2.0-flash", "REDB_LLM_GEMINI_KEY"),
SharedHttp));
// ---------- Mistral ----------
[EnvFact("REDB_LLM_MISTRAL_KEY")]
public Task Mistral_Stream() => SmokeStreamAsync(
new OpenAiProvider(
MakeFactory("mistral", "mistral", "mistral-small-latest", "REDB_LLM_MISTRAL_KEY"),
SharedHttp));
// ---------- OpenRouter ----------
[EnvFact("REDB_LLM_OPENROUTER_KEY")]
public Task OpenRouter_Stream() => SmokeStreamAsync(
new OpenAiProvider(
MakeFactory("openrouter", "openrouter",
"meta-llama/llama-3.3-70b-instruct:free", "REDB_LLM_OPENROUTER_KEY"),
SharedHttp));
}
Path: redb-route/tests/redb.Route.Tests.Llm/LiveTranscriptionTests.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/tests/redb.Route.Tests.Llm/LiveTranscriptionTests.cs
----
using System.Text;
using AwesomeAssertions;
using redb.Route.Llm;
using redb.Route.Llm.Providers;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// A live check of the transcription transport against a real server.
///
/// The stub tests () prove the shape of the request
/// as the transport's author meant it. What they do not prove is that a real server accepts EXACTLY
/// that shape: the form field names, the file name, the content type and how it
/// reads response_format. That is exactly where multipart transports break, and a stub
/// cannot show it at all.
///
/// Turned on by the variable REDB_STT_BASE_URL, for example
/// http://127.0.0.1:8083/v1/ (whisper.cpp server, Speaches, LM Studio or a local speech-to-text
/// container). Unset, the fact is skipped, like the other live ones.
///
public sealed class LiveTranscriptionTests
{
private const string BaseUrlVariable = "REDB_STT_BASE_URL";
private const string ModelVariable = "REDB_STT_MODEL";
private static OpenAiTranscriptionProvider Provider()
{
var baseUrl = Environment.GetEnvironmentVariable(BaseUrlVariable)!;
return OpenAiTranscriptionProvider.Create(new LlmConnectionFactory
{
Name = "live-stt",
Provider = "whisper",
ModelId = Environment.GetEnvironmentVariable(ModelVariable) ?? "medium",
BaseUrl = new Uri(baseUrl),
ApiKey = Environment.GetEnvironmentVariable("REDB_STT_KEY"),
RequestTimeoutMs = 300_000,
});
}
///
/// A valid WAV: one second of tone, one second of silence. There is no speech in it, and here that is a
/// convenience, not a problem: the transport is checked, not the model's hearing.
///
private static byte[] ToneWav(int seconds = 2, int rate = 16000, double hz = 220)
{
var samples = rate * seconds;
var data = new byte[samples * 2];
for (var i = 0; i < samples; i++)
{
short value = i < samples / 2
? (short)(12000 * Math.Sin(2 * Math.PI * hz * i / rate))
: (short)0;
data[i * 2] = (byte)(value & 0xFF);
data[i * 2 + 1] = (byte)((value >> 8) & 0xFF);
}
using var stream = new MemoryStream();
using var writer = new BinaryWriter(stream, Encoding.ASCII, leaveOpen: true);
writer.Write("RIFF"u8.ToArray());
writer.Write(36 + data.Length);
writer.Write("WAVE"u8.ToArray());
writer.Write("fmt "u8.ToArray());
writer.Write(16); // format block size
writer.Write((short)1); // PCM
writer.Write((short)1); // mono
writer.Write(rate);
writer.Write(rate * 2); // bytes per second
writer.Write((short)2); // block alignment
writer.Write((short)16); // bits per sample
writer.Write("data"u8.ToArray());
writer.Write(data.Length);
writer.Write(data);
writer.Flush();
return stream.ToArray();
}
[EnvFact(BaseUrlVariable)]
public async Task A_live_server_accepts_our_upload_form()
{
var provider = Provider();
var result = await provider.TranscribeAsync(
new TranscriptionRequest(ToneWav(), "probe.wav", Language: "ru"));
// The text may be anything, empty included: the server may hear no speech in a tone.
// What is proven is something else: the request arrived, was understood and parsed without an exception.
result.Text.Should().NotBeNull();
provider.ModelId.Should().NotBeNullOrWhiteSpace();
}
///
/// A recording without speech must come back EMPTY. Whisper does not stay silent on silence, it
/// makes things up: on the very first run of the synthetic tone it produced a stock phrase
/// (a typical hallucination learned from video subtitles). For a route this is not a curiosity:
/// the invented phrase would go to the model as the words of a person.
///
/// The server itself suppresses it (the no_speech_prob threshold), not the transport, so
/// the fact is live: it checks the stand, not our code.
///
[EnvFact(BaseUrlVariable)]
public async Task A_live_server_does_not_invent_words_for_a_recording_without_speech()
{
var result = await Provider().TranscribeAsync(
new TranscriptionRequest(ToneWav(), "probe.wav", Language: "ru"));
result.Text.Should().BeEmpty(
"a recording without speech must come back as an empty string: an invented phrase would go "
+ "into the conversation as the person's words");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmAuditPersistenceTests.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/tests/redb.Route.Tests.Llm/LlmAuditPersistenceTests.cs
----
using redb.Route.Llm.Engine.Storage;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// Producer-level coverage for the audit-extension wiring (3.1.1):
/// ?user= + ?audit= URI options + llm.user.id /
/// llm.audit.<name> headers reach the conversation store
/// stamped on every persisted row of the run. Backed by
/// — no DB required.
///
public sealed class LlmAuditPersistenceTests
{
private static (RouteContext ctx, LlmEndpoint endpoint, InMemoryConversationStore store)
Build(FakeProvider provider, string uri)
{
var ctx = new RouteContext();
var component = new LlmComponent();
ctx.AddComponent(component);
ctx.AddToRegistry("fake", new LlmConnectionFactory
{
Name = "fake",
Provider = "fake",
ModelId = provider.ModelId,
PrebuiltProvider = provider
});
var store = new InMemoryConversationStore();
ctx.AddService(typeof(IAgentEngine), new AgentEngine(
logger: null,
producerTemplate: null,
observer: null,
budget: null,
approval: null,
redaction: null,
shadow: null,
conversation: store,
idempotency: null,
approvalStore: null));
var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(uri));
return (ctx, endpoint, store);
}
private static async Task> RunAsync(string uri, Action? configureIn = null)
{
var fake = new FakeProvider().EnqueueText("ok", tokensIn: 1, tokensOut: 1);
var (_, endpoint, store) = Build(fake, uri);
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var msg = new Message("hi");
msg.Headers[LlmHeaders.ConversationId] = "c-test";
configureIn?.Invoke(msg);
await producer.Process(new Exchange(msg));
return await store.LoadTreeAsync("c-test");
}
[Fact]
public async Task User_LiteralOption_StampedOnEveryRow()
{
var rows = await RunAsync("llm://fake?user=system&conversation=header");
rows.Should().NotBeEmpty();
rows.Select(r => r.Meta.UserId).Should().AllBeEquivalentTo("system");
}
[Fact]
public async Task User_HeaderExpression_ResolvesAtRunTime()
{
var encoded = "%24%7Bheader.X-User-Id%7D"; // ${header.X-User-Id}
var rows = await RunAsync(
$"llm://fake?user={encoded}&conversation=header",
m => m.Headers["X-User-Id"] = "alice@example.com");
rows.Select(r => r.Meta.UserId).Should().AllBeEquivalentTo("alice@example.com");
}
[Fact]
public async Task User_HeaderFallback_FromLlmUserIdHeader()
{
var rows = await RunAsync(
"llm://fake?conversation=header",
m => m.Headers[LlmHeaders.UserId] = "bob");
rows.Select(r => r.Meta.UserId).Should().AllBeEquivalentTo("bob");
}
[Fact]
public async Task Audit_OptionCsv_IsStampedOnEveryRow()
{
var rows = await RunAsync(
"llm://fake?conversation=header&audit=tier%3Dgold%2Cbucket%3DA");
rows.Should().NotBeEmpty();
foreach (var r in rows)
{
r.Meta.AuditTags.Should().NotBeNull();
r.Meta.AuditTags!["tier"].Should().Be("gold");
r.Meta.AuditTags!["bucket"].Should().Be("A");
}
}
[Fact]
public async Task Audit_HeaderTags_AreMergedAndWinOnCollision()
{
var rows = await RunAsync(
"llm://fake?conversation=header&audit=tier%3Dgold%2Cbucket%3DA",
m =>
{
m.Headers["llm.audit.tier"] = "platinum"; // overrides option-side "gold"
m.Headers["llm.audit.region"] = "eu-west"; // adds new key
});
var tags = rows[0].Meta.AuditTags!;
tags["tier"].Should().Be("platinum");
tags["bucket"].Should().Be("A");
tags["region"].Should().Be("eu-west");
}
[Fact]
public async Task PromptTemplate_NameAndVersion_AreStampedOnEveryRow()
{
var rows = await RunAsync(
"llm://fake?conversation=header&promptTemplateName=triage&promptTemplateVersion=v3");
rows.Should().NotBeEmpty();
rows.Select(r => r.Meta.PromptTemplateName).Should().AllBeEquivalentTo("triage");
rows.Select(r => r.Meta.PromptTemplateVersion).Should().AllBeEquivalentTo("v3");
}
[Fact]
public async Task User_OptionWins_OverHeaderFallback()
{
var rows = await RunAsync(
"llm://fake?conversation=header&user=system",
m => m.Headers[LlmHeaders.UserId] = "ignored");
rows.Select(r => r.Meta.UserId).Should().AllBeEquivalentTo("system");
}
[Fact]
public async Task NoUserNoAudit_LeavesMetaNull()
{
var rows = await RunAsync("llm://fake?conversation=header");
rows.Should().NotBeEmpty();
rows.Should().OnlyContain(r => r.Meta.UserId == null);
rows.Should().OnlyContain(r => r.Meta.AuditTags == null);
}
[Fact]
public async Task FactoryName_IsStampedOnEveryRow()
{
// Build helper registers the factory under name "fake".
var rows = await RunAsync("llm://fake?conversation=header");
rows.Should().NotBeEmpty();
rows.Select(r => r.Meta.FactoryName).Should().AllBeEquivalentTo("fake");
}
[Fact]
public async Task ProviderResponseId_AndLatency_AreStampedOnAssistantRow()
{
var rows = await RunAsync("llm://fake?conversation=header");
var assistant = rows.Should().ContainSingle(r => r.Message.Role == "assistant").Subject;
// FakeProvider sets ProviderResponseId via EnqueueText defaults; if null, latency must still be present.
assistant.Meta.LatencyMs.Should().NotBeNull();
assistant.Meta.LatencyMs!.Value.Should().BeGreaterThanOrEqualTo(0);
}
[Fact]
public async Task ProviderResponseId_RoundTripsFromProviderResponse()
{
// Drive the producer with a hand-built LlmResponse so we can pin a known id.
var fake = new FakeProvider();
fake.Enqueue(new LlmResponse
{
Content = [new LlmTextBlock("ok")],
StopReason = LlmStopReason.EndTurn,
Usage = new LlmUsage(1, 1),
ProviderResponseId = "resp_abc123"
});
var (_, endpoint, store) = Build(fake, "llm://fake?conversation=header");
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var msg = new Message("hi");
msg.Headers[LlmHeaders.ConversationId] = "c-rid";
await producer.Process(new Exchange(msg));
var rows = await store.LoadTreeAsync("c-rid");
var assistant = rows.Should().ContainSingle(r => r.Message.Role == "assistant").Subject;
assistant.Meta.ProviderResponseId.Should().Be("resp_abc123");
}
[Fact]
public async Task LatencyAndResponseId_AreNullOnNonAssistantRows()
{
var rows = await RunAsync("llm://fake?conversation=header");
rows.Where(r => r.Message.Role != "assistant")
.Should().OnlyContain(r => r.Meta.LatencyMs == null);
rows.Where(r => r.Message.Role != "assistant")
.Should().OnlyContain(r => r.Meta.ProviderResponseId == null);
}
[Fact]
public async Task RetryCount_NullByDefault_OnFirstDelivery()
{
var rows = await RunAsync("llm://fake?conversation=header");
rows.Should().NotBeEmpty();
rows.Should().OnlyContain(r => r.Meta.RetryCount == null);
}
[Fact]
public async Task RetryCount_FromRetryAttemptProperty_StampedOnEveryRow()
{
var fake = new FakeProvider().EnqueueText("ok", tokensIn: 1, tokensOut: 1);
var (_, endpoint, store) = Build(fake, "llm://fake?conversation=header");
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var msg = new Message("hi");
msg.Headers[LlmHeaders.ConversationId] = "c-retry-prop";
var exchange = new Exchange(msg);
// RetryProcessor.cs writes this property each retry attempt.
exchange.Properties["RetryAttempt"] = 2;
await producer.Process(exchange);
var rows = await store.LoadTreeAsync("c-retry-prop");
rows.Should().NotBeEmpty();
rows.Select(r => r.Meta.RetryCount).Should().AllBeEquivalentTo(2);
}
[Fact]
public async Task RetryCount_FallsBackTo_CamelRedeliveryCounter()
{
var fake = new FakeProvider().EnqueueText("ok", tokensIn: 1, tokensOut: 1);
var (_, endpoint, store) = Build(fake, "llm://fake?conversation=header");
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var msg = new Message("hi");
msg.Headers[LlmHeaders.ConversationId] = "c-retry-hdr";
// OnExceptionProcessor stamps this header on the inbound message.
msg.Headers["CamelRedeliveryCounter"] = 3;
await producer.Process(new Exchange(msg));
var rows = await store.LoadTreeAsync("c-retry-hdr");
rows.Should().NotBeEmpty();
rows.Select(r => r.Meta.RetryCount).Should().AllBeEquivalentTo(3);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmBuilderTests.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/tests/redb.Route.Tests.Llm/LlmBuilderTests.cs
----
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm;
public sealed class LlmBuilderTests
{
[Fact]
public void Factory_StartsWithLlmScheme()
{
LlmDsl.Factory("claude").AsUri().Should().StartWith("llm://claude");
}
[Fact]
public void NullFactory_Throws()
{
var act = () => LlmDsl.Factory(null!);
act.Should().Throw();
}
[Fact]
public void EmptyFactory_Throws()
{
var act = () => LlmDsl.Factory(" ");
act.Should().Throw();
}
[Fact]
public void Temperature_SetsParam()
{
LlmDsl.Factory("c").Temperature(0.25).AsUri().Should().Contain("temperature=0.25");
}
[Fact]
public void MaxTokens_SetsParam()
{
LlmDsl.Factory("c").MaxTokens(1024).AsUri().Should().Contain("maxTokens=1024");
}
[Fact]
public void TopP_SetsParam()
{
LlmDsl.Factory("c").TopP(0.9).AsUri().Should().Contain("topP=0.9");
}
[Fact]
public void SystemPromptRef_SetsParam()
{
LlmDsl.Factory("c").SystemPromptRef("translate-en").AsUri().Should().Contain("systemPromptRef=translate-en");
}
[Fact]
public void Conversation_FromHeader_SetsParam()
{
LlmDsl.Factory("c").ConversationFromHeader().AsUri().Should().Contain("conversation=header");
}
[Fact]
public void Conversation_FromRoute_SetsParam()
{
LlmDsl.Factory("c").ConversationFromRoute().AsUri().Should().Contain("conversation=property");
}
[Fact]
public void Stream_SetsTheMode()
{
LlmDsl.Factory("c").Stream(LlmStreamMode.Calls).AsUri().Should().Contain("stream=calls");
LlmDsl.Factory("c").Stream(LlmStreamMode.Body).AsUri().Should().Contain("stream=body");
LlmDsl.Factory("c").AsUri().Should().NotContain("stream", "no streaming is the absence of the option");
}
[Fact]
public void Schedule_SetsParam()
{
LlmDsl.Factory("c").Schedule("0 0/5 * * * ?").AsUri()
.Should().Contain("schedule=");
}
[Fact]
public void MaxIterations_SetsParam()
{
LlmDsl.Factory("c").MaxIterations(4).AsUri().Should().Contain("maxIterations=4");
}
[Fact]
public void CacheSystemPrompt_SetsParam_AndBindsToTheOption()
{
LlmDsl.Factory("c").CacheSystemPrompt().AsUri().Should().Contain("cacheSystemPrompt=true");
// The URI is only half the contract: the parameter has to land on the option the
// producer reads, or the flag would be a string nobody acts on.
var options = new LlmEndpointOptions();
options.BindFromUri(EndpointUriParser.Parse(
LlmDsl.Factory("c").CacheSystemPrompt().AsUri()).RawParameters);
options.CacheSystemPrompt.Should().BeTrue();
}
[Fact]
public void CacheSystemPrompt_IsAbsentUnlessAskedFor()
{
// Off by default and absent from the URI entirely: an address that says nothing about
// caching must behave exactly as it did before the option existed.
LlmDsl.Factory("c").MaxIterations(4).AsUri()
.Should().NotContain("cacheSystemPrompt");
new LlmEndpointOptions().CacheSystemPrompt.Should().BeFalse();
}
[Fact]
public void Combined_ProducesMultipleParams()
{
var uri = LlmDsl.Factory("claude")
.Temperature(0.0)
.MaxTokens(512)
.ConversationFromHeader()
.Stream(LlmStreamMode.Body)
.AsUri();
uri.Should().Contain("temperature=0");
uri.Should().Contain("maxTokens=512");
uri.Should().Contain("conversation=header");
uri.Should().Contain("stream=body");
}
[Fact]
public void ImplicitConversion_ProducesValidEndpointUri()
{
EndpointUri uri = LlmDsl.Factory("claude").Temperature(0.1).MaxTokens(64);
uri.Scheme.Should().Be("llm");
uri.Path.Should().Be("claude");
}
[Fact]
public void User_LiteralExpression_SetsParam()
{
LlmDsl.Factory("c").User("system").AsUri().Should().Contain("user=system");
}
[Fact]
public void User_HeaderExpression_IsUrlEncodedOnce()
{
var uri = LlmDsl.Factory("c").User("${header.X-User-Id}").AsUri();
// ${header.X-User-Id} → URL-encoded values can be %24/%24 etc; just assert the key/value survive a parse.
var parsed = EndpointUriParser.Parse(uri);
parsed.RawParameters["user"].Should().Be("${header.X-User-Id}");
}
[Fact]
public void Audit_SinglePair_SetsParam()
{
var uri = LlmDsl.Factory("c").Audit("tier", "gold").AsUri();
var parsed = EndpointUriParser.Parse(uri);
parsed.RawParameters["audit"].Should().Be("tier=gold");
}
[Fact]
public void Audit_MultiplePairs_JoinedWithComma()
{
var uri = LlmDsl.Factory("c").Audit("tier", "gold").Audit("bucket", "A").AsUri();
var parsed = EndpointUriParser.Parse(uri);
parsed.RawParameters["audit"].Should().Be("tier=gold,bucket=A");
}
[Fact]
public void Audit_ValueWithCommaAndEquals_RoundTripsAfterUrlDecode()
{
var uri = LlmDsl.Factory("c").Audit("expr", "a=1,b=2").AsUri();
var parsed = EndpointUriParser.Parse(uri);
// The CSV uses URL-encoded commas/equals inside the value, so the inner comma
// does NOT split the pair — the producer's CSV parser sees "expr=a%3D1%2Cb%3D2"
// (or similar) and URL-decodes each side.
parsed.RawParameters["audit"].Should().Contain("expr=");
parsed.RawParameters["audit"].Split(',').Should().HaveCount(1);
}
[Fact]
public void Audit_NullKey_Throws()
{
var b = LlmDsl.Factory("c");
var act = () => b.Audit(null!, "v");
act.Should().Throw();
}
[Fact]
public void PromptTemplate_SetsBothParams()
{
var uri = LlmDsl.Factory("c").PromptTemplate("triage", "v3").AsUri();
uri.Should().Contain("promptTemplateName=triage");
uri.Should().Contain("promptTemplateVersion=v3");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmComponentTests.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/tests/redb.Route.Tests.Llm/LlmComponentTests.cs
----
namespace redb.Route.Tests.Llm;
public sealed class LlmComponentTests
{
[Fact]
public void Scheme_IsLlm()
{
new LlmComponent().Scheme.Should().Be("llm");
}
[Fact]
public void CreateEndpoint_ParsesPathAsFactoryName()
{
var component = new LlmComponent();
var uri = EndpointUriParser.Parse("llm://claude?temperature=0.2");
var endpoint = (LlmEndpoint)component.CreateEndpoint(uri);
endpoint.ConnectionFactoryName.Should().Be("claude");
endpoint.Uri.RawParameters["temperature"].Should().Be("0.2");
}
[Fact]
public void CreateEndpoint_FactoryNameViaQuery_Works()
{
var component = new LlmComponent();
var uri = EndpointUriParser.Parse("llm://?connectionFactory=local");
var endpoint = (LlmEndpoint)component.CreateEndpoint(uri);
endpoint.ConnectionFactoryName.Should().Be("local");
}
[Fact]
public void CreateEndpoint_NoFactoryName_Throws()
{
var component = new LlmComponent();
var uri = EndpointUriParser.Parse("llm://?temperature=0.1");
var act = () => component.CreateEndpoint(uri);
act.Should().Throw().WithMessage("*connection factory*");
}
[Fact]
public void CreateEndpoint_InvalidTemperature_Throws()
{
var component = new LlmComponent();
var uri = EndpointUriParser.Parse("llm://c?temperature=5.0");
var act = () => component.CreateEndpoint(uri);
act.Should().Throw();
}
[Fact]
public void CreateEndpoint_NullUri_Throws()
{
var component = new LlmComponent();
var act = () => component.CreateEndpoint(null!);
act.Should().Throw();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmConnectionFactoryTests.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/tests/redb.Route.Tests.Llm/LlmConnectionFactoryTests.cs
----
namespace redb.Route.Tests.Llm;
public sealed class LlmConnectionFactoryTests
{
[Fact]
public void Defaults_AreReasonable()
{
var f = new LlmConnectionFactory();
f.Provider.Should().Be("stub");
f.ModelId.Should().Be("stub-model");
f.RequestTimeoutMs.Should().Be(600_000,
"ten minutes, like the official Anthropic and OpenAI SDKs: a thinking model's non-streaming answer takes minutes");
}
[Fact]
public void Build_StubProvider_Works()
{
var f = new LlmConnectionFactory { Provider = "stub", ModelId = "x" };
var p = f.Build();
p.Should().BeOfType();
p.ProviderId.Should().Be("stub");
p.ModelId.Should().Be("x");
}
[Fact]
public void Build_AnthropicProvider_ReturnsAnthropicType()
{
// Anthropic is placeholder; ctor must succeed even though CompleteAsync isn't implemented.
var f = new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-haiku" };
var p = f.Build();
p.Should().BeOfType();
}
[Fact]
public void Build_UnknownProvider_Throws()
{
var f = new LlmConnectionFactory { Provider = "does-not-exist" };
var act = () => f.Build();
act.Should().Throw().WithMessage("*Unknown LLM provider*");
}
[Fact]
public void Build_PrebuiltProvider_TakesPrecedence()
{
var prebuilt = new StubProvider(new LlmConnectionFactory { ModelId = "x" }) { FixedReply = "pre" };
var f = new LlmConnectionFactory
{
Provider = "does-not-exist", // ignored
PrebuiltProvider = prebuilt
};
f.Build().Should().BeSameAs(prebuilt);
}
[Fact]
public void ProviderName_IsCaseInsensitive()
{
var f = new LlmConnectionFactory { Provider = "STUB" };
f.Build().Should().BeOfType();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmConsumerPromptExchangeTests.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/tests/redb.Route.Tests.Llm/LlmConsumerPromptExchangeTests.cs
----
using System.Collections.Concurrent;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// The scheduled agent (From("llm://...?schedule=...")) resolves its prompt references with the tick's
/// own exchange. A redb-backed template registry needs it to resolve a scope of that tick instead of the one
/// shared instance every concurrent tick would land on. The lookup runs inside the block that owns the
/// exchange, so a failing template releases it.
///
public sealed class LlmConsumerPromptExchangeTests
{
/// Records every lookup: the exchange it was made with and whether that exchange had a DI scope.
private sealed class RecordingTemplates(Func lookup) : IPromptTemplateRegistry
{
private readonly ConcurrentQueue<(IExchange? Exchange, bool HadScope)> _lookups = new();
public (IExchange? Exchange, bool HadScope)[] Lookups => _lookups.ToArray();
public Task GetAsync(string name, string? version = null, IExchange? exchange = null,
CancellationToken ct = default)
{
_lookups.Enqueue((exchange, exchange?.ServiceProvider is not null));
return Task.FromResult(lookup(name));
}
public Task SetAsync(PromptTemplate template, IExchange? exchange = null, CancellationToken ct = default)
=> Task.CompletedTask;
public Task> ListAsync(IExchange? exchange = null, CancellationToken ct = default)
=> Task.FromResult>([]);
}
private static LiveLlmHost Host(FakeProvider fake, IPromptTemplateRegistry templates)
{
var host = LiveLlmHost.Build();
host.AddFactory("fake", new LlmConnectionFactory
{
Name = "fake",
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
host.Context.AddService(typeof(IPromptTemplateRegistry), templates);
return host;
}
private static async Task WaitUntilAsync(Func condition)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(20);
}
[Fact]
public async Task ScheduledTick_ResolvesPromptsWithItsExchange()
{
var calls = new ConcurrentQueue<(string? SystemPrompt, string? UserText)>();
var fake = new FakeProvider
{
OnCall = (request, _) =>
{
var userText = request.Messages.LastOrDefault()?.Content.OfType().FirstOrDefault()?.Text;
calls.Enqueue((request.SystemPrompt, userText));
return Task.CompletedTask;
}
}.EnqueueText("tick!");
var templates = new RecordingTemplates(name => new PromptTemplate
{
Name = name,
Version = "1",
Body = name == "go" ? "status of order 42?" : "Reply tersely."
});
await using var host = Host(fake, templates);
await host.StartAsync(r => r.From("llm://fake?schedule=200ms&initialBodyRef=#go&systemPromptRef=#terse")
.To("mock:llm-ticks"));
var sink = host.Mock("mock:llm-ticks");
await WaitUntilAsync(() => sink.ReceivedCount > 0);
sink.ReceivedCount.Should().BeGreaterThan(0, "at least one tick has to reach the route");
var lookups = templates.Lookups;
lookups.Should().NotBeEmpty();
lookups.Should().OnlyContain(l => l.Exchange != null,
"a lookup without the tick's exchange lands every concurrent tick on one shared redb instance");
lookups.Should().OnlyContain(l => l.HadScope, "the exchange carries the tick's DI scope when the prompts resolve");
var first = calls.Should().NotBeEmpty().And.Subject.First();
first.SystemPrompt.Should().Be("Reply tersely.");
first.UserText.Should().Be("status of order 42?", "the resolved initial body is still what the model is asked");
}
[Fact]
public async Task ScheduledTick_TemplateFailure_ReleasesTheExchange()
{
var fake = new FakeProvider();
var templates = new RecordingTemplates(_ => throw new InvalidOperationException("template store is down"));
await using var host = Host(fake, templates);
await host.StartAsync(r => r.From("llm://fake?schedule=200ms&initialBodyRef=#go").To("mock:llm-ticks"));
await WaitUntilAsync(() => templates.Lookups.Length > 0);
var lookup = templates.Lookups.Should().NotBeEmpty().And.Subject.First();
lookup.Exchange.Should().NotBeNull("the prompt is resolved with the tick's exchange");
lookup.HadScope.Should().BeTrue("the exchange owned a DI scope when the lookup failed");
// The failing lookup runs inside the block that owns the exchange, so the tick's scope is released.
await WaitUntilAsync(() => lookup.Exchange!.ServiceProvider is null);
lookup.Exchange!.ServiceProvider.Should().BeNull("a failed template lookup must not leak the tick's DI scope");
fake.CallCount.Should().Be(0, "the tick failed before the model was called");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmEndpointOptionsTests.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/tests/redb.Route.Tests.Llm/LlmEndpointOptionsTests.cs
----
namespace redb.Route.Tests.Llm;
public sealed class LlmEndpointOptionsTests
{
private static LlmEndpointOptions Bind(string uriStr)
{
var uri = EndpointUriParser.Parse(uriStr);
var opts = new LlmEndpointOptions();
opts.BindFromUri(uri.RawParameters);
return opts;
}
[Fact]
public void Defaults_AreSet()
{
var opts = new LlmEndpointOptions();
opts.MaxIterations.Should().Be(8);
opts.Conversation.Should().Be("none");
opts.Stream.Should().Be(LlmStreamMode.Off);
}
[Fact]
public void BindFromUri_PullsTemperatureAndMaxTokens()
{
var opts = Bind("llm://c?temperature=0.3&maxTokens=512");
opts.Temperature.Should().Be(0.3);
opts.MaxTokens.Should().Be(512);
}
[Fact]
public void BindFromUri_PullsConversationAndStream()
{
var opts = Bind("llm://c?conversation=header&stream=calls");
opts.Conversation.Should().Be("header");
opts.Stream.Should().Be(LlmStreamMode.Calls);
}
[Fact]
public void BindFromUri_PullsSystemPromptRef()
{
var opts = Bind("llm://c?systemPromptRef=translate-en");
opts.SystemPromptRef.Should().Be("translate-en");
}
[Fact]
public void BindFromUri_PullsMaxIterations()
{
var opts = Bind("llm://c?maxIterations=3");
opts.MaxIterations.Should().Be(3);
}
[Fact]
public void Validate_NegativeIterations_Throws()
{
var opts = new LlmEndpointOptions { MaxIterations = 0 };
var act = () => opts.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_TemperatureOutOfRange_Throws()
{
var opts = new LlmEndpointOptions { Temperature = 3.0 };
var act = () => opts.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_ValidConfig_DoesNotThrow()
{
var opts = new LlmEndpointOptions { Temperature = 0.5, MaxIterations = 4 };
var act = () => opts.Validate();
act.Should().NotThrow();
}
[Fact]
public void BindFromUri_PullsUser()
{
var opts = Bind("llm://c?user=system");
opts.User.Should().Be("system");
}
[Fact]
public void BindFromUri_PullsUserHeaderExpression()
{
var opts = Bind("llm://c?user=" + System.Web.HttpUtility.UrlEncode("${header.X-User-Id}"));
opts.User.Should().Be("${header.X-User-Id}");
}
[Fact]
public void BindFromUri_PullsAuditCsv()
{
var opts = Bind("llm://c?audit=tier%3Dgold%2Cbucket%3DA");
opts.Audit.Should().Be("tier=gold,bucket=A");
}
[Fact]
public void BindFromUri_PullsPromptTemplateNameAndVersion()
{
var opts = Bind("llm://c?promptTemplateName=triage&promptTemplateVersion=v3");
opts.PromptTemplateName.Should().Be("triage");
opts.PromptTemplateVersion.Should().Be("v3");
}
// The core binder leaves an unknown name, or a value that does not convert, among the unmapped
// parameters, where nothing reads it: a typo used to drop the option without a word.
[Fact]
public void Validate_UnknownOption_IsRefused_WithTheNearestName()
{
// Refused while binding, in the core, before Validate runs.
var act = () => Bind("llm://c?tempreature=0.2");
act.Should().Throw("a misspelt option would silently run with the default")
.Which.Message.Should().Contain("tempreature").And.Contain("temperature", "the nearest option is named");
}
[Fact]
public void Validate_ValueThatDoesNotConvert_IsRefused()
{
var act = () => Bind("llm://c?maxIterations=abc");
act.Should().Throw("the option would silently keep its default")
.Which.Message.Should().Contain("maxIterations").And.Contain("abc");
}
[Fact]
public void EveryDslOption_IsAnOptionTheEndpointKnows()
{
var uri = redb.Route.Llm.Fluent.Llm.Factory("c")
.Temperature(0.2).MaxTokens(512).TopP(0.9)
.SystemPromptRef("#sys").ConversationFromHeader().Stream(LlmStreamMode.Calls)
.Schedule("30s").InitialBody("#first").MaxIterations(4)
.Budget(inputTokens: 100, outputTokens: 50, costUsd: 0.5m).CacheSystemPrompt()
.Tools("*").User("${header.userId}").Audit("tenant", "acme")
.PropagateToolHeaders("x-tenant-id").PromptTemplate("triage", "v3")
.AsUri() + "&redb=main&connectionFactory=c";
var opts = Bind(uri);
opts.UnmappedParameters.Should().BeEmpty("every option the DSL writes is one the endpoint reads");
opts.Invoking(o => o.Validate()).Should().NotThrow();
}
[Fact]
public void Bind_StreamWithoutAMode_SaysWhatEachModeDoes()
{
var act = () => Bind("llm://c?stream=true");
act.Should().Throw()
.Which.Message.Should().Contain("stream=calls").And.Contain("stream=body")
.And.Contain("inside the route", "the connector says what each mode does, not only that it exists");
}
[Fact]
public void Bind_StreamNumberThatNamesNoMode_IsRefused()
{
// A number converts into any enum; 5 names no mode, and the binding refuses it.
var act = () => Bind("llm://c?stream=5");
act.Should().Throw().Which.Message.Should().Contain("stream=5");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmEndpointTests.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/tests/redb.Route.Tests.Llm/LlmEndpointTests.cs
----
namespace redb.Route.Tests.Llm;
public sealed class LlmEndpointTests
{
private static LlmEndpoint CreateEndpoint(string uriStr)
{
var component = new LlmComponent();
var uri = EndpointUriParser.Parse(uriStr);
return (LlmEndpoint)component.CreateEndpoint(uri);
}
[Fact]
public void ConnectionFactoryName_FromPath()
{
CreateEndpoint("llm://claude").ConnectionFactoryName.Should().Be("claude");
}
[Fact]
public void CreateProducer_ReturnsLlmProducer()
{
CreateEndpoint("llm://c").CreateProducer().Should().BeOfType();
}
[Fact]
public void CreateConsumer_ReturnsLlmConsumer()
{
var ep = CreateEndpoint("llm://c");
var processor = Substitute.For();
ep.CreateConsumer(processor).Should().BeOfType();
}
[Fact]
public void Uri_PreservesSchemeAndPath()
{
var ep = CreateEndpoint("llm://my-factory?temperature=0.1");
ep.Uri.Scheme.Should().Be("llm");
ep.Uri.Path.Should().Be("my-factory");
}
[Fact]
public void Component_IsLlmComponent()
{
CreateEndpoint("llm://c").Component.Should().BeOfType();
}
[Fact]
public void Statistics_AreInitialized()
{
var ep = CreateEndpoint("llm://c");
ep.MessagesIn.Should().Be(0);
ep.MessagesOut.Should().Be(0);
ep.Errors.Should().Be(0);
ep.BytesIn.Should().Be(0);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmHttpTransportTests.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/tests/redb.Route.Tests.Llm/LlmHttpTransportTests.cs
----
using System.Net;
using System.Text;
namespace redb.Route.Tests.Llm;
///
/// Every model client of the package keeps a long silent call alive the same way: HTTP/2 when the server offers it,
/// and a PING frame while the request is in flight. The client built by Create asks for HTTP/2, and every
/// request carries the client's version: a hand-built request starts at HTTP/1.1, and then the pings never happen.
///
public sealed class LlmHttpTransportTests
{
/// Records the HTTP version every request asked for and answers with a fixed body.
private sealed class VersionRecordingHandler(string body, string mediaType = "application/json") : HttpMessageHandler
{
public List<(Version Version, HttpVersionPolicy Policy)> Requests { get; } = [];
protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct)
{
Requests.Add((request.Version, request.VersionPolicy));
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(body, Encoding.UTF8, mediaType)
});
}
}
/// A caller's client that asks for HTTP/2, the way the package's own default client does.
private static HttpClient Http2Client(HttpMessageHandler handler) => new(handler)
{
DefaultRequestVersion = HttpVersion.Version20,
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower
};
private static LlmConnectionFactory Factory(string provider, string model) =>
new() { Provider = provider, ModelId = model, ApiKey = "sk-test", RequestTimeoutMs = 90_000 };
[Fact]
public void OpenAi_DefaultClient_AsksForHttp2()
{
var provider = OpenAiProvider.Create(Factory("deepseek", "deepseek-flash"));
provider.Http.DefaultRequestVersion.Should().Be(HttpVersion.Version20,
"the keep-alive pings ride on HTTP/2 frames; a thinking model's call is minutes of silence");
provider.Http.DefaultVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 stays the fallback");
provider.Http.Timeout.Should().Be(Timeout.InfiniteTimeSpan,
"RequestTimeoutMs limits the whole call and is applied per call (RequestTimeoutTests)");
}
[Fact]
public async Task OpenAi_Request_CarriesTheClientsHttpVersion()
{
var handler = new VersionRecordingHandler("""{"choices":[{"message":{"role":"assistant","content":"done"}}]}""");
var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Http2Client(handler));
await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] });
var sent = handler.Requests.Should().ContainSingle().Subject;
sent.Version.Should().Be(HttpVersion.Version20, "a hand-built request must carry the client's version");
sent.Policy.Should().Be(HttpVersionPolicy.RequestVersionOrLower);
}
[Fact]
public async Task OpenAi_StreamRequest_CarriesTheClientsHttpVersion()
{
var handler = new VersionRecordingHandler(
"data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n", "text/event-stream");
var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Http2Client(handler));
await foreach (var _ in provider.StreamAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] }))
{
}
var sent = handler.Requests.Should().ContainSingle().Subject;
sent.Version.Should().Be(HttpVersion.Version20, "the streaming request is hand-built too");
sent.Policy.Should().Be(HttpVersionPolicy.RequestVersionOrLower);
}
[Fact]
public void Transcription_DefaultClient_AsksForHttp2()
{
var provider = OpenAiTranscriptionProvider.Create(Factory("openai", "whisper-1"));
provider.Http.DefaultRequestVersion.Should().Be(HttpVersion.Version20,
"a long recording is minutes of compute with nothing on the wire");
provider.Http.DefaultVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 stays the fallback");
provider.Http.Timeout.Should().Be(Timeout.InfiniteTimeSpan,
"RequestTimeoutMs limits the whole call and is applied per call (RequestTimeoutTests)");
}
[Fact]
public async Task Transcription_Request_CarriesTheClientsHttpVersion()
{
var handler = new VersionRecordingHandler("""{"text":"hi"}""");
var provider = new OpenAiTranscriptionProvider(Factory("openai", "whisper-1"), Http2Client(handler));
await provider.TranscribeAsync(new TranscriptionRequest(new byte[] { 0x4F, 0x67, 0x67, 0x53 }, "voice.oga", Language: "ru"));
var sent = handler.Requests.Should().ContainSingle().Subject;
sent.Version.Should().Be(HttpVersion.Version20, "a hand-built request must carry the client's version");
sent.Policy.Should().Be(HttpVersionPolicy.RequestVersionOrLower);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmIntegrationTests.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/tests/redb.Route.Tests.Llm/LlmIntegrationTests.cs
----
using System.Diagnostics.Metrics;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using redb.Route.Llm.Engine.Governance;
using redb.Route.Llm.Engine.Observability;
using redb.Route.Tests.Llm.TestHelpers;
using LlmDsl = redb.Route.Llm.Fluent.Llm;
namespace redb.Route.Tests.Llm;
///
/// End-to-end pipeline tests using a scriptable .
/// Verifies that LlmComponent → LlmEndpoint → LlmProducer → AgentEngine
/// correctly forwards user content, dispatches tool calls through the producer
/// template against a real direct: route, and emits the canonical
/// metrics. Because the provider is scripted, these tests run without any
/// network access or API keys.
///
public sealed class LlmIntegrationTests
{
private static (RouteContext ctx, LlmProducer producer, LlmEndpoint endpoint, IProducerTemplate pt)
BuildRoute(FakeProvider fake, string factoryName = "fake", string uri = "llm://fake")
{
var ctx = new RouteContext();
var component = new LlmComponent();
ctx.AddComponent(component);
ctx.AddToRegistry(factoryName, new LlmConnectionFactory
{
Name = factoryName,
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
var pt = new ProducerTemplate(ctx);
ctx.AddService(typeof(IProducerTemplate), pt);
var engine = new AgentEngine(
logger: null,
producerTemplate: pt,
observer: new NoopAgentObserver(),
budget: new NoopBudgetEnforcer(),
approval: new AutoApproveGate(),
redaction: new NoopRedactionFilter(),
shadow: new NoopShadowRunner(),
conversation: null, idempotency: null, approvalStore: null);
ctx.AddService(typeof(IAgentEngine), engine);
var registry = new ToolDescriptorRegistry();
ctx.AddService(typeof(IToolDescriptorRegistry), registry);
var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(uri));
var producer = (LlmProducer)endpoint.CreateProducer();
return (ctx, producer, endpoint, pt);
}
[Fact]
public async Task EndToEnd_StubProvider_RoundTrip()
{
var ctx = new RouteContext();
var component = new LlmComponent();
ctx.AddComponent(component);
ctx.AddToRegistry("local", new LlmConnectionFactory
{
Name = "local",
Provider = "stub",
ModelId = "echo-1"
});
ctx.AddService(typeof(IAgentEngine), new AgentEngine());
var endpoint = (LlmEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse(LlmDsl.Factory("local").Temperature(0.0).AsUri()));
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var ex = new Exchange(new Message("translate this"));
await producer.Process(ex);
ex.Out!.Body.Should().Be("[stub] translate this");
ex.Out.Headers[LlmHeaders.ProviderId].Should().Be("stub");
ex.Out.Headers[LlmHeaders.ModelId].Should().Be("echo-1");
// Ownership audit: the connector keeps MessagesIn (a user turn arrived - no core wrapper
// counts that for a producer); MessagesOut/Errors/Time belong to the core (ToProcessor on
// a routed .To(), the ProducerTemplate for template sends). A bare producer.Process call
// like this one therefore moves nothing into MessagesOut - and no longer double-counts
// on the routed path the tsak dashboard actually watches.
endpoint.MessagesIn.Should().Be(1);
endpoint.MessagesOut.Should().Be(0);
// The prompt goes out, the model's answer comes back in. Both used to compete for the one
// byte counter, so the prompt sat in BytesIn and the answer was discarded.
endpoint.BytesOut.Should().Be("translate this".Length);
}
[Fact]
public async Task EndToEnd_ToolLoop_DispatchesViaProducerTemplate()
{
// Scripted provider asks for tool 'echo' once, then ends the turn with text.
var fake = new FakeProvider()
.EnqueueToolUse("echo", "{\"v\":1}")
.EnqueueText("done");
// Set up everything via host helper so the tool route shares the registry.
await using var host = LiveLlmHost.Build();
host.Context.AddToRegistry("fake", new LlmConnectionFactory
{
Name = "fake",
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
var echoTool = new EchoToolRoute(
toolName: "echo",
description: "echo back the result",
inputSchema: """{"type":"object","properties":{"v":{"type":"number"}}}""",
replyJson: """{"r":42}""");
await host.StartAsync(echoTool, r =>
{
r.From("direct:agent")
.To(LlmDsl.Factory("fake").Tools("echo").AsUri())
.To("mock:done");
});
var ex = await host.SendAsync("direct:agent", "go");
// After running through the route, the body has rotated into In on the next hop.
var sink = host.Mock("mock:done");
sink.ReceivedCount.Should().Be(1);
((string)sink.ReceivedExchanges[0].In.Body!).Should().Be("done");
echoTool.CapturedInputs.Should().ContainSingle()
.Which.Should().Contain("\"v\":1");
fake.CallCount.Should().Be(2);
// The second LLM request must contain the tool_result that came back from the route.
var followUp = fake.CapturedRequests[^1];
followUp.Messages.SelectMany(m => m.Content)
.OfType()
.Should().ContainSingle()
.Which.OutputJson.Should().Contain("42");
}
[Fact]
public async Task EndToEnd_EmitsOpenTelemetryMetrics()
{
var exported = new List();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("redb.Route")
.AddInMemoryExporter(exported)
.Build();
var fake = new FakeProvider().EnqueueText("hi", tokensIn: 7, tokensOut: 11);
var (_, producer, _, _) = BuildRoute(fake);
await producer.Start();
await producer.Process(new Exchange(new Message("ping")));
meterProvider.ForceFlush(2000);
exported.Should().Contain(m => m.Name == "redb.route.llm.calls");
exported.Should().Contain(m => m.Name == "redb.route.llm.agent.runs");
exported.Should().Contain(m => m.Name == "redb.route.llm.tokens.in");
exported.Should().Contain(m => m.Name == "redb.route.llm.tokens.out");
}
[Fact]
public async Task EndToEnd_ConversationFromHeader_PropagatesToRequest()
{
var fake = new FakeProvider().EnqueueText("ack");
var (_, producer, _, _) = BuildRoute(fake, uri: "llm://fake?conversation=header");
await producer.Start();
var msg = new Message("hello");
msg.Headers[LlmHeaders.ConversationId] = "conv-42";
await producer.Process(new Exchange(msg));
// ConversationId is forwarded to the agent request; persistence is opt-in (Phase 2).
fake.CallCount.Should().Be(1);
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmPreambleTests.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/tests/redb.Route.Tests.Llm/LlmPreambleTests.cs
----
using redb.Route.Llm.Engine.Storage;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// Producer-level coverage for the header: fixed opening
/// messages open the transcript on every call, sit before the loaded history, and never reach
/// the conversation store. Backed by — no DB required.
///
public sealed class LlmPreambleTests
{
private const string Question = "Read it? Now, in your own words: do you accept?";
private const string Reply = "I accept — as a working rule, with the reservations named.";
private static (LlmProducer producer, FakeProvider fake, InMemoryConversationStore store) Build()
{
var ctx = new RouteContext();
var component = new LlmComponent();
ctx.AddComponent(component);
var fake = new FakeProvider();
ctx.AddToRegistry("fake", new LlmConnectionFactory
{
Name = "fake",
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
var store = new InMemoryConversationStore();
ctx.AddService(typeof(IAgentEngine), new AgentEngine(
logger: null,
producerTemplate: null,
observer: null,
budget: null,
approval: null,
redaction: null,
shadow: null,
conversation: store,
idempotency: null,
approvalStore: null));
var endpoint = (LlmEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse("llm://fake?conversation=header"));
return ((LlmProducer)endpoint.CreateProducer(), fake, store);
}
private static IReadOnlyList Preamble() =>
[
LlmMessage.User(Question),
new LlmMessage
{
Role = "assistant",
Content = [new LlmTextBlock(Reply)],
CacheBreakpoint = true
}
];
private static async Task TurnAsync(LlmProducer producer, string text)
{
var msg = new Message(text);
msg.Headers[LlmHeaders.ConversationId] = "c-test";
msg.Headers[LlmHeaders.Preamble] = Preamble();
await producer.Process(new Exchange(msg));
}
private static string Text(LlmMessage m) => m.Content.OfType().First().Text;
[Fact]
public async Task Preamble_OpensTheTranscript_AndSitsBeforeTheLoadedHistory()
{
var (producer, fake, _) = Build();
fake.EnqueueText("first").EnqueueText("second");
await producer.Start();
await TurnAsync(producer, "hi");
await TurnAsync(producer, "again");
fake.CapturedRequests.Should().HaveCount(2);
// Second call: preamble first, then the stored history, then the new turn. (The captured
// list is the engine's live transcript, so the tail also carries the reply appended after
// the call — the prefix is what this fact is about.)
var seen = fake.CapturedRequests[1].Messages;
seen.Take(5).Select(m => m.Role).Should().Equal("user", "assistant", "user", "assistant", "user");
Text(seen[0]).Should().Be(Question);
Text(seen[1]).Should().Be(Reply);
seen[1].CacheBreakpoint.Should().BeTrue("the breakpoint rides on the message into the provider");
Text(seen[2]).Should().Be("hi");
Text(seen[3]).Should().Be("first");
Text(seen[4]).Should().Be("again");
}
[Fact]
public async Task Preamble_IsNeverPersisted()
{
var (producer, fake, store) = Build();
fake.EnqueueText("ok");
await producer.Start();
await TurnAsync(producer, "hi");
// The store holds what was said in this dialog — one user turn, one reply — and nothing
// of the fixed opening exchange.
var rows = await store.LoadTreeAsync("c-test");
rows.Should().HaveCount(2);
rows.Select(r => r.Message.Role).Should().Equal("user", "assistant");
rows.Select(r => Text(r.Message)).Should().NotContain(Question).And.NotContain(Reply);
}
[Fact]
public async Task WithoutTheHeader_NothingChanges()
{
var (producer, fake, _) = Build();
fake.EnqueueText("ok");
await producer.Start();
var msg = new Message("hi");
msg.Headers[LlmHeaders.ConversationId] = "c-test";
await producer.Process(new Exchange(msg));
fake.CapturedRequests.Single().Messages[0].Role.Should().Be("user");
Text(fake.CapturedRequests.Single().Messages[0]).Should().Be("hi");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmProducerTests.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/tests/redb.Route.Tests.Llm/LlmProducerTests.cs
----
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
public sealed class LlmProducerTests
{
private static (RouteContext ctx, LlmEndpoint endpoint) Build(
FakeProvider provider,
string factoryName = "fake",
string uri = "llm://fake",
Action? configure = null)
{
var ctx = new RouteContext();
var component = new LlmComponent();
ctx.AddComponent(component);
var factory = new LlmConnectionFactory
{
Name = factoryName,
Provider = "fake",
ModelId = provider.ModelId,
PrebuiltProvider = provider
};
configure?.Invoke(factory);
ctx.AddToRegistry(factoryName, factory);
ctx.AddService(typeof(IAgentEngine), new AgentEngine());
var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(uri));
return (ctx, endpoint);
}
[Fact]
public void Ctor_NullEndpoint_Throws()
{
var act = () => new LlmProducer(null!, new LlmEndpointOptions());
act.Should().Throw();
}
[Fact]
public void Ctor_NullOptions_Throws()
{
var (_, endpoint) = Build(new FakeProvider());
var act = () => new LlmProducer(endpoint, null!);
act.Should().Throw();
}
[Fact]
public async Task Process_BeforeStart_Throws()
{
var (_, endpoint) = Build(new FakeProvider());
var producer = new LlmProducer(endpoint, new LlmEndpointOptions());
var act = () => producer.Process(new Exchange(new Message("hi")));
await act.Should().ThrowAsync().WithMessage("*not been started*");
}
[Fact]
public async Task Process_WritesAssistantTextAndHeaders()
{
var fake = new FakeProvider().EnqueueText("hello back", tokensIn: 3, tokensOut: 4);
var (_, endpoint) = Build(fake);
var producer = new LlmProducer(endpoint, new LlmEndpointOptions());
await producer.Start();
var exchange = new Exchange(new Message("hi"));
await producer.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.Body.Should().Be("hello back");
exchange.Out.Headers[LlmHeaders.ProviderId].Should().Be("fake");
exchange.Out.Headers[LlmHeaders.ModelId].Should().Be("fake-model");
exchange.Out.Headers[LlmHeaders.TokensIn].Should().Be(3);
exchange.Out.Headers[LlmHeaders.TokensOut].Should().Be(4);
exchange.Out.Headers[LlmHeaders.ToolIterations].Should().Be(1);
exchange.Out.Headers[LlmHeaders.StopReason].Should().Be(nameof(LlmStopReason.EndTurn));
}
[Fact]
public async Task Process_RecordsThePromptAsBytesOut()
{
var fake = new FakeProvider().EnqueueText("ok");
var (_, endpoint) = Build(fake);
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var prompt = "abcdefghij"; // 10 bytes
await producer.Process(new Exchange(new Message(prompt)));
// The prompt LEAVES the endpoint. It was recorded as BytesIn while RecordBytesOut did not
// exist — the one byte counter had to hold both directions.
endpoint.BytesOut.Should().Be(prompt.Length);
}
[Fact]
public async Task Process_CountsThePromptInUtf8Bytes()
{
var fake = new FakeProvider().EnqueueText("ok");
var (_, endpoint) = Build(fake);
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var prompt = "привет"; // 6 UTF-16 chars, 12 UTF-8 bytes
await producer.Process(new Exchange(new Message(prompt)));
endpoint.BytesOut.Should().Be(12, "the counter is called Bytes, yet UTF-16 chars were counted");
}
[Fact]
public async Task Process_MissingFactory_Throws()
{
var ctx = new RouteContext();
var component = new LlmComponent();
ctx.AddComponent(component);
ctx.AddService(typeof(IAgentEngine), new AgentEngine());
var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("llm://nope"));
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var act = () => producer.Process(new Exchange(new Message("hi")));
await act.Should().ThrowAsync()
.WithMessage("*nope*not registered*");
}
[Fact]
public async Task Process_MissingEngine_Throws()
{
var ctx = new RouteContext();
var component = new LlmComponent();
ctx.AddComponent(component);
ctx.AddToRegistry("fake", new LlmConnectionFactory
{
Name = "fake",
Provider = "stub",
ModelId = "x"
});
var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("llm://fake"));
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var act = () => producer.Process(new Exchange(new Message("hi")));
await act.Should().ThrowAsync()
.WithMessage("*IAgentEngine*");
}
[Fact]
public async Task Process_PassesSystemPromptFromHeader()
{
var fake = new FakeProvider().EnqueueText("ok");
var (_, endpoint) = Build(fake);
var producer = (LlmProducer)endpoint.CreateProducer();
await producer.Start();
var msg = new Message("translate me");
msg.Headers[LlmHeaders.SystemPrompt] = "you are a translator";
await producer.Process(new Exchange(msg));
fake.CapturedRequests.Single().SystemPrompt.Should().Be("you are a translator");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmScheduledOwnershipTests.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/tests/redb.Route.Tests.Llm/LlmScheduledOwnershipTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Tests.Llm.TestHelpers;
namespace redb.Route.Tests.Llm;
///
/// Statistics ownership for the scheduled agent (From("llm://...?schedule=...")):
/// the route pipeline is wrapped by the core's StatisticsProcessor, so the consumer must not
/// self-record what the core already counts. It records only what the core cannot see —
/// a tick that failed before the exchange reached the pipeline.
///
public sealed class LlmScheduledOwnershipTests
{
[Fact]
public async Task ScheduledTick_IsCountedByTheCore_NotByTheConsumer()
{
var fake = new FakeProvider().EnqueueText("tick!");
await using var host = LiveLlmHost.Build();
host.AddFactory("fake", new LlmConnectionFactory
{
Name = "fake",
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
const string uri = "llm://fake?schedule=200ms&initialBodyRef=go";
await host.StartAsync(r => r.From(uri).To("mock:llm-ticks"));
var sink = host.Mock("mock:llm-ticks");
var deadline = DateTime.UtcNow.AddSeconds(10);
while (sink.ReceivedCount == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
sink.ReceivedCount.Should().BeGreaterThan(0, "at least one tick must reach the route");
var ep = (IEndpointStatistics)host.Context.GetEndpoint(uri);
// The pipeline leg is the core's: MessagesIn per tick from StatisticsProcessor.
ep.MessagesIn.Should().BeGreaterThan(0, "MessagesIn is written by StatisticsProcessor around From()");
// Nothing produces THROUGH the scheduled endpoint - self-recording a MessagesOut per
// tick doubled the picture (core wrote its own success number on the same endpoint).
ep.MessagesOut.Should().Be(0, "MessagesOut is a producer counter, a tick is not one");
ep.Errors.Should().Be(0, "successful ticks must bring no errors");
}
[Fact]
public async Task A_tick_whose_model_call_failed_is_recorded_with_its_text()
{
var fake = new FakeProvider { ThrowOnCall = new InvalidOperationException("model refused by the test") };
await using var host = LiveLlmHost.Build();
host.AddFactory("fake", new LlmConnectionFactory
{
Name = "fake",
Provider = "fake",
ModelId = fake.ModelId,
PrebuiltProvider = fake
});
const string uri = "llm://fake?schedule=200ms&initialBodyRef=go";
await host.StartAsync(r => r.From(uri).To("mock:llm-failed-ticks"));
var ep = (IEndpointStatistics)host.Context.GetEndpoint(uri);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (ep.Errors == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
ep.Errors.Should().BeGreaterThan(0, "a tick that failed before the pipeline is the consumer's to count");
ep.LastErrorMessage.Should().Contain("model refused by the test");
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmServiceCollectionExtensionsTests.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/tests/redb.Route.Tests.Llm/LlmServiceCollectionExtensionsTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Llm.Extensions;
using redb.Route.Llm.Storage.Redb;
namespace redb.Route.Tests.Llm;
public sealed class LlmServiceCollectionExtensionsTests
{
[Fact]
public void AddRedbRouteLlm_RegistersComponentEngineAndRegistry()
{
var services = new ServiceCollection();
var ctx = new RouteContext();
services.AddSingleton(ctx);
services.AddRedbRouteLlm();
var sp = services.BuildServiceProvider();
sp.GetRequiredService().Should().BeOfType();
sp.GetRequiredService().Should().BeOfType();
// The startup hook RouteHostedService applies
foreach (var configurator in sp.GetServices())
configurator.Configure(ctx);
ctx.GetComponent("llm").Should().NotBeNull();
}
[Fact]
public void AddLlmConnectionFactory_RegistersFactoryByName()
{
var services = new ServiceCollection();
var ctx = new RouteContext();
services.AddSingleton(ctx);
services.AddRedbRouteLlm();
services.AddLlmConnectionFactory("claude", f =>
{
f.Provider = "stub";
f.ModelId = "haiku";
});
var sp = services.BuildServiceProvider();
foreach (var configurator in sp.GetServices())
configurator.Configure(ctx);
var factory = ctx.GetFromRegistry("claude");
factory.Should().NotBeNull();
factory!.Name.Should().Be("claude");
factory.Provider.Should().Be("stub");
factory.ModelId.Should().Be("haiku");
}
[Fact]
public void AddLlmConnectionFactory_NameWinsOverConfigureOverride()
{
var services = new ServiceCollection();
var ctx = new RouteContext();
services.AddSingleton(ctx);
services.AddRedbRouteLlm();
services.AddLlmConnectionFactory("registered-name", f =>
{
f.Name = "evil-rename"; // user attempted override
f.Provider = "stub";
});
var sp = services.BuildServiceProvider();
foreach (var configurator in sp.GetServices())
configurator.Configure(ctx);
var factory = ctx.GetFromRegistry("registered-name");
factory.Should().NotBeNull();
factory!.Name.Should().Be("registered-name");
ctx.GetFromRegistry("evil-rename").Should().BeNull();
}
[Fact]
public void AddLlmConnectionFactory_NullName_Throws()
{
var services = new ServiceCollection();
var act = () => services.AddLlmConnectionFactory(null!, _ => { });
act.Should().Throw();
}
[Fact]
public void AddLlmConnectionFactory_NullConfigure_Throws()
{
var services = new ServiceCollection();
var act = () => services.AddLlmConnectionFactory("c", null!);
act.Should().Throw();
}
// ── The tool idempotency store: an in-memory default that any other registration replaces ──
private static ServiceProvider Build(Action register)
{
var services = new ServiceCollection();
services.AddSingleton(new RouteContext());
register(services);
return services.BuildServiceProvider();
}
private sealed class HostStore : IToolIdempotencyStore
{
public Task TryReserveAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default)
=> Task.FromResult(ToolIdempotencyReservation.NewReservation);
public Task CompleteAsync(string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default)
=> Task.CompletedTask;
public Task ReleaseAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default)
=> Task.CompletedTask;
}
[Fact]
public async Task AddRedbRouteLlm_Alone_RegistersAnInMemoryToolIdempotencyStore_ThatDeduplicates()
{
await using var sp = Build(s => s.AddRedbRouteLlm());
var store = sp.GetRequiredService();
store.Should().BeOfType();
(await store.TryReserveAsync("conv", "tu-1")).IsNew.Should().BeTrue();
await store.CompleteAsync("conv", "tu-1", """{"sent":true}""");
var again = await store.TryReserveAsync("conv", "tu-1");
again.IsNew.Should().BeFalse("a repeated call with the same key gets the stored output");
again.CachedOutputJson.Should().Be("""{"sent":true}""");
}
[Fact]
public async Task AddRedbLlmStorage_Wins_WhenCalledAfterAddRedbRouteLlm()
{
await using var sp = Build(s => { s.AddRedbRouteLlm(); s.AddRedbLlmStorage(); });
sp.GetRequiredService().Should().BeOfType();
}
[Fact]
public async Task AddRedbLlmStorage_Wins_WhenCalledBeforeAddRedbRouteLlm()
{
await using var sp = Build(s => { s.AddRedbLlmStorage(); s.AddRedbRouteLlm(); });
sp.GetRequiredService().Should().BeOfType();
}
[Fact]
public async Task AHostsOwnStore_Wins_WhenRegisteredBeforeAddRedbRouteLlm()
{
await using var sp = Build(s => { s.AddSingleton(); s.AddRedbRouteLlm(); });
sp.GetRequiredService().Should().BeOfType();
}
[Fact]
public async Task AHostsOwnStore_Wins_WhenRegisteredAfterAddRedbRouteLlm()
{
await using var sp = Build(s => { s.AddRedbRouteLlm(); s.AddSingleton(); });
sp.GetRequiredService().Should().BeOfType();
}
}
Path: redb-route/tests/redb.Route.Tests.Llm/LlmTraceTests.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/tests/redb.Route.Tests.Llm/LlmTraceTests.cs
----
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Tests.Llm.TestHelpers;
using redb.Route.Tests.Telemetry;
namespace redb.Route.Tests.Llm;
///
/// A scheduled agent opens a root span per tick, with the model call and the route under it, never a child of the
/// activity that started the routes; a failed tick marks it red, our own stop does not. The model call of the producer
/// is a transport span of its endpoint: it honours