Skip to content

Agent Config

AgentConfig is the serializable data class that holds all build-time agent configuration. It can be defined in C# or loaded from a JSON file, and passed into AgentBuilder as the base configuration.

csharp
var config = new AgentConfig
{
    Name = "SupportAgent",
    SystemInstructions = "You are a helpful support assistant.",
    Provider = new ProviderConfig
    {
        ProviderKey = "openai",
        ModelName = "gpt-4o",
        ApiKey = "sk-..."
    }
};

var agent = await new AgentBuilder(config)
    .WithServiceProvider(services)
    .BuildAsync();

Core Properties

PropertyTypeDefaultDescription
Namestring"HPD-Agent"Agent display name
SystemInstructionsstring"You are a helpful assistant."System prompt / persona
MaxAgenticIterationsint10Max tool-calling iterations per turn before a continuation is required
ContinuationExtensionAmountint3Extra iterations granted when the user continues past the limit
CoalesceDeltasboolfalseMerge streaming text/reasoning chunks into complete events instead of deltas
PreserveReasoningInHistoryboolfalseInclude extended reasoning tokens in conversation history
DefaultReasoningReasoningOptions?nullDefault reasoning effort/output applied to all calls

Provider

csharp
Provider = new ProviderConfig
{
    ProviderKey = "openai",        // "openai", "anthropic", "ollama", "azureai", etc.
    ModelName = "gpt-4o",
    ApiKey = "sk-...",             // Optional — resolved via ISecretResolver if null
    Endpoint = null,               // Custom endpoint (Azure OpenAI, self-hosted, etc.)
    CustomHeaders = new Dictionary<string, string>
    {
        ["X-Organization"] = "myorg"
    },
    ProviderOptionsJson = null,    // Provider-specific config as a JSON string
    AdditionalProperties = null    // Legacy key-value config (deprecated)
}

DefaultChatOptions on ProviderConfig is [JsonIgnore] — set it programmatically.

ProviderOptionsJson supports typed round-trip helpers:

csharp
config.Provider.SetTypedProviderConfig(new OpenAIProviderConfig { ... });
var typedConfig = config.Provider.GetTypedProviderConfig<OpenAIProviderConfig>();

See Providers for per-provider configuration.


Toolkits

Register toolkits by class name (string shorthand) or rich reference object:

csharp
// String shorthand
Toolkits = ["CalculatorToolkit", "FileToolkit"]

// Rich reference — restrict which functions are exposed, or pass toolkit config
Toolkits =
[
    new ToolkitReference { Name = "FileToolkit", Functions = ["ReadFile", "WriteFile"] },
    new ToolkitReference { Name = "SearchToolkit", Config = mySearchConfig }
]

In JSON:

json
{
    "Toolkits": [
        "CalculatorToolkit",
        { "Name": "FileToolkit", "Functions": ["ReadFile", "WriteFile"] }
    ]
}

Native C# toolkits (type references) must be registered via .WithToolkit<T>() on the builder.


Middlewares

Register middleware by class name or rich reference:

csharp
Middlewares = ["LoggingMiddleware", "RateLimitMiddleware"]

Middleware executes in the order listed. Native middleware types must be registered via .WithMiddleware<T>() on the builder.


Nested Config Sections

Each section is an optional nullable config class. All default to null (framework uses built-in defaults).

PropertyTypePurpose
ErrorHandlingErrorHandlingConfig?Retries, timeouts, error formatting
HistoryReductionHistoryReductionConfig?Conversation history summarization/trimming
AgenticLoopAgenticLoopConfig?Turn duration limits and parallel function caps
CachingCachingConfig?LLM response caching
CollapsingCollapsingConfigToolkit hierarchical collapse/expand (default: new CollapsingConfig { Enabled = true })
ObservabilityObservabilityConfig?Event sampling and circuit breaker
BackgroundResponsesBackgroundResponsesConfig?Long-running / async provider support
DocumentHandlingDocumentHandlingConfig?File attachment extraction settings
ToolSelectionToolSelectionConfig?Default tool calling mode
MessagesAgentMessagesConfigCustomizable system messages (default: new AgentMessagesConfig())
AudioAudioConfig?TTS/STT/VAD settings
ValidationValidationConfig?Provider validation on build
McpMcpConfig?Model Context Protocol configuration

Each section has its own reference page — see the links at the bottom of this page.

AgenticLoopConfig

PropertyTypeDefaultDescription
MaxTurnDurationTimeSpan?5 minutesMax wall-clock time for a single turn
MaxParallelFunctionsint?nullMax concurrent function executions (null = unlimited)
TerminateOnUnknownCallsboolfalseStop the turn if the model calls a function that doesn't exist

ToolSelectionConfig

PropertyTypeDefaultDescription
ToolModestring"Auto""Auto", "None", "RequireAny", or "RequireSpecific"
RequiredFunctionNamestring?nullFunction name to force-call when ToolMode = "RequireSpecific"

AgentMessagesConfig

Customise the messages the framework sends to the LLM for system events. All support placeholder substitution.

PropertyPlaceholdersDefault
MaxIterationsReached{maxIterations}"Maximum iteration limit reached ({maxIterations} iterations)..."
CircuitBreakerTriggered{toolName}, {count}"Circuit breaker triggered: '{toolName}' called {count} times..."
MaxConsecutiveErrors{maxErrors}"Exceeded maximum consecutive errors ({maxErrors})..."
PermissionDeniedDefault"Permission denied by user."

ValidationConfig

PropertyTypeDefaultDescription
EnableAsyncValidationboolfalseMake a network call to validate the API key during BuildAsync()
TimeoutMsint3000Validation request timeout in milliseconds
FailOnValidationErrorboolfalseThrow if validation fails (default: warn and continue)

McpConfig

PropertyTypeDefaultDescription
ManifestPathstring""Path to the MCP manifest file
Optionsobject?nullMCP-specific options (stored as object to avoid circular dependencies)

DocumentHandlingConfig

PropertyTypeDefaultDescription
DocumentTagFormatstring?nullCustom injection format string. null uses the built-in default ([ATTACHED_DOCUMENT[{0}]]...)
MaxFileSizeByteslong10 MBMaximum file size to process

Non-Serializable Properties

These exist on AgentConfig but are marked [JsonIgnore]. Set them programmatically:

PropertyTypeDescription
SessionStoreISessionStore?Durable session persistence
SessionStoreOptionsSessionStoreOptions?Auto-save timing
ServerConfiguredToolsIList<AITool>?Tools known to the server but not in ChatOptions
ConfigureOptionsAction<ChatOptions>?Dynamic ChatOptions transform per request
ChatClientMiddlewareList<Func<IChatClient, IServiceProvider?, IChatClient>>?Runtime wrappers around the IChatClient

Building from a JSON File

csharp
// One-liner: load, deserialize, and build
var agent = await AgentConfig.BuildFromFileAsync("agent-config.json");

// Or use the builder for runtime additions
var agent = await new AgentBuilder("agent-config.json")
    .WithServiceProvider(services)
    .WithToolkit<MyToolkit>()
    .BuildAsync();

See Also

Released under the MIT License.