Path: redb-route/redb.Route.Llm/LlmConnectionFactory.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/LlmConnectionFactory.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Llm.Providers; using redb.Route.Core; namespace redb.Route.Llm; /// /// Connection factory configuration for the LLM connector. Register in the route /// registry and reference by name in endpoint URIs (connectionFactory=myFactory /// or as the URI host: llm://myFactory). /// /// Centralises model identity, version, credentials and per-provider tuning so /// they are kept out of the URI. /// /// public sealed class LlmConnectionFactory { /// /// Logical name of this factory (the registry key, e.g. "claude"). /// Set by when the factory is registered. /// Surfaced as the llm.factory tag on metrics and traces. /// public string Name { get; set; } = string.Empty; /// Provider identifier: "anthropic", "openai", "azure-openai", "ollama", "stub". public string Provider { get; set; } = "stub"; /// Model identifier passed to the provider (e.g. "claude-haiku-4.5", "gpt-4o-mini"). public string ModelId { get; set; } = "stub-model"; /// /// Optional Anthropic contract-tier override (legacy/transitional/modern). /// Escape-hatch for self-hosted ids, proxies, or model snapshots the built-in generation /// table does not recognise. When unset, the tier is inferred from /// (unknown ids default to modern — no removed sampling knobs are sent). Anthropic-only; /// ignored by OpenAI-compatible providers. See . /// public string? ModelContractTier { get; set; } /// API key. Prefer for production deployments. [Sensitive] public string? ApiKey { get; set; } /// Reference to a secret store entry — resolved at time. public string? ApiKeySecretRef { get; set; } /// Optional base URL override (Azure OpenAI, OpenAI-compatible servers, local Ollama). public Uri? BaseUrl { get; set; } /// Default sampling temperature. public double? Temperature { get; set; } /// Default max output tokens. public int? MaxTokens { get; set; } /// /// Effort level for models that think by default (Anthropic Claude 4.6+ / Sonnet 5 / Opus 5: /// low, medium, high, xhigh, max; sent as /// output_config.effort). null — the provider's default (high on /// Anthropic). Thinking tokens count against : at the default effort /// a hard question can spend the whole budget on thinking and return NO text (seen /// 2026-09-07 with max_tokens 4096 on Sonnet 5) — medium or low keeps the /// answer inside the budget. Models without the effort ladder (Haiku 4.5) reject the field /// with 400, so set it per factory, not globally. /// public string? Effort { get; set; } /// Default top-p sampling parameter. public double? TopP { get; set; } /// /// Limit of one call to the model, in milliseconds (default: 600 000, ten minutes, like the official Anthropic /// and OpenAI SDKs; at least 1 000). It covers the whole call, waiting for the answer and reading it, on every /// provider and whatever client sends it; running out throws . A /// non-streaming answer from a thinking model is minutes of generation, so set it to the longest answer you /// expect. A streamed call is limited the same way, from the send to the last piece; a stream's silence has a /// limit of its own, . A client passed in by the host keeps its own /// as well. /// public int RequestTimeoutMs { get; set; } = 600_000; /// /// Longest silence of a streamed call, in milliseconds: how long the provider may send nothing at all — no text, /// no thinking, not even a keep-alive comment or ping — before the call fails with /// (). It counts only /// the waits on the provider, not the time the reader spends between pieces. Off by default (null): the /// whole call is still limited by , and some reasoning models stream nothing for /// minutes before their first token. Must be positive when set. /// public int? StreamIdleTimeoutMs { get => _streamIdleTimeoutMs; set { if (value is <= 0) throw new ArgumentOutOfRangeException(nameof(value), value, "StreamIdleTimeoutMs must be positive; leave it unset (null) to turn the silence limit off."); _streamIdleTimeoutMs = value; } } private int? _streamIdleTimeoutMs; // Retries was removed: it was never read, and the Llm engine's resilience // policy is deliberately fallback-to-another-factory, not retry-the-same-provider. /// /// Optional pre-built provider instance. When set, returns it /// without attempting to construct one — useful for tests and custom providers. /// public ILlmProvider? PrebuiltProvider { get; set; } /// /// Logger factory used by built providers for diagnostics (e.g. Anthropic sampling-knob /// drops). Set automatically at registration by AddLlmConnectionFactory from DI; /// null in bare test setups (providers then fall back to activity events only). /// public ILoggerFactory? LoggerFactory { get; set; } /// /// Builds an from this configuration. Resolution order: /// /// if set; /// built-in provider matching ; /// for unknown providers. /// /// public ILlmProvider Build() { if (PrebuiltProvider is not null) return PrebuiltProvider; if (_cached is not null) return _cached; // Cache the built provider so its HttpClient is reused, not minted (and leaked) per call. Providers are // stateless per request and HttpClient is thread-safe, so one instance per factory is correct. lock (_buildLock) return _cached ??= BuildCore(); } private ILlmProvider? _cached; private readonly object _buildLock = new(); private ILlmProvider BuildCore() { return Provider?.ToLowerInvariant() switch { "stub" => new StubProvider(this), "anthropic" => new AnthropicProvider(this), // All providers below speak the OpenAI Chat Completions protocol. // Default base URLs are resolved by OpenAiProvider.ResolveDefaultBaseUrl; // override LlmConnectionFactory.BaseUrl for self-hosted/proxy setups. "openai" or "groq" or "cerebras" or "openrouter" or "gemini" or "google" or "github-models" or "github" or "mistral" or "together" or "togetherai" or "huggingface" or "hf" or "deepseek" or "ollama" or "lmstudio" => OpenAiProvider.Create(this), _ => throw new NotSupportedException( $"Unknown LLM provider '{Provider}'. Built-in providers: stub, anthropic, " + $"openai, groq, cerebras, openrouter, gemini, github-models, mistral, together, " + $"huggingface, deepseek, ollama, lmstudio. " + $"Use {nameof(PrebuiltProvider)} to plug a custom provider.") }; } }