microsoft/semantic-kernel · error · InvalidOperationException

Unable to create agent

Error message

Unable to create agent

What it means

AzureAIAgentFactory.CreateAgentFromYamlAsync returns Task<Agent?> — a nullable Agent. It parses YAML into an AgentDefinition, then delegates to AgentFactory.CreateAsync, which returns null if no registered factory can handle the agent definition's Type. The ?? throw converts that null into an InvalidOperationException. The YAML 'type' field (e.g., 'foundry_agent') must match a type the factory recognizes.

Source

Thrown at dotnet/samples/GettingStartedWithAgents/AzureAIAgent/Step08_AzureAIAgent_Declarative.cs:385

                    description: The topic of the story.
                    required: true
                    default: Cats
                length:
                    description: The number of sentences in the story.
                    required: true
                    default: 2
            outputs:
                output1:
                    description: output1 description
            template:
                format: semantic-kernel
            """;
        AzureAIAgentFactory factory = new();
        var promptTemplateFactory = new KernelPromptTemplateFactory();

        var agent =
            await factory.CreateAgentFromYamlAsync(text, new() { Kernel = this._kernel }, TestConfiguration.ConfigurationRoot) ??
            throw new InvalidOperationException("Unable to create agent");

        var options = new AgentInvokeOptions()
        {
            KernelArguments = new()
            {
                { "topic", "Dogs" },
                { "length", "3" },
            }
        };

        Microsoft.SemanticKernel.Agents.AgentThread? agentThread = null;
        try
        {
            await foreach (var response in agent!.InvokeAsync(Array.Empty<ChatMessageContent>(), agentThread, options))
            {
                agentThread = response.Thread;
                this.WriteAgentChatMessage(response);
            }

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Ensure the YAML 'type' field is set to the correct value for AzureAIAgentFactory (e.g., 'foundry_agent').
  2. Verify TestConfiguration.ConfigurationRoot contains the required AzureAI configuration section referenced by ${...} tokens.
  3. Check that the YAML is valid and the AgentDefinitionYaml parser consumed it without error (log the parsed AgentDefinition before the null check).
  4. If using a custom factory, ensure your agent type is registered in the factory's Types collection.

Example fix

// before
var agent =
    await factory.CreateAgentFromYamlAsync(text, new() { Kernel = this._kernel }, TestConfiguration.ConfigurationRoot) ??
    throw new InvalidOperationException("Unable to create agent");

// after — surface the parsed definition and type for diagnosis
var agent = await factory.CreateAgentFromYamlAsync(text, new() { Kernel = this._kernel }, TestConfiguration.ConfigurationRoot);
if (agent is null)
    throw new InvalidOperationException(
        $"Unable to create agent. YAML type: '{parsedType}'. Registered factory types: {string.Join(", ", factory.Types)}. " +
        "Verify the 'type' field in your YAML and the AzureAI configuration section.");
Defensive patterns

Strategy: validation

Validate before calling

// Validate YAML type and configuration before calling the factory
var agentDefinition = AgentDefinitionYaml.FromYaml(text, configuration);
if (string.IsNullOrWhiteSpace(agentDefinition.Type))
    throw new InvalidOperationException("YAML 'type' field is missing or empty.");
if (!factory.Types.Contains(agentDefinition.Type))
    throw new InvalidOperationException($"Agent type '{agentDefinition.Type}' not registered. Registered: {string.Join(", ", factory.Types)}");

Try / catch

try { var agent = await factory.CreateAgentFromYamlAsync(text, options, config); if (agent is null) logger.LogWarning("Factory returned null for YAML type '{Type}'.", parsedType); } catch (Exception ex) { logger.LogError(ex, "Agent creation failed."); throw; }

Prevention

When it happens

Trigger: The YAML's 'type' field is missing, misspelled, or set to a value not registered with the AzureAIAgentFactory; the AgentDefinitionYaml parser couldn't determine the type and the factory's Types collection is empty or doesn't contain the YAML's type; the configuration root is missing required model/credential keys referenced by ${...} tokens in the YAML.

Common situations: YAML 'type' field doesn't match the AzureAIAgentFactory's expected type string; using AzureAIAgentFactory with a YAML meant for OpenAIAssistantAgentFactory or ChatCompletionAgentFactory; TestConfiguration.ConfigurationRoot is null or missing the AzureAI section; YAML syntax errors that cause partial parsing; version mismatch where the factory's type registry changed.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/ae7ba78c63c2a938. Report an issue: GitHub.