Path: redb-route/redb.Route.Llm/Knowledge/KnowledgeRetrievalDsl.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Knowledge/KnowledgeRetrievalDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Knowledge;
/// Options for the step.
public sealed class KnowledgeRetrievalOptions
{
/// Collection to search (null = across all collections).
public string? Collection { get; set; }
/// How many chunks to inject.
public int TopK { get; set; } = 5;
/// Explicit store. When null, resolved from the exchange's .
public IKnowledgeStore? Store { get; set; }
///
/// When set (or resolvable from DI), retrieval is semantic (embed query → cosine
/// ); otherwise keyword
/// ().
///
public IEmbeddingProvider? EmbeddingProvider { get; set; }
/// Chooses the query text. Default: the exchange body as string.
public Func? Query { get; set; }
/// Max chars of each chunk injected (0 = full).
public int MaxCharsPerChunk { get; set; } = 1000;
/// Line placed above the retrieved chunks in the system prompt.
public string Preamble { get; set; } =
"Relevant knowledge (ground your answer on it; do not quote it verbatim to the user):";
}
///
/// DSL step that retrieves top-K knowledge chunks for the current message and
/// injects them into the system prompt (LlmHeaders.SystemPrompt),
/// so a following .To("llm://...") answers grounded on them. A no-op when
/// no store is available or nothing is retrieved — never breaks the pipeline.
///
///
/// From("kafka://questions")
/// .Knowledge("handbook", k: 5) // retrieve + inject
/// .To("llm://claude"); // answer, grounded
///
///
///
public static class KnowledgeRetrievalDsl
{
/// Retrieve + inject, shorthand.
public static IRouteDefinition Knowledge(this IRouteDefinition self, string? collection, int k = 5) =>
Knowledge(self, new KnowledgeRetrievalOptions { Collection = collection, TopK = k });
/// Retrieve + inject with explicit options.
public static IRouteDefinition Knowledge(this IRouteDefinition self, KnowledgeRetrievalOptions options)
{
ArgumentNullException.ThrowIfNull(self);
ArgumentNullException.ThrowIfNull(options);
return self.Process(async (exchange, ct) =>
{
var store = options.Store
?? exchange.ServiceProvider?.GetService(typeof(IKnowledgeStore)) as IKnowledgeStore;
if (store is null) return; // no store wired → no-op
var query = (options.Query?.Invoke(exchange) ?? exchange.In.Body?.ToString())?.Trim();
if (string.IsNullOrEmpty(query)) return;
var topK = Math.Clamp(options.TopK, 1, 50);
var embedder = options.EmbeddingProvider
?? exchange.ServiceProvider?.GetService(typeof(IEmbeddingProvider)) as IEmbeddingProvider;
IReadOnlyList hits;
if (embedder is not null)
{
var vector = await embedder.EmbedOneAsync(query, ct).ConfigureAwait(false);
hits = await store.SearchAsync(vector, topK, options.Collection, exchange, ct).ConfigureAwait(false);
}
else
{
hits = await store.SearchTextAsync(query, topK, options.Collection, exchange, ct).ConfigureAwait(false);
}
if (hits.Count == 0) return;
var block = BuildBlock(hits, options);
var existing = exchange.In.Headers.TryGetValue(LlmHeaders.SystemPrompt, out var sp) ? sp?.ToString() : null;
exchange.In.Headers[LlmHeaders.SystemPrompt] =
string.IsNullOrEmpty(existing) ? block : existing + "\n\n" + block;
exchange.In.Headers["llm.knowledge.injected"] = hits.Count;
});
}
private static string BuildBlock(IReadOnlyList hits, KnowledgeRetrievalOptions options)
{
var sb = new StringBuilder(options.Preamble);
foreach (var hit in hits)
{
var text = hit.Chunk.Text;
if (options.MaxCharsPerChunk > 0 && text.Length > options.MaxCharsPerChunk)
text = text[..options.MaxCharsPerChunk] + "…";
sb.Append("\n- ").Append(text.Replace("\r\n", " ").Replace('\n', ' '));
}
return sb.ToString();
}
}