Providers, Clients, And Secrets
Providers connect an HPD agent to model clients. A provider package registers a provider key, such as openai, anthropic, or ollama, and the application's generated provider composition collects the providers of every referenced provider package. The agent configuration chooses a client family, usually Clients.Chat, and points that family at a provider key plus a model name.
The same resolution model applies across providers:
- A fluent
AgentConfighelper such asWithOpenAI(...)writes aChatClientConfigintoAgentConfig.Clients.Chat. AgentRuntimeBuilder.BuildAsync()checks that each code agent names a provider of the composition and creates the secret-resolver chain. It does not create the chat client or resolve its credential.- Each
RunAsync(...)resolves an effective provider, model, endpoint, construction options, request options, and authentication selection. - The runtime lazily acquires and leases the matching chat client. Equivalent runs reuse a cached client; different construction identities acquire different clients.
For most applications, prefer fluent setup:
using HPD.Agent;
using HPD.Agent.Providers.OpenAI;
var assistant = new AgentConfig()
.WithOpenAI(model: "gpt-5-mini")
.WithInstructions("You are a concise helpful assistant.");
await using var runtime = await new AgentRuntimeBuilder()
.AddAgent("assistant", assistant)
.BuildAsync();
var result = await runtime.RunAsync("Say hello in one sentence.");
Console.WriteLine(result.Text);Configuration-based setup uses the same model, but writes the client selection directly:
{
"clients": {
"chat": {
"provider": {
"key": "openai"
},
"modelName": "gpt-4o"
}
}
}Current configuration belongs under Clients, with Clients.Chat for the primary chat model.
The Provider Composition
The providers a runtime can use are the providers of the application's generated provider composition: one per referenced provider package. runtime.Composition.Providers lists them as ProviderDescriptor values (key, display name, aliases, client families, documentation link, secret names, and models), without building an agent or reading storage.
A definition whose clients.{family}.provider.key names no provider of the composition (matched by key or alias, ignoring case) is refused with agent_provider_unknown: at BuildAsync() for a code agent, and when a stored definition is created or updated. A provider that does not implement the family is refused with agent_provider_family_unsupported. Reference the provider package to add a provider.
WithChatClient(client) puts an existing IChatClient on the definition instead. It is a process-local part of the definition: every agent the runtime builds from that definition uses it, and the definition cannot be stored.
Client Families
AgentConfig.Clients has separate slots for different model client families:
ChatTextToSpeechSpeechToTextRealtimeImageGenerationEmbeddingsHostedFilesVoiceActivityDetectionEndOfTurnDetection
Provider setup pages focus first on Clients.Chat. Some provider packages expose additional families. See Provider Families for the broader client-family model.
The family slot matters as much as the provider key. openai can mean chat, text-to-speech, speech-to-text, realtime, image generation, embeddings, or hosted files depending on the slot and referenced provider packages. elevenlabs can mean speech-to-text or text-to-speech, but not chat. A provider key is not a promise that every family exists.
Provider selection does not replace the HPD runtime. The same AgentRuntime still owns RunAsync(...), tools, middleware, sessions, threads, events, permissions, compaction, hosting, and stored definitions.
Selection, Construction, And Request Options
Provider selection identifies the provider, model, endpoint, and optional named authentication registration. The agent definition supplies defaults; AgentRunConfig can replace them for one invocation.
Construction configuration is for values bound when a client is created, such as deployments, regions, API versions, SDK connection settings, and other provider-native constructor inputs. It is stored in the typed ProviderConfig payload on the selected family. Credentials are not provider configuration and are never serialized there.
Shared chat behavior and provider/model selection live together on ChatClientConfig. Agent defaults use AgentConfig.Clients.Chat; a complete per-invocation replacement uses AgentRunConfig.Clients.Chat.
Use ChatClientConfig for serializable chat controls:
- model selection
- temperature, top-p, top-k, seed, max output tokens, and stop sequences
- response format and structured-output shape
- generic reasoning options
Use the normal HPD tool registration APIs for model-callable tools. Advanced in-process integrations can still use MEAI ChatOptions where HPD exposes runtime-only hooks for non-serializable objects.
Use construction options for:
- provider-native service tiers, regions, deployments, hosted resource ids, or SDK connection settings
- provider-native content handling such as prompt-cache markers
- audio-specific voice, format, speed, transcript, or realtime settings
- advanced API controls that do not have a generic MEAI/HPD chat option
In C#, assign the provider package's typed configuration to ProviderConfig. In JSON or YAML, put the provider-specific object under providerConfig. Request-only provider settings belong under the typed providerOptions payload.
Runtime Provider And Model Selection
One agent can use different chat providers and models on consecutive or concurrent runs:
await runtime.RunAsync("Use OpenAI", runConfig: new AgentRunConfig
{
Clients = new AgentClientsConfig
{
Chat = new ChatClientConfig
{
Provider = new ProviderReference { Key = "openai" },
ModelName = "gpt-5-mini"
}
}
});
await runtime.RunAsync("Use Anthropic", runConfig: new AgentRunConfig
{
Clients = new AgentClientsConfig
{
Chat = new ChatClientConfig
{
Provider = new ProviderReference { Key = "anthropic" },
ModelName = "claude-sonnet-4-5"
}
}
});AgentRunConfig.Clients.Chat is the complete run-level chat replacement. Its provider key, model, portable chat controls, authentication selection, typed provider configuration, and typed provider options travel as one coherent unit. An explicitly supplied runtime client remains a runtime-only override. HPD fails when a provider key contradicts the provider-owned payload types; it never silently ignores the mismatch.
Secret Resolution
A literal key passed to a provider method, such as WithOpenAI(model, apiKey) or WithProvider(key, model, apiKey), is used for that definition's client. Every other secret is read through the resolver chain that BuildAsync() creates and retains:
- environment variables, including each provider's documented aliases
- resolvers added with
AddSecretResolver(...), in order - the application configuration:
appsettings.json, the entry assembly's user secrets, and environment variables
WithSecretResolver(...) replaces the whole chain with one custom resolver. To resolve from an IConfiguration the application already has, add AddSecretResolver(new ConfigurationSecretResolver(configuration)).
A literal key is a process-local part of the definition (ExplicitApiKeyProviderAuthentication.FromLiteral): HPD copies it, registers it in the runtime's secret registry when an agent with the definition is built, and clears it when the runtime is disposed. It is never stored or serialized, so a definition carrying one cannot be saved to the agent store. Portable authentication publishes only a secret key, account reference, or external-identity name; credential material is never serialized. Do not put credentials in ProviderConfig or custom headers.
Environment variables are the usual deployment path. Configuration lookup also supports provider-scoped keys such as:
openai:ApiKey
Providers:openai:ApiKeyConfiguration capitalization is mechanical. Prefer the exact provider key in docs and examples unless a provider page lists a specific alias.
Secret resolution happens when a run first needs a provider client, not during BuildAsync() or while the agent is built. This means an application can build a runtime without a credential, and a configured default that is never selected never contacts its provider.
Setup Failures
Client setup failures use the same structured contract across providers. A provider configuration, model, local model path, client-family, or payload problem throws ClientSetupException. Credential and authorization failures throw ProviderAuthenticationException. Both implement IClientSetupFailure and expose a ClientSetupDiagnostic.
The diagnostic includes a stable Code, safe Message, optional Guidance, and relevant context such as the client family, provider, backend, model, configuration path, and individual provider validation issues. Read those fields directly; do not classify failures by matching message text.
RunAsync(...) still throws these failures to a direct caller after recording the turn failure. A console or other direct host must catch the exception when it wants to remain alive:
using HPD.Agent.Providers;
try
{
await runtime.RunAsync("Say hello.");
}
catch (Exception exception) when (exception is IClientSetupFailure setupFailure)
{
var diagnostic = setupFailure.Diagnostic;
Console.Error.WriteLine($"[{diagnostic.Code}] {diagnostic.Message}");
if (!string.IsNullOrWhiteSpace(diagnostic.Guidance))
Console.Error.WriteLine(diagnostic.Guidance);
}Hosted event observers receive the same safe details on MessageTurnErrorEvent.ClientSetup. Provider authors return ProviderValidationIssue values from ValidateConfiguration(...); each issue has a stable code, configuration path, safe message, and optional guidance.
Selecting A Static Credential
Use the portable authentication union on ProviderReference when a host has independently selectable credentials such as personal, work, or tenant-specific API keys. The selection contains a secret-resolver key, never the secret value:
using HPD.Agent;
using HPD.Agent.Providers;
await runtime.RunAsync("Use the work credential", runConfig: new AgentRunConfig
{
Clients = new AgentClientsConfig
{
Chat = new ChatClientConfig
{
Provider = new ProviderReference
{
Key = "openai",
Authentication = new ApiKeyProviderAuthentication
{
SecretKey = "openai:work:ApiKey"
}
},
ModelName = "gpt-5-mini"
}
}
});The host must register the corresponding secret with its ISecretResolver. The serialized configuration contains the secret key, not the resolved value. OAuthProviderAuthentication selects a durable authorization account, and ExternalIdentityProviderAuthentication selects an SDK-native identity registered by the host.
Setup Caveats
Provider creation can resolve secrets from environment variables or configuration. These are the practical setup boundaries:
| Setup path | Behavior |
|---|---|
| OpenAI, Azure OpenAI, Anthropic, Google AI, Hugging Face, Mistral | Env-backed fluent setup works when the documented environment variable is present. OpenAI and Anthropic also support env-backed Clients.Chat JSON setup. Missing credentials fail when a run first acquires that provider client, not during BuildAsync(). |
| Bedrock | Region env such as AWS_REGION / AWS_DEFAULT_REGION is accepted; credentials normally flow through the AWS SDK default credential chain. |
| Ollama | OLLAMA_ENDPOINT / OLLAMA_HOST apply to fluent .WithOllama(...); JSON/config setup should include Endpoint when not using localhost. |
Catch IClientSetupFailure at a direct host boundary and present its ClientSetupDiagnostic. Do not add a second provider-specific diagnostic system or infer missing credentials from an opaque custom client.