Path: redb-route/redb.Route.Llm/Fluent/Llm.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/Fluent/Llm.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Llm.Fluent; /// /// Fluent API for LLM endpoints. /// /// .To(Llm.Factory("claude").Temperature(0.2).MaxTokens(1024)) /// .To(Llm.Factory("claude").Tools("*").Stream(LlmStreamMode.Calls)) /// /// public static class Llm { /// Creates an LLM endpoint targeting the named connection factory. public static LlmBuilder Factory(string connectionFactoryName) => new(connectionFactoryName); } /// Fluent builder for LLM endpoint URIs. public sealed class LlmBuilder { private readonly string _factory; private string? _temperature; private string? _maxTokens; private string? _topP; private string? _systemPromptRef; private string? _conversation; private LlmStreamMode _stream; private string? _schedule; private string? _initialBodyRef; private string? _maxIterations; private string? _budgetInputTokens; private string? _budgetOutputTokens; private string? _budgetCostUsd; private bool _cacheSystemPrompt; private string? _tools; private string? _user; private readonly List> _auditTags = []; private readonly List _propagateToolHeaders = []; private string? _promptTemplateName; private string? _promptTemplateVersion; internal LlmBuilder(string factory) { ArgumentException.ThrowIfNullOrWhiteSpace(factory); _factory = factory; } /// Sampling temperature. public LlmBuilder Temperature(double v) { _temperature = v.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Maximum output tokens. public LlmBuilder MaxTokens(int v) { _maxTokens = v.ToString(); return this; } /// Top-p sampling. public LlmBuilder TopP(double v) { _topP = v.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Reference (or literal) for system-prompt template. public LlmBuilder SystemPromptRef(string r) { _systemPromptRef = r; return this; } /// Tracks conversation by reading llm.conversation.id header. public LlmBuilder ConversationFromHeader() { _conversation = "header"; return this; } /// Tracks conversation using the route id as conversation key. public LlmBuilder ConversationFromRoute() { _conversation = "property"; return this; } /// /// Streams the step: — every model call streamed inside the route, tools and /// the route's transaction as without streaming, the pieces to the observer; — /// the text streamed into Out.Body while the model writes it. /// public LlmBuilder Stream(LlmStreamMode mode) { _stream = mode; return this; } /// Schedule for consumer mode (cron or fixed interval). public LlmBuilder Schedule(string s) { _schedule = s; return this; } /// Initial body template for scheduled consumers. public LlmBuilder InitialBody(string bodyRef) { _initialBodyRef = bodyRef; return this; } /// Maximum tool-loop iterations. public LlmBuilder MaxIterations(int n) { _maxIterations = n.ToString(); return this; } /// /// Per-run budget. Only the dimensions you pass reach the URI — an omitted ceiling stays absent, /// because "not set" and "zero" are different states in the URI. /// /// A value of 0 or less means no ceiling for that dimension, exactly as /// AgentBudget.Unbounded does: the enforcer only checks a limit that is positive. To stop a /// route from doing work, take the tool away, require an approval or require a claim — a zero ceiling /// is not a switch, and pretending otherwise would silently do nothing. /// /// /// The cost ceiling needs a registered that can /// price the model; without one the run fails fast rather than pretending to enforce it. /// /// public LlmBuilder Budget(int? inputTokens = null, int? outputTokens = null, decimal? costUsd = null) { if (inputTokens is not null) _budgetInputTokens = inputTokens.Value.ToString(); if (outputTokens is not null) _budgetOutputTokens = outputTokens.Value.ToString(); if (costUsd is not null) _budgetCostUsd = costUsd.Value.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// /// Asks the provider to cache the system prompt across turns /// (). /// Only pays off when the system prompt is byte-stable: caching matches on the /// rendered prefix, so a prompt that varies per request is written and never read back. /// LlmUsage.CacheReadInputTokens is what says it works. /// public LlmBuilder CacheSystemPrompt() { _cacheSystemPrompt = true; return this; } /// /// Tool exposure filter — "*" for every descriptor in the registry, /// or a CSV of tool names (e.g. "get_order,get_invoice"). /// public LlmBuilder Tools(string filter) { _tools = filter; return this; } /// Exposes every descriptor registered in the global tool registry. public LlmBuilder UseAllTools() { _tools = "*"; return this; } /// /// Principal identifier for audit — literal value ("system") or a /// header reference ("${header.X-User-Id}"). The producer resolves /// this expression pre-call against the inbound exchange and stamps the /// resolved value on every persisted row of the run as /// MessageProps.UserId. When unset, LlmHeaders.UserId /// (llm.user.id) is used as a fallback. /// public LlmBuilder User(string expression) { _user = expression; return this; } /// /// Adds one audit tag to the run. may be a literal /// or a ${header.X} expression. The producer resolves the value /// pre-call and stamps the (key, value) pair on every persisted row as /// MessageProps.AuditTags entry. Headers named /// llm.audit.<key> merge on top of these; headers win on /// collision. Repeatable — call once per tag. /// public LlmBuilder Audit(string key, string value) { ArgumentException.ThrowIfNullOrWhiteSpace(key); _auditTags.Add(new KeyValuePair(key, value ?? string.Empty)); return this; } /// /// Opts extra headers into propagation from this exchange to every tool call /// of the run. A trailing * makes an entry a prefix match: /// .PropagateToolHeaders("x-tenant-id", "x-app-*"). /// /// Propagation is default-deny. Without this call a tool route already /// receives the conversation id, both correlation-id spellings, the resolved /// principal (llm.user.id — see ) and the resolved /// audit tags (llm.audit.* — see ). The inbound /// transport's own headers are never forwarded implicitly; name here only /// headers the route itself sets or has sanitized. /// /// Repeatable — names accumulate across calls. /// public LlmBuilder PropagateToolHeaders(params string[] names) { ArgumentNullException.ThrowIfNull(names); foreach (var n in names) if (!string.IsNullOrWhiteSpace(n)) _propagateToolHeaders.Add(n.Trim()); return this; } /// /// Locks the prompt-template (name, version) pair onto every persisted row /// of the run as MessageProps.PromptTemplateName / /// PromptTemplateVersion. Independent of /// — you can carry name/version even when the prompt body comes from /// elsewhere. /// public LlmBuilder PromptTemplate(string name, string version) { _promptTemplateName = name; _promptTemplateVersion = version; return this; } /// Implicit conversion to for use in .To(...) / .From(...). public static implicit operator EndpointUri(LlmBuilder b) => EndpointUriParser.Parse(b.ToString()); /// Returns the URI string. Useful for .To(builder.AsUri()) overloads that take string. public string AsUri() => ToString(); /// public override string ToString() { var sb = new StringBuilder("llm://").Append(Uri.EscapeDataString(_factory)); var first = true; Append(sb, ref first, "temperature", _temperature); Append(sb, ref first, "maxTokens", _maxTokens); Append(sb, ref first, "topP", _topP); Append(sb, ref first, "systemPromptRef", _systemPromptRef); Append(sb, ref first, "conversation", _conversation); if (_stream != LlmStreamMode.Off) Append(sb, ref first, "stream", _stream.ToString().ToLowerInvariant()); Append(sb, ref first, "schedule", _schedule); Append(sb, ref first, "initialBodyRef", _initialBodyRef); Append(sb, ref first, "maxIterations", _maxIterations); Append(sb, ref first, "budgetInputTokens", _budgetInputTokens); Append(sb, ref first, "budgetOutputTokens", _budgetOutputTokens); Append(sb, ref first, "budgetCostUsd", _budgetCostUsd); if (_cacheSystemPrompt) Append(sb, ref first, "cacheSystemPrompt", "true"); Append(sb, ref first, "tools", _tools); Append(sb, ref first, "user", _user); Append(sb, ref first, "audit", BuildAuditCsv(_auditTags)); Append(sb, ref first, "propagateToolHeaders", BuildCsv(_propagateToolHeaders)); Append(sb, ref first, "promptTemplateName", _promptTemplateName); Append(sb, ref first, "promptTemplateVersion", _promptTemplateVersion); return sb.ToString(); } private static string? BuildCsv(List values) { if (values.Count == 0) return null; var sb = new StringBuilder(); for (var i = 0; i < values.Count; i++) { if (i > 0) sb.Append(','); sb.Append(Uri.EscapeDataString(values[i])); } return sb.ToString(); } private static string? BuildAuditCsv(List> tags) { if (tags.Count == 0) return null; var sb = new StringBuilder(); for (var i = 0; i < tags.Count; i++) { if (i > 0) sb.Append(','); sb.Append(Uri.EscapeDataString(tags[i].Key)) .Append('=') .Append(Uri.EscapeDataString(tags[i].Value)); } return sb.ToString(); } private static void Append(StringBuilder sb, ref bool first, string key, string? value) { if (string.IsNullOrEmpty(value)) return; sb.Append(first ? '?' : '&'); first = false; sb.Append(key).Append('=').Append(Uri.EscapeDataString(value)); } }