Documentation
Table of Contents

Providers

A provider sends a request to a model and brings the reply back. The providers come from a provider file, from a source of your own, or from code. IntentSharp includes two kinds that a provider file names: openai, for OpenAI and services that accept its chat completions requests, and anthropic. For any other model service, use its IChatClient (Microsoft.Extensions.AI) or write a provider of your own.

The provider file

intentsharp.providers.json (or its .yaml spelling) in a document store names each provider and maps the roles to them. Provider file covers every key, the roles and their chains and the model aliases, and Provider secrets the secrets and the edits it flags:

{
  "intentsharp": "providers/1",
  "providers": [
    { "name": "main", "kind": "anthropic", "secret": "env:ANTHROPIC_API_KEY", "model": "<model id>" },
    { "name": "backup", "kind": "openai", "secret": "env:OPENAI_API_KEY", "model": "<model id>" }
  ],
  "roles": {
    "answer": ["main", "backup"],
    "judge": "backup"
  }
}

Build the client over the folder that holds the file:

using var store = new FolderDocumentStore("config");   // holds intentsharp.providers.json
using var client = new IntentClientBuilder()
    .UseProviderOptions(store)
    .Build();

var summary = await email.AIAsync(client, "Summarize this email in one sentence.");

IntentSharp ships no model id. A call whose provider has no model in the call, the role or the file throws ProviderConfigurationException, naming the provider and the role, and nothing is sent. Build() throws InvalidOperationException when nothing serves the answer role, and names the file's problems when it did not load. An edit to the file applies to the next call, with no restart; a version that does not load is reported, and the version before it keeps running.

Where keys come from

A secret names its key by reference, never the key itself: env:NAME reads the environment variable NAME, and config:Key reads Key from the application's configuration under dependency injection, user secrets included. A key is read on the provider's first request; a reference that resolves to nothing fails that call with ProviderConfigurationException.

The provider file decides where your keys and your data go: an entry's endpoint is the address its key is sent to, and its secret names which value is sent. So treat the file as you treat code. An edit that changes either is flagged as widening, an entry with a secret and a plain http endpoint loads only for a loopback host or with "allowInsecureHttp": true, and a resolver of your own can bound what a file may name (Provider secrets).

Settings and retries

The built-in kinds send each request to the entry's endpoint, or the vendor's, and follow no redirect. They retry a 408, a 429, a 5xx and a transport error up to 3 times, after a wait that starts at 500 ms and doubles up to 30 seconds (a 429's Retry-After under two minutes is used instead), and give each send 120 seconds. These are fixed for the built-in kinds; a provider of your own sets them on HttpProviderOptions. A reply over 16 MB fails the call (IntentClientOptions.MaxResponseBytes). The call's time budget, 5 minutes by default, covers every send, wait and fallback (How it works).

WithHttpClientFactory supplies the HttpClient of each entry, asked by the entry's name:

// Asked for each entry's name: the entry "main" goes through a proxy; null lets a provider create its own client.
var proxied = new HttpClient(new HttpClientHandler
{
    Proxy = new WebProxy("http://proxy.example.com:8080"),
    AllowAutoRedirect = false,
})
{
    Timeout = Timeout.InfiniteTimeSpan,   // each provider keeps its own limit per send
};

var client = new IntentClientBuilder()
    .WithHttpClientFactory(name => name == "main" ? proxied : null)
    .UseProviderOptions(store)
    .Build();

A client you supply keeps its own Timeout (100 seconds unless you change it), its own base address is not used, and the provider never disposes it. Turn redirects off on its handler, as the providers' own clients do: a redirect it follows sends the request, and the key, to the address the redirect names. An anthropic entry sends a temperature only when its temperature capability is true. An openai entry serves embeddings with its embeddingModel; anthropic has none.

Under dependency injection

AddIntentSharp takes the providers from the container: the provider file of a registered document store, a registered provider options source, and registered providers. Its settings name no provider and read no environment variable (Configuration and DI):

services.AddDocumentStore("config");   // the folder that holds intentsharp.providers.json
services.AddIntentSharp(configuration);

// The HttpClient every openai entry uses: here behind a proxy. A handler of your own follows no redirect.
services.AddHttpClient("IntentSharp.OpenAI")
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
    {
        Proxy = new WebProxy("http://proxy.example.com:8080"),
        AllowAutoRedirect = false,
    });

Every openai entry uses the named client "IntentSharp.OpenAI", and every anthropic entry "IntentSharp.Anthropic".

A provider error is an issue, not an exception

The provider's reply The failure Retried Falls back
a redirect (3xx) AIProviderException no no
401 or 403 AIAuthenticationException no no
408 AIProviderException, transient yes yes
429 AIRateLimitException yes yes
400 or 422 AIValidationException no no
404: a model the provider does not serve AIModelUnavailableException no yes
5xx AIProviderInternalException yes yes
any other error status AIProviderException no no
a success that cannot be read AIProviderException, transient no yes
a success larger than the reply limit AIProviderException no no
a transport error AIProviderException, transient yes yes
no answer within the send timeout AITimeoutException no yes

A failure that no later provider answers ends the call with Success false and a Provider issue that carries the failure's message. The message names the provider, the status and the provider's error code, never the reply's body, which is on AIProviderException.Detail and logged at Debug. A rate limiter (WithRateLimiter) that would make a model call wait more than 30 seconds fails it with AIRateLimitException, which falls back like a 429. A cancellation of your own token throws OperationCanceledException.

The fallback

A model call goes to the next provider of its role's chain when the provider before it failed with an error marked "Falls back" above or a rule or setting refused it, when the request names no provider, and when IntentClientOptions.FallbackOnTransientErrors is true, as it is by default. A judge call never falls back. Each fallback logs a Warning, and the result's Provider names the provider that answered. A later provider asks for the call's FallbackModel, else its entry's fallbackModel, else its own model: a model the call names goes to the first provider only, since another vendor would refuse it.

One call can name its provider

// Only the provider named backup, with no fallback, on the model its entry names.
var options = new AIRequestOptions { Provider = "backup" };
var summary = await email.AIAsync(client, "Summarize this email in one sentence.", options);

A call that names a provider has no fallback, and an unknown name throws ArgumentException. An intent file's provider field does the same for every run; its model field does not turn fallback off. Role picks another role's chain for one call.

IntentClientBuilder.AddProvider adds providers that are reachable only by name: a call reaches one when AIRequestOptions.Provider, its intent's provider or a role of the provider file names it, and never otherwise. Such a provider never becomes the primary or the fallback and never joins a chain the client makes up itself. Names stay unique across every provider, ignoring case, and the client disposes these providers as it does the others. Under dependency injection, services.AddNamedProvider(provider) does the same; a registered IAIProvider keeps its meaning.

Write a provider of your own

A provider implements IAIProvider:

Member What it is
Name The name in results, logs, rate limiting, the roles and AIRequestOptions.Provider.
CompleteAsync(request, cancellationToken) Sends one AIRequest and returns one AIResponse.
RequestHost The host its requests go to, in lower case with no port, or null, the default, when it cannot say. A rule set that checks hosts refuses a provider that reports none.
GetRequestHost(request) Optional: the host of one request, for a provider that passes each request on to one of several others. By default it returns RequestHost.

A provider that embeds implements IEmbeddingProvider as well. CompleteAsync receives one attempt's request: SystemPrompt, Messages, Model (null when the call, the role and the file name none), MaxOutputTokens, Temperature (null to send none), Format and, for a typed result, JsonSchema and SchemaName. When Format is JsonSchema, the reply must match JsonSchema. Tags are for your own use; do not send them to the model. The AIResponse fills Content, Model, Provider and Usage, and sets IsTruncated when the output limit cut the reply off and IsRefusal when the model declined.

For an HTTP service, derive from HttpProviderBase, which brings the options, the retries and the table above: implement Authenticate, post with PostJsonAsync, and read the reply inside catch (Exception ex) when (IsMalformedReply(ex)) that throws MalformedReply(ex):

/// <summary>
/// A provider for a model service of your own that takes {model, system, messages, max_tokens, schema} at v1/complete
/// and answers {text, stop, input_tokens, output_tokens}.
/// </summary>
public sealed class InHouseModelProvider : HttpProviderBase
{
    public InHouseModelProvider(HttpProviderOptions options, HttpClient? httpClient = null, ILogger? logger = null)
        : base(options, httpClient, new Uri("https://models.internal.example.com/"), logger) { }

    public override string Name => "InHouse";

    protected override void Authenticate(HttpRequestMessage message)
        => message.Headers.Add("X-Api-Key", Options.ApiKey);

    public override async Task<AIResponse> CompleteAsync(AIRequest request, CancellationToken cancellationToken = default)
    {
        var body = new
        {
            model = request.Model ?? DefaultModel,
            system = request.SystemPrompt,
            messages = request.Messages.Select(m => new { role = m.Role, content = m.Content }),
            max_tokens = request.MaxOutputTokens,
            schema = request.Format == ResponseFormat.JsonSchema ? request.JsonSchema : null,
        };

        // Retries a 408, a 429, a 5xx and a transport error, and turns every failure into an IntentSharp provider exception.
        using var reply = await PostJsonAsync("v1/complete", body, cancellationToken);
        try
        {
            var root = reply.RootElement;
            var stop = root.GetProperty("stop").GetString();
            return new AIResponse
            {
                Content = root.GetProperty("text").GetString() ?? "",
                Model = request.Model ?? DefaultModel,
                Provider = Name,
                Usage = new TokenUsage(root.GetProperty("input_tokens").GetInt32(), root.GetProperty("output_tokens").GetInt32()),
                StopReason = stop,
                IsRefusal = stop == "refused",   // ends the call's attempts
                IsTruncated = stop == "length",  // fails this attempt
            };
        }
        catch (Exception ex) when (IsMalformedReply(ex))
        {
            // A reply without these fields fails the attempt, or falls back, instead of escaping the call.
            throw MalformedReply(ex);
        }
    }
}

Add it with UseProvider or UseFallbackProvider, and the provider file's roles can name it:

// The provider file's roles name it like an entry: "answer": ["InHouse", "main"].
var client = new IntentClientBuilder()
    .UseProviderOptions(store)
    .UseProvider(new InHouseModelProvider(new HttpProviderOptions { ApiKey = apiKey, Model = "house-large" }))
    .Build();

With no provider file, the providers added in code are the answer chain. For a kind that provider file entries create, implement IAIProviderFactory and add it with AddProviderFactory.

A provider of any kind reports a failure with IntentSharp's provider exceptions: AIProviderException (with isTransient true for a failure that may pass), AIRateLimitException, AIAuthenticationException, AIValidationException, AIProviderInternalException or AITimeoutException. Each ends the call with a Provider issue, and the transient ones go to the fallback. An AIConstraintException ends the call with a Constraint issue, and any other exception reaches your code. To test without a model, use ScriptedProvider (Testing).

Limits

  • The built-in kinds send one request per attempt and do not stream.
  • EmbedAsync uses the embedding role, else the first provider of answer that embeds, and returns null when none does.
  • Disposing a client disposes its providers, yours included, so give each client its own provider instances.