Skip to main content

How to Get Structured Output from an Agent Inside a Microsoft Agent Framework Workflow in C#

· 13 min read
Jagdish Kumawat
Founder @ Dewiride

An agent inside a Microsoft Agent Framework workflow can hand the next step a typed C# object instead of text. This guide calls the agent with RunAsync<T> inside an executor, so the step after it receives a Feedback record and decides the reply in plain code.

Syntax​

Syntax
internal sealed partial class <ClassName>(AIAgent <agent>) : Executor("<executorId>")
{
[MessageHandler]
private async ValueTask<<TResult>> HandleAsync(<TInput> message, IWorkflowContext context, CancellationToken cancellationToken)
{
AgentResponse<<TResult>> response = await <agent>.RunAsync<<TResult>>(<prompt>, cancellationToken: cancellationToken);
return response.Result;
}
}
PartWhat it is
<ClassName>, <executorId>The executor's class and its id, as in any class-based executor.
AIAgent <agent>The agent, passed to the class's constructor.
<TInput> messageThe message this step receives, such as a text for the agent to read.
<TResult>The C# type you want back. Microsoft's guide says of RunAsync<T>: It accepts a generic type parameter that specifies the structured outputs type.
<prompt>The text the agent reads.
response.ResultThe answer as a <TResult> object. Its documentation: Gets the result value of the agent response as an instance of T.
cancellationTokenThe handler's cancellation token. Passing it on lets the agent's call be cancelled too.

RunAsync<T> is available on the AIAgent base class, so the executor's constructor can take a plain AIAgent. Returning response.Result from the handler sends the object to the next executor.

The Example​

A console app called FeedbackReplies answers customers' feedback about a café. Its first step, ReadMood, gives the feedback to an agent, which returns a Feedback record: how the customer feels (Happy, Neutral or Unhappy) and what the feedback is about. Its second step, WriteReply, is plain C#: it writes a reply for that mood. Two pieces of feedback run through the workflow, a happy one and an unhappy one.

The agent runs on a model deployment in Microsoft Foundry, gpt-5.6-luna here. The app calls the model once for each piece of feedback, so every run makes two model calls, which cost a little on your deployment.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.
  • A Microsoft Foundry project with a deployed chat model, and the Azure CLI signed in with az login.

Step 1: Create a Console App and Add the Packages​

In a terminal, in the folder where you keep your projects, run:

Terminal
dotnet new console -o FeedbackReplies
cd FeedbackReplies
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
dotnet add package Microsoft.Agents.AI.Workflows.Generators --version 1.28.0
dotnet add package Microsoft.Agents.AI.Foundry --version 1.28.0-preview.261106.1
dotnet add package Azure.Identity --version 1.21.0
Output (first command)
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/FeedbackReplies/FeedbackReplies.csproj:
Restore succeeded.
  • Microsoft.Agents.AI.Workflows has the workflow builder, executors and the code that runs a workflow.
  • Microsoft.Agents.AI.Workflows.Generators is the source generator that class-based executors need: it registers their [MessageHandler] methods while the project builds.
  • Microsoft.Agents.AI.Foundry connects Agent Framework to a Microsoft Foundry project. It's a preview package, 1.28.0-preview.261106.1.
  • Azure.Identity has AzureCliCredential, which signs in with your Azure CLI account.

The project file now has the four packages:

FeedbackReplies.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="Microsoft.Agents.AI.Foundry" Version="1.28.0-preview.261106.1" />
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.28.0" />
<PackageReference Include="Microsoft.Agents.AI.Workflows.Generators" Version="1.28.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

</Project>

Step 2: Create the Agent​

Replace everything in Program.cs with this, using your own project endpoint and model deployment:

Program.cs
using System.ComponentModel;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Workflows;

AIAgent moodReader = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(
model: "gpt-5.6-luna",
instructions: "You read a customer's feedback about a cafe and say how the customer feels and what it's about.",
name: "MoodReader");
  • AIProjectClient connects to your Foundry project at its endpoint, signed in through AzureCliCredential, your Azure CLI sign-in.
  • AsAIAgent creates an agent on that project with a model deployment, instructions and a name. Microsoft's structured output guide creates its agent the same way.
  • The instructions only describe the job. The shape of the answer comes from a C# type, next.

Step 3: Describe the Answer as a C# Type​

Add the type at the end of the file:

Program.cs (add at the end)
[Description("How a customer feels in one piece of feedback.")]
record Feedback(
[property: Description("How the customer feels.")] Mood Mood,
[property: Description("What the feedback is mostly about, in one to three lowercase words without 'the', such as 'coffee' or 'waiting time'.")] string Topic);

enum Mood { Happy, Neutral, Unhappy }
  • Feedback is the answer the next step needs: a Mood and a Topic. Mood is an enum with three values, Happy, Neutral and Unhappy.
  • [Description] describes the record and each of its properties. RunAsync<Feedback> asks the model for JSON that follows a schema made from Feedback, and these descriptions are part of that schema, so they tell the model what each property means. [property: ...] puts the attribute on the property that the record creates from that parameter.
  • The Topic description asks for one to three lowercase words, so topics come back short and easy to use in a sentence.

Step 4: Call the Agent Inside an Executor​

Add the first executor above the Feedback record:

Program.cs (above the Feedback record)
// Step 1: the agent reads the feedback and returns a Feedback object.
internal sealed partial class ReadMoodExecutor(AIAgent moodReader) : Executor("ReadMood")
{
[MessageHandler]
private async ValueTask<Feedback> HandleAsync(string text, IWorkflowContext context, CancellationToken cancellationToken)
{
AgentResponse<Feedback> response = await moodReader.RunAsync<Feedback>(text, cancellationToken: cancellationToken);
return response.Result;
}
}
  • (AIAgent moodReader) after the class name is a primary constructor: the executor receives the agent when it's created, and its method can use moodReader.
  • async ValueTask<Feedback> HandleAsync(string text, ...) accepts the feedback text, awaits the agent, and returns a Feedback. A [MessageHandler] method can take a CancellationToken as its third parameter, and this one passes it on to the agent.
  • moodReader.RunAsync<Feedback>(text, ...) runs the agent with the feedback and asks for a Feedback back. cancellationToken: is named because RunAsync<T> has three optional parameters before it: a session, serializer options and run options.
  • return response.Result sends the Feedback object, not text, to the next executor.

Why not add the agent to the workflow directly? You can, but then the workflow wraps it in an agent executor, which Sends the agent's response messages to all connected downstream executors. The next step would receive chat messages, not a Feedback. Calling the agent inside your own executor lets the step return any type you choose. Microsoft's conditional-edges example also calls an agent inside an executor: a spam-detection agent whose JSON answer the executor turns into an object.

Step 5: Write the Reply in Plain Code​

Add the second executor below ReadMoodExecutor:

Program.cs (below ReadMoodExecutor)
// Step 2: plain code writes the reply for that mood.
internal sealed partial class WriteReplyExecutor() : Executor("WriteReply")
{
[MessageHandler]
private string Handle(Feedback feedback, IWorkflowContext context) => feedback.Mood switch
{
Mood.Happy => $"Thank you! We're glad you enjoyed the {feedback.Topic}.",
Mood.Unhappy => $"We're sorry about the {feedback.Topic}. A manager will contact you today.",
_ => $"Thank you for telling us about the {feedback.Topic}.",
};
}

WriteReply accepts a Feedback, the type ReadMood returns, so the workflow hands the object straight to it. The switch expression picks a sentence by Mood, and the _ line covers the one that's left, Neutral. The model judges the feedback, and the code decides the reply, so every reply is one of three fixed sentences with the topic filled in.

Step 6: Connect the Steps and Run Two Pieces of Feedback​

Add this below the agent, above the classes:

Program.cs (below the agent)
ReadMoodExecutor readMood = new(moodReader);
WriteReplyExecutor writeReply = new();

Workflow workflow = new WorkflowBuilder(readMood)
.AddEdge(readMood, writeReply)
.WithOutputFrom(writeReply)
.Build();

string[] feedback =
[
"The flat white was perfect and the staff were lovely.",
"I waited 25 minutes and my sandwich arrived cold.",
];

foreach (string text in feedback)
{
await using Run run = await InProcessExecution.RunAsync(workflow, text);

foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
switch (workflowEvent)
{
case ExecutorCompletedEvent { ExecutorId: "ReadMood" } completed:
Console.WriteLine($"ReadMood returned: {completed.Data}");
break;
case WorkflowOutputEvent output:
Console.WriteLine($"Reply: {output.Data}");
break;
}
}
}
  • new(moodReader) gives ReadMood the agent. WriteReply needs nothing.
  • The workflow starts at ReadMood, sends its result to WriteReply, and takes its output from WriteReply.
  • The loop runs the workflow once for each piece of feedback.
  • ExecutorCompletedEvent { ExecutorId: "ReadMood" } matches only the event of the ReadMood executor, so the app prints the object the agent returned. The WorkflowOutputEvent carries the reply.

Step 7: Run It​

Terminal
dotnet run
Output
ReadMood returned: Feedback { Mood = Happy, Topic = coffee }
Reply: Thank you! We're glad you enjoyed the coffee.
ReadMood returned: Feedback { Mood = Unhappy, Topic = waiting time }
Reply: We're sorry about the waiting time. A manager will contact you today.

macOS-style terminal window titled Terminal — FeedbackReplies showing dotnet run printing ReadMood returned: Feedback with Mood Happy and Topic coffee, the reply Thank you! We're glad you enjoyed the coffee., then ReadMood returned: Feedback with Mood Unhappy and Topic waiting time, and the reply We're sorry about the waiting time. A manager will contact you today.

ReadMood returned a real Feedback object both times, printed the way C# prints a record. The flat white became Happy about coffee, and the cold sandwich after 25 minutes became Unhappy about waiting time, in the short form the Topic description asks for. WriteReply then chose each sentence by mood, without another model call.

Clean Up​

An agent made with AsAIAgent on a Foundry project uses the Responses API, and Foundry stores each response it creates. The run above left two responses in the project, one for each piece of feedback. Microsoft's Responses API guide gives the period: By default, response data is retained for 30 days. To remove a response sooner, delete it by its ID: How to Delete a Stored Response in Microsoft Foundry with the Azure CLI. To build an agent that stores nothing, see How to Keep Microsoft Foundry from Storing an Agent's Conversations in C#.

The Complete File​

Program.cs
using System.ComponentModel;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Workflows;

AIAgent moodReader = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(
model: "gpt-5.6-luna",
instructions: "You read a customer's feedback about a cafe and say how the customer feels and what it's about.",
name: "MoodReader");

ReadMoodExecutor readMood = new(moodReader);
WriteReplyExecutor writeReply = new();

Workflow workflow = new WorkflowBuilder(readMood)
.AddEdge(readMood, writeReply)
.WithOutputFrom(writeReply)
.Build();

string[] feedback =
[
"The flat white was perfect and the staff were lovely.",
"I waited 25 minutes and my sandwich arrived cold.",
];

foreach (string text in feedback)
{
await using Run run = await InProcessExecution.RunAsync(workflow, text);

foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
switch (workflowEvent)
{
case ExecutorCompletedEvent { ExecutorId: "ReadMood" } completed:
Console.WriteLine($"ReadMood returned: {completed.Data}");
break;
case WorkflowOutputEvent output:
Console.WriteLine($"Reply: {output.Data}");
break;
}
}
}

// Step 1: the agent reads the feedback and returns a Feedback object.
internal sealed partial class ReadMoodExecutor(AIAgent moodReader) : Executor("ReadMood")
{
[MessageHandler]
private async ValueTask<Feedback> HandleAsync(string text, IWorkflowContext context, CancellationToken cancellationToken)
{
AgentResponse<Feedback> response = await moodReader.RunAsync<Feedback>(text, cancellationToken: cancellationToken);
return response.Result;
}
}

// Step 2: plain code writes the reply for that mood.
internal sealed partial class WriteReplyExecutor() : Executor("WriteReply")
{
[MessageHandler]
private string Handle(Feedback feedback, IWorkflowContext context) => feedback.Mood switch
{
Mood.Happy => $"Thank you! We're glad you enjoyed the {feedback.Topic}.",
Mood.Unhappy => $"We're sorry about the {feedback.Topic}. A manager will contact you today.",
_ => $"Thank you for telling us about the {feedback.Topic}.",
};
}

[Description("How a customer feels in one piece of feedback.")]
record Feedback(
[property: Description("How the customer feels.")] Mood Mood,
[property: Description("What the feedback is mostly about, in one to three lowercase words without 'the', such as 'coffee' or 'waiting time'.")] string Topic);

enum Mood { Happy, Neutral, Unhappy }

macOS-style code window titled Program.cs — FeedbackReplies showing the MoodReader agent created on a Foundry project with gpt-5.6-luna, a two-step workflow from ReadMood to WriteReply run over two pieces of feedback, the ReadMoodExecutor class that awaits moodReader.RunAsync of Feedback and returns response.Result, the WriteReplyExecutor class that picks a reply by mood, and the Feedback record with its descriptions and the Mood enum

Common Mistakes​

MistakeWhat happensDo this instead
Adding the agent itself to the workflow when the next step needs a typed objectThe agent executor the workflow wraps it in sends the agent's response messages on, not your typeCall the agent inside your own executor with RunAsync<T>
Leaving out Microsoft.Agents.AI.Workflows.GeneratorsEach executor class fails to build with CS0534 (Fixed)Add it to the project that defines the executors
Declaring an executor class without partialMAFGENWF003, plus CS0534 for that class (Fixed)Declare it internal sealed partial class

FAQ​

Why not let the agent write the reply too?​

Because the reply follows fixed rules. Reading a mood from free text is the part that needs a model. Choosing a sentence for a mood is a lookup that code does the same way every time, so each reply says exactly what you wrote.

Does every agent support structured output?​

Not natively. Microsoft's structured output guide: Not all agent types support structured outputs natively. and The ChatClientAgent supports structured outputs when used with compatible chat clients. The agent here is created with AsAIAgent on a Foundry project, as in that guide.

Can the executor stream the agent's answer?​

It can, but a typed object needs the whole answer. Microsoft's guide says you can only deserialize the response once all the updates have been received. The streaming way to get one is in the post linked below.

Conclusion​

To get structured output from an agent inside a workflow, call the agent yourself in a class-based executor: pass it to the constructor, await RunAsync<T> in an async [MessageHandler] method, and return response.Result. The next executor receives a typed object, so plain code can decide what happens next.

Additional Resources​