Skip to content

DI Extensions

AIProviderConnect.DependencyInjection exposes AddAiProviders in three overloads:

// Embedded catalog only.
public static IServiceCollection AddAiProviders(this IServiceCollection services);

// Merge/override definitions, then register the resulting catalog.
public static IServiceCollection AddAiProviders(
    this IServiceCollection services,
    IEnumerable<ProviderDefinition> customProviders);

// Full builder: definitions, named options, custom providers, model overrides.
public static IServiceCollection AddAiProviders(
    this IServiceCollection services,
    Action<AIProviderRegistrationBuilder> configure);

Each overload registers the ProviderCatalog singleton, one named options instance and one IAIProvider singleton per catalog entry, seeding option defaults (BaseUrl plus the protocol's chat/models endpoints) from each definition. See Dependency Injection for the full registration picture.

AIProviderRegistrationBuilder

The builder overload collects customizations applied before providers are wired. All methods return the builder for chaining.

Method Description
Add(ProviderDefinition) Add a new definition, or replace an already-added one with the same id
Replace(string providerId, Func<ProviderDefinition, ProviderDefinition>) Transform an embedded or added definition in place; chained calls on the same id compose
Configure<TOptions>(string providerId, Action<TOptions>) Configure named options; runs after seeding, so consumer values win
AddProvider<TProvider>(string providerId, Func<IServiceProvider, TProvider>) Register a consumer IAIProvider and exclude that id from the automatic protocol loop
OverrideModels(string providerId, IEnumerable<ModelOverride>) Register model/pricing overrides merged transparently over GetModelsAsync (see Model Discovery)
UseModelOverrideStore(IModelOverrideStore) Replace the default in-memory override store with a consumer-supplied source
UseCredentialResolver(ICredentialResolver) Register a consumer-supplied resolver consulted once per provider call for runtime credential/model overrides (see Runtime Credentials)

Custom definitions are validated at registration time: a missing id, a missing base URL, or a duplicate id throws ArgumentException. A Native-protocol definition with no AddProvider registration throws InvalidOperationException.

Seeding an authored provider

SeedFromDefinition(AIProviderOptions options, ProviderDefinition definition) is public. It copies a definition's base URL, endpoint paths (including every endpoints override), its requiresApiKey value, the read-out members, and the protocolConfiguration dictionary onto an options instance. The built-in registration uses it for every catalog entry; a provider registered through AddProvider<TProvider> uses it for the same reason — a Native-protocol id is skipped by the automatic registration loop, so the provider's own factory is the only place the definition can be applied.

services.AddAiProviders(b => b
    .Add(definition)                       // Protocol = EProviderProtocol.Native
    .AddProvider<MyProvider>("my-host", sp =>
    {
        var options = new MyProviderOptions();
        AIProviderServiceCollectionExtensions.SeedFromDefinition(options, definition);
        sp.GetRequiredService<IConfiguration>()
          .GetSection("Providers:my-host").Bind(options);   // consumer values win
        return new MyProvider(sp.GetRequiredService<HttpClient>(), options, ...);
    }));

A consumer Configure<TOptions> callback is applied after seeding and wins over every definition-seeded value. The authored class itself builds on the protected surface of AIProviderBase and the public wire maps — see Writing your own transport.

Endpoint Folding and Class Selection

Before the protocol switch runs, each definition's endpoints block is validated and folded into the named options (see Wire Protocols for the precedence chain and the rejection matrix). Registration fails fast with AiException (ai/configuration-error) for an unknown operation key, an entry that changes nothing, an empty or absolute path, a non-HTTPS baseUrl on a routable host (a loopback address may use http), a chat entry on a KeyQuery provider without a {model} placeholder, a decisionReadout entry on a root with no chat surface, or a decisions override the root protocol cannot serve.

When an OpenAICompatible or HybridGateway definition declares a decisions entry with protocol: "decision", registration selects the combined OpenAICompatibleDecisionProvider (chat, streaming, model discovery, embeddings, and decisions under one id) and seeds its DecisionsEndpoint/DecisionsBaseUrl from the entry; the embeddings entry's path and optional baseUrl fold into EmbeddingsEndpoint and EmbeddingsBaseUrl in the same registration, independent of whether a decisions override is present. This is the one exception to "one IAIProvider singleton per catalog entry with a concrete type chosen from the definition's wire protocol" — the id still holds one singleton, but its type serves two wire protocols.

The model-override decorator chain stays capability-transparent: a provider id with override entries that is streaming and decision-capable is wrapped in a decorator that forwards both, so is IDecisionProvider keeps matching after decoration. A streaming id that also implements IEmbeddingProvider keeps it; one that does not (a MessagesApi, KeyQuery, or Catalog entry) gets the non-embedding variant, so is IEmbeddingProvider stays accurate. Streaming-only ids keep the streaming decorator, and non-streaming decision providers keep the decision decorator.

Options Reference

All options classes live in AIProviderConnect.Options and derive from AIProviderOptions. Options are named by provider catalog ID.

AIProviderOptions (base)

Property Type Default Description
Enabled bool true Provider is enabled by default; set false to disable it before any call succeeds
ApiKey string "" API key (Bearer token, x-api-key, or x-goog-api-key header depending on protocol)
BaseUrl string "" API base URL
DefaultModel string "" Fallback model applied when a request carries no model and no per-call override supplies one; the chat path resolves credentials?.Model → request.Model → DefaultModel
DefaultHeaders Dictionary<string, string> empty Extra headers sent with every request (see Custom Headers)
MaxRetryCount int 0 Maximum retry attempts for transient failures (rate-limit, server errors); 0 disables retry
RetryDelay TimeSpan 1s Base delay between retries; actual delay uses exponential backoff with jitter
ProtocolConfiguration IReadOnlyDictionary<string, string>? null Protocol-specific key-value pairs seeded from the provider JSON manifest
RequiresApiKey bool? null Explicit API-key requirement. When set it wins over the definition; when unset the definition value applies and, failing that, the requirement is derived from the configured address — a loopback host does not require a key
DecisionReadoutEnabled bool true Whether a provider with no native decisions surface answers DecideAsync through the read-out; false restores the ai/decision-not-supported refusal
DecisionReadoutPromptTemplate string? null Overrides the built-in read-out prompt; placeholders {state}, {instructions}, {options}
DecisionReadoutOptionTokenStyle string "uppercaseLetter" Option prefix in the read-out prompt: uppercaseLetter (A.), lowercaseLetter (a.), or levelIndex (0.)
DecisionReadoutTopLogprobs int 20 Requested top_logprobs at the answer position; also the read-out's Choice-option ceiling
DecisionReadoutBoolTokens string "yes,no" The two comma-separated tokens a Noul question reads
DecisionReadoutTemperature float 0 Sampling temperature for a read-out chat call
DecisionsMaxOptions int? null Declared Choice-option ceiling for both transports; null leaves the wire's 255-option limit as the only cap

OpenAICompatibleProviderOptions

Base properties plus:

Property Type Default
ChatEndpoint string "chat/completions"
ModelsEndpoint string "models"
EmbeddingsEndpoint string "embeddings"
EmbeddingsBaseUrl string? null
DefaultEmbeddingModel string ""

HybridGatewayProviderOptions

Same shape as OpenAICompatibleProviderOptions. The HybridGateway protocol is served by OpenAICompatibleProvider internally.

Base properties plus:

Property Type Default
ChatEndpoint string "chat/completions"
ModelsEndpoint string "models"
EmbeddingsEndpoint string "embeddings"
EmbeddingsBaseUrl string? null
DefaultEmbeddingModel string ""

MessagesApiOptions

Base properties plus:

Property Type Default
MessagesEndpoint string "messages"
ModelsEndpoint string "models"

The anthropic-version header for Anthropic-compatible providers is sourced from the provider JSON manifest's protocolConfiguration.anthropicVersion via MessagesApiProtocol.ApplyProtocolConfiguration.

KeyQueryOptions

Base properties only.

DecisionProviderOptions

Base properties plus:

Property Type Default Description
DecisionsEndpoint string "alpha/decisions" Endpoint path resolved against BaseUrl
DecisionsBaseUrl string? null Full-URL override for hosts whose decisions surface lives on a different origin than BaseUrl

Both are also readable from the definition's protocolConfiguration (decisionsEndpoint, decisionsBaseUrl) via DecisionsWireProtocol.ApplyProtocolConfiguration. See Decision Models.

Catalog (uses OpenAICompatibleProviderOptions)

Base properties plus ChatEndpoint and ModelsEndpoint (see OpenAICompatibleProviderOptions above). Endpoint defaults are chat/completions and models respectively.

The X-GitHub-Api-Version header is sourced from the provider JSON manifest's protocolConfiguration.apiVersion via CatalogWireProtocol.ApplyProtocolConfiguration.

Prerequisites

Providers resolve HttpClient directly from the container, so one of these must be registered before resolving any provider:

builder.Services.AddHttpClient();                       // Microsoft.Extensions.Http
// or
builder.Services.AddSingleton(new HttpClient());