Skip to content

.NET: [Bug]: Error while trying to use Magentic Orchestration #5774

@marcominerva

Description

@marcominerva

Description

I'm trying to use the new Magentic Orchestration, but if I try to convert the Workflow as AIAgent, I systematically get the an error that says that Executor 'MagenticOrchestrator' cannot send messages of type 'Microsoft.Extensions.AI.ChatMessage'.:

Image

Code Sample

#!/usr/bin/env dotnet

#:sdk Microsoft.NET.Sdk

#:property OutputType=Exe
#:property TargetFramework=net10.0
#:property ImplicitUsings=enable
#:property Nullable=enable
#:property NoWarn=$(NoWarn);MEAI001;OPENAI001;MAAI001;MAAIW001
#:property PublishAot=false

#:package Microsoft.Agents.AI.OpenAI@1.5.0
#:package Microsoft.Agents.AI.Workflows@1.5.0

using System.ClientModel;
using System.ClientModel.Primitives;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Responses;

var apiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_APIKEY") ?? throw new InvalidOperationException("AZURE_OPENAI_APIKEY is not set.");
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-5.4-mini";

var openAIClient = new OpenAIClient(new ApiKeyCredential(apiKey), new()
{
    Endpoint = new(endpoint),
    Transport = new HttpClientPipelineTransport(new HttpClient(new TraceHttpClientHandler()))
});

var chatClient = openAIClient.GetResponsesClient().AsIChatClientWithStoredOutputDisabled(deploymentName);

var teamLeaderAgent = chatClient.AsAIAgent(new ChatClientAgentOptions
{
    Name = "OrchestratorAgent",
    ChatOptions = new()
    {
        Instructions = "You are a Team Leader of a .NET team. When you are asked to implement a feature, you need to delegate the task to the appropriate agents and then ensure the implementation meets the required standards after a code review.",
        Reasoning = new()
        {
            Effort = ReasoningEffort.Medium,
            Output = ReasoningOutput.Summary
        }
    }
});

var developerAgent = chatClient.AsAIAgent(new ChatClientAgentOptions
{
    Name = "DeveloperAgent",
    ChatOptions = new()
    {
        Instructions = "You are an experienced .NET developer. When you are requested to develop an algorigthm, you need to use web_search tool to find the correct way to implement it. You can use web_search also to check the correct available API. Always use .NET 10 and C# 14 features",
        Reasoning = new()
        {
            Effort = ReasoningEffort.Medium,
            Output = ReasoningOutput.Summary
        },
        Tools = [new HostedWebSearchTool()]
    }
});

var codeReviewerAgent = chatClient.AsAIAgent(new ChatClientAgentOptions
{
    Name = "CodeReviewerAgent",
    ChatOptions = new()
    {
        Instructions = "You are an expert in reviewing and validating .NET code. You can use web_search tool to gather information about the code you need to review.",
        Reasoning = new()
        {
            Effort = ReasoningEffort.Medium,
            Output = ReasoningOutput.Summary
        },
        Tools = [new HostedWebSearchTool()]
    }
});

var agent = new MagenticWorkflowBuilder(teamLeaderAgent).WithName("Developing Team")
    .AddParticipants([developerAgent, codeReviewerAgent]).RequirePlanSignoff(false)
    .Build().AsAIAgent(includeExceptionDetails: true);

var session = await agent.CreateSessionAsync();

while (true)
{
    Console.Write("Question: ");
    var question = Console.ReadLine()!;

    var response = await agent.RunAsync(question, session);
    Console.WriteLine(response);

    Console.WriteLine();
}

public class TraceHttpClientHandler : HttpClientHandler
{
    private static readonly JsonSerializerOptions jsonSerializerOptions = new()
    {
        WriteIndented = true,
        Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
    };

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var requestString = request.Content is null ? "(no request body)" : await request.Content.ReadAsStringAsync(cancellationToken);

        PrintText($"Raw Request ({request.RequestUri})", ConsoleColor.Green);
        PrintText(FormatJson(requestString), ConsoleColor.DarkGray);
        PrintSeparator();

        var response = await base.SendAsync(request, cancellationToken);

        var responseString = await response.Content.ReadAsStringAsync(cancellationToken);

        PrintText("Raw Response", ConsoleColor.Green);
        PrintText(FormatJson(responseString), ConsoleColor.DarkGray);
        PrintSeparator();

        return response;

        static void PrintText(string message, ConsoleColor color)
        {
            var originalColor = Console.ForegroundColor;
            Console.ForegroundColor = color;
            Console.WriteLine(message);
            Console.ForegroundColor = originalColor;
        }

        static void PrintSeparator() => Console.WriteLine(new string('-', 50));
    }

    private static string FormatJson(string input)
    {
        try
        {
            var jsonElement = JsonSerializer.Deserialize<JsonElement>(input);
            return JsonSerializer.Serialize(jsonElement, jsonSerializerOptions);
        }
        catch
        {
            return input;
        }
    }
}

Package Versions

Microsoft.Agents.AI.OpenAI: 1.5.0, Microsoft.Agents.AI.Workflows:1.5.0

.NET Version

.NET 10.0.7

Metadata

Metadata

Assignees

Labels

Type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions