Structured Output in Microsoft Agent Framework
The main idea of structured output is very simple:
Instead of allowing an LLM to return any text or JSON format it wants, we define the exact C# structure that the application expects and ask the agent framework to make the LLM follow that structure.
This is especially important in enterprise applications, where the output from an AI model needs to be consumed reliably by C# code.
1. Why Structured Output Is Important
LLMs are probabilistic.
That means the same prompt can potentially produce slightly different responses.
For example, suppose an application asks:
Extract the topic, action items and sentiment from this meeting.
Return the result as JSON.
The model might return:
{
"topic": "Q4 Marketing",
"actionItems": [
"Finalize budget",
"Contact ad agency"
],
"sentiment": "Optimistic"
}
But it could also return something like:
Sure, here is the JSON:
{
"Topic": "Q4 Marketing",
"Actions": [
"Finalize budget"
],
"Mood": "Positive"
}
For a human, this is understandable.
For a strongly typed C# application, this can cause problems.
The application may expect:
Topic
ActionItems
Sentiment
but receive:
Topic
Actions
Mood
Now the application has a contract mismatch.
2. Traditional Software vs LLM Output
Traditional enterprise software normally works with strict contracts.
For example:
C# Application
|
| HTTP Request
v
External API
|
| JSON
v
Strongly Typed C# Object
The application expects a predictable JSON structure.
For example:
{
"topic": "Q4 Marketing",
"actionItems": [
"Finalize budget",
"Contact ad agency"
],
"sentiment": "Optimistic"
}
The C# application can deserialize this into:
MeetingAnalysis
The problem is that an LLM doesn't naturally behave like a traditional deterministic API.
Structured output provides the bridge:
Unstructured Text
|
v
Agent
|
v
LLM
|
| Structured Output Contract
v
MeetingAnalysis
|
v
C# Application
3. What Is Structured Output?
Structured output means that the LLM response must follow a predefined structure.
For example, the application defines:
public record MeetingAnalysis(
string Topic,
string[] ActionItems,
string Sentiment
);
This tells the application that the expected result contains exactly these conceptual fields:
MeetingAnalysis
├── Topic
├── ActionItems[]
└── Sentiment
Instead of manually asking the LLM:
Please return JSON.
The property should be called topic.
The property should be called actionItems.
The property should be called sentiment.
Do not add any other properties.
the Agent Framework uses the C# type itself as the data contract.
That is the important concept in this example.
4. Data Contract
The transcript calls the C# record the data contract.
The code defines:
public record MeetingAnalysis(
[property: JsonPropertyName("topic")] string Topic,
[property: JsonPropertyName("actionItems")] string[] ActionItems,
[property: JsonPropertyName("sentiment")] string Sentiment
);
This record represents the structure expected from the AI.
Conceptually:
MeetingAnalysis
│
├── topic → string
├── actionItems → string[]
└── sentiment → string
This becomes the source of truth for the application's expected AI response.
5. Why Use a C# Record?
A record is useful for representing data.
For example:
public record MeetingAnalysis(
string Topic,
string[] ActionItems,
string Sentiment
);
This creates a data type whose purpose is primarily to hold related data.
For an AI response, this is a natural fit because the result is essentially data:
Topic
Action Items
Sentiment
The application doesn't need to manually construct this object.
The Agent Framework creates it from the model response.
6. What Does JsonPropertyName Do?
The code uses:
[property: JsonPropertyName("topic")]
This comes from:
using System.Text.Json.Serialization;
It tells the JSON serializer that the JSON property should be named:
"topic"
even though the C# property is:
Topic
Similarly:
[property: JsonPropertyName("actionItems")]
maps:
C# JSON
---------------------------
Topic ---> topic
ActionItems ---> actionItems
Sentiment ---> sentiment
So the expected JSON structure is approximately:
{
"topic": "...",
"actionItems": [
"...",
"..."
],
"sentiment": "..."
}
The important point is that the C# data contract describes the expected output format.
7. The Azure OpenAI Client
The first part of the application retrieves configuration:
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-mini";
There are two important values here.
Endpoint
AZURE_OPENAI_ENDPOINT
This identifies the Azure OpenAI resource endpoint.
Deployment Name
AZURE_OPENAI_DEPLOYMENT_NAME
This identifies the model deployment that should process the request.
The code uses an environment variable rather than hard-coding these values.
That is preferable for configuration and security.
8. Creating the Azure OpenAI Client
The next code is:
new AzureOpenAIClient(
new Uri(endpoint),
new AzureCliCredential()
)
AzureOpenAIClient comes from:
using Azure.AI.OpenAI;
It represents the client used to communicate with Azure OpenAI.
The second parameter is:
new AzureCliCredential()
This comes from:
using Azure.Identity;
It allows authentication using Azure CLI credentials.
For example, after authenticating with:
az login
the application can use the Azure CLI identity.
Conceptually:
Application
|
v
AzureCliCredential
|
v
Azure Authentication
|
v
Azure OpenAI
9. Getting the Chat Client
The code then calls:
.GetChatClient(deploymentName)
This obtains the chat client associated with the specified Azure OpenAI deployment.
The result is then converted to an AI abstraction:
.AsAIAgent(...)
So the flow is:
AzureOpenAIClient
|
v
GetChatClient()
|
v
IChatClient
|
v
AsAIAgent()
|
v
AIAgent
This allows the application to work with the Microsoft Agent Framework abstraction.
10. Creating the Agent
The agent is created with:
AIAgent meetingAgent = ...
The agent is given a name:
name: "MeetingAnalyst"
and instructions:
instructions:
"You are an AI analyst. Extract the topic, action items, and overall sentiment from the provided transcript."
Notice something very important.
There is no JSON format instruction here.
There is no:
Return JSON.
There is no:
Use these property names...
There is no manually written JSON schema in the prompt.
The instruction only describes the semantic task:
Extract the topic, action items, and sentiment.
The structured-output requirement comes from the C# type used later.
11. The Agent Instruction vs Data Contract
These two things have different responsibilities.
Agent instructions
Tell the model what to do.
Extract:
- topic
- action items
- sentiment
Data contract
Defines what the result must look like.
MeetingAnalysis
So:
Instructions
|
| What should the AI do?
v
LLM
^
|
| What structure must the result have?
|
Data Contract
This separation is very useful in enterprise applications.
12. The Unstructured Transcript
The application receives a normal text transcript:
string transcript =
"We discussed the Q4 marketing push. Sarah needs to finalize the budget by Tuesday. John will contact the ad agency. Overall, everyone felt very optimistic about the campaign.";
This is unstructured input.
It is just a normal string.
Conceptually:
"We discussed the Q4 marketing push.
Sarah needs to finalize the budget by Tuesday.
John will contact the ad agency.
Overall, everyone felt very optimistic..."
The AI needs to extract useful structured information from this text.
13. The Critical Line: RunAsync<T>
This is the most important line in the entire example:
AgentResponse<MeetingAnalysis> response =
await meetingAgent.RunAsync<MeetingAnalysis>(transcript);
The important part is:
RunAsync<MeetingAnalysis>
The generic type:
MeetingAnalysis
tells the Agent Framework:
The expected result from this agent execution is a
MeetingAnalysis.
This is where the structured-output mechanism becomes important.
14. What Happens Internally?
Conceptually, the framework performs something similar to this:
C# Record
|
| MeetingAnalysis
v
Framework examines the type
|
v
Creates structured schema
|
v
Provides schema to the LLM
|
v
LLM generates response
|
v
Response follows required structure
|
v
Framework deserializes response
|
v
MeetingAnalysis object
The application doesn't need to manually write the JSON schema.
It also doesn't need to manually deserialize the response.
15. Without Structured Output
Without this mechanism, an application might have to do something like:
string response = await CallLLM();
var json = ExtractJson(response);
var analysis =
JsonSerializer.Deserialize<MeetingAnalysis>(json);
There are multiple problems.
The model might return:
Sure! Here is your JSON:
{
...
}
Now the application has to find the actual JSON.
The model could also change property names.
Or it could produce invalid JSON.
Or it could add unexpected text.
This creates additional error-handling code.
16. With Structured Output
With:
await meetingAgent.RunAsync<MeetingAnalysis>(transcript);
the framework handles the structured-response mechanism.
The application receives:
AgentResponse<MeetingAnalysis>
and then:
MeetingAnalysis? analysis = response.Result;
Now analysis is a strongly typed C# object.
17. Strongly Typed Result
The code accesses:
analysis.Topic
analysis.Sentiment
and:
analysis.ActionItems
The compiler knows the types.
For example:
analysis.Topic
is:
string
and:
analysis.ActionItems
is:
string[]
This is much safer than working with:
Dictionary<string, object>
or:
JsonDocument
or raw strings.
18. Understanding AgentResponse<MeetingAnalysis>
This:
AgentResponse<MeetingAnalysis>
means the agent response is associated with a MeetingAnalysis result.
The generic parameter:
<MeetingAnalysis>
provides the expected result type.
Then:
response.Result
provides the actual typed result.
So the flow is:
RunAsync<MeetingAnalysis>()
|
v
AgentResponse<MeetingAnalysis>
|
v
response.Result
|
v
MeetingAnalysis
19. Why There Is No Manual Deserialization
Normally, JSON processing might look like:
var analysis =
JsonSerializer.Deserialize<MeetingAnalysis>(json);
But the example doesn't do this.
Instead:
MeetingAnalysis? analysis = response.Result;
The Agent Framework handles the conversion.
That is one of the major benefits of the structured-output API.
20. Working with the Result
The code checks:
if (analysis != null)
This ensures that the result exists before accessing its properties.
Then:
Console.WriteLine($"Topic: {analysis.Topic}");
prints the topic.
And:
Console.WriteLine($"Sentiment: {analysis.Sentiment}");
prints the overall sentiment.
For action items:
Console.WriteLine($"Action Items Count: {analysis.ActionItems.Length}");
Length gives the number of items in the array.
Then:
foreach (var item in analysis.ActionItems)
{
Console.WriteLine($"- {item}");
}
iterates through every action item.
21. Expected Result
For the supplied transcript, the model could produce a structured result conceptually similar to:
{
"topic": "Q4 marketing campaign",
"actionItems": [
"Sarah needs to finalize the budget by Tuesday",
"John will contact the ad agency"
],
"sentiment": "Optimistic"
}
The application then receives the equivalent C# object:
MeetingAnalysis
Topic = "Q4 marketing campaign"
ActionItems = ["Sarah needs...", "John will..."]
Sentiment = "Optimistic"
The important difference is that the application works with the C# object, not with raw JSON text.
22. Why This Is Useful for Enterprise Applications
Imagine an enterprise application that processes:
- Customer support tickets
- Meeting transcripts
- Insurance claims
- Product reviews
- Job applications
- Invoice information
- Customer feedback
- Security alerts
- Email classification
- Document analysis
The input may be completely unstructured:
Large amount of natural language
But the application needs deterministic information:
Category
Priority
Customer
ActionItems
Confidence
Status
Structured output creates this bridge:
Unstructured Data
|
v
AI
|
v
Structured Contract
|
v
Strongly Typed C#
|
v
Business Logic
|
v
Database / API / Workflow
This is one of the most important patterns when integrating generative AI into existing enterprise systems.
23. POCO vs Record
The transcript says you can create a C# POCO or record.
For example, a class could be:
public class MeetingAnalysis
{
public string Topic { get; set; } = "";
public string[] ActionItems { get; set; } = [];
public string Sentiment { get; set; } = "";
}
Or a record:
public record MeetingAnalysis(
string Topic,
string[] ActionItems,
string Sentiment
);
Both can represent the data contract.
The example chooses a record because the result is primarily a data structure.
24. Why the Framework Is Better Than Prompt Engineering Alone
A weak approach would be:
Please return JSON.
The JSON must contain:
topic
actionItems
sentiment
Do not add any additional text.
This is still relying heavily on the model following instructions.
Structured output moves the requirement into the application/framework contract.
Instead of:
Prompt says:
"Please follow this JSON format."
the application says:
RunAsync<MeetingAnalysis>()
This makes the expected structure explicit in the program.
25. Important Distinction: Structured Input vs Structured Output
This example is specifically about structured output.
The input is:
string transcript
which is unstructured natural language.
The output is:
MeetingAnalysis
which is structured.
Therefore:
INPUT
--------------------------------
"We discussed the Q4 marketing
push. Sarah needs to finalize..."
|
v
AGENT
|
v
LLM
|
v
OUTPUT
--------------------------------
MeetingAnalysis
Topic
ActionItems[]
Sentiment
That is the core pattern.
26. JsonPropertyName Is Not the Same as Prompt Instructions
This is an important detail.
The following:
[property: JsonPropertyName("actionItems")]
doesn't tell the AI what an action item means.
It defines the JSON property name.
The instruction:
Extract the topic, action items, and overall sentiment
defines the semantic task.
So they work together:
Agent Instructions
|
| Meaning
v
"Find action items"
Data Contract
|
| Structure
v
"actionItems": string[]
27. The Complete Execution Flow
The entire application can be understood in seven steps:
1. Get Azure OpenAI configuration
|
v
2. Create AzureOpenAIClient
|
v
3. Create AIAgent
|
v
4. Define MeetingAnalysis contract
|
v
5. Send transcript to RunAsync<MeetingAnalysis>()
|
v
6. Framework enforces structured output
|
v
7. Receive MeetingAnalysis object
Or in a more architectural view:
Azure OpenAI
|
v
+----------------+
| LLM |
+----------------+
^
|
Structured Schema
^
|
+----------------+ |
| C# Application |-------+
| |
| MeetingAnalysis|
+----------------+
^
|
|
AgentResponse<T>
^
|
RunAsync<T>
28. The Most Important Code to Remember
If learning this example for practical Agentic AI development, focus especially on these three pieces.
1. Define the contract
public record MeetingAnalysis(
[property: JsonPropertyName("topic")] string Topic,
[property: JsonPropertyName("actionItems")] string[] ActionItems,
[property: JsonPropertyName("sentiment")] string Sentiment
);
2. Execute with the generic type
await meetingAgent.RunAsync<MeetingAnalysis>(transcript);
3. Access the strongly typed result
MeetingAnalysis? analysis = response.Result;
Together:
MeetingAnalysis
|
v
RunAsync<MeetingAnalysis>()
|
v
AgentResponse<MeetingAnalysis>
|
v
response.Result
|
v
Strongly Typed C# Object
This is the central concept of the entire example.
Synchronous vs Streaming
The transcript also briefly mentions that structured output can be used with streaming.
The example shown uses:
RunAsync<T>()
which is the straightforward approach when the application wants the completed structured result.
The important concept remains the same:
C# Type
↓
Structured Schema
↓
LLM
↓
Structured Response
↓
C# Type
The difference with streaming is mainly how the response is delivered over time, rather than changing the fundamental purpose of structured output.
Final Summary
Structured output solves a fundamental problem when connecting probabilistic LLMs with deterministic enterprise applications.
The application defines a C# contract:
MeetingAnalysis
The Agent Framework uses that type to establish the expected response structure. The agent is then executed with:
RunAsync<MeetingAnalysis>()
Instead of receiving an arbitrary string that must be manually parsed, the application receives:
AgentResponse<MeetingAnalysis>
and can directly access:
response.Result.Topic
response.Result.ActionItems
response.Result.Sentiment
So the key idea to remember is:
Use the C# type as the contract, pass that type to
RunAsync<T>, and let the Agent Framework handle structured generation and deserialization.
Complete Code
using System.Text.Json.Serialization;
using Azure.Identity;
using Azure.AI.OpenAI;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
// 1. Define the variables we extracted from Microsoft Foundry
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-mini";
// 2. Initialize the Agent from AzureOpenAIClient via IChatClient
AIAgent meetingAgent =
new AzureOpenAIClient(
new Uri(endpoint),
new AzureCliCredential())
.GetChatClient(deploymentName)
.AsAIAgent(
name: "MeetingAnalyst",
instructions:
"You are an AI analyst. Extract the topic, action items, and overall sentiment from the provided transcript."
);
// 3. Execute the Agent with RunAsync<T> for strongly-typed structured output
string transcript =
"We discussed the Q4 marketing push. Sarah needs to finalize the budget by Tuesday. John will contact the ad agency. Overall, everyone felt very optimistic about the campaign.";
Console.WriteLine(
$"Analyzing Transcript:\n{transcript}\n");
AgentResponse<MeetingAnalysis> response =
await meetingAgent.RunAsync<MeetingAnalysis>(
transcript);
// 4. Access the strongly-typed Result directly
// No manual JSON deserialization is needed
MeetingAnalysis? analysis = response.Result;
// 5. Utilize deterministic C# objects
if (analysis != null)
{
Console.WriteLine(
$"Full Analysis: {analysis}\n");
Console.WriteLine(
$"Topic: {analysis.Topic}");
Console.WriteLine(
$"Sentiment: {analysis.Sentiment}");
Console.WriteLine(
$"Action Items Count: {analysis.ActionItems.Length}");
Console.WriteLine(
$"Action Items:");
foreach (var item in analysis.ActionItems)
{
Console.WriteLine($"- {item}");
}
}
// Data Contract
public record MeetingAnalysis(
[property: JsonPropertyName("topic")]
string Topic,
[property: JsonPropertyName("actionItems")]
string[] ActionItems,
[property: JsonPropertyName("sentiment")]
string Sentiment
);