-
Notifications
You must be signed in to change notification settings - Fork 1.2k
.NET: Add decorator for structured output support #3694
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
SergeyMenshykh
merged 4 commits into
microsoft:feature-so
from
SergeyMenshykh:add-so-decorator
Feb 5, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
34be0ef
add decorator that adds structured output support to agents that don'…
SergeyMenshykh e849bb4
Update dotnet/src/Microsoft.Agents.AI/StructuredOutput/StructuredOutp…
SergeyMenshykh 0725aae
Update dotnet/samples/GettingStarted/Agents/Agent_Step05_StructuredOu…
SergeyMenshykh 8102b8d
address pr review feedback
SergeyMenshykh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52
dotnet/samples/GettingStarted/Agents/Agent_Step05_StructuredOutput/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| # Structured Output with ChatClientAgent | ||
|
|
||
| This sample demonstrates how to configure ChatClientAgent to produce structured output in JSON format using various approaches. | ||
|
|
||
| ## What this sample demonstrates | ||
|
|
||
| - **ResponseFormat approach**: Configuring agents with JSON schema response format via `ChatResponseFormat.ForJsonSchema<T>()` for inter-agent communication or when the type is not known at compile time | ||
| - **Generic RunAsync<T> method**: Using the generic `RunAsync<T>` method for structured output when the caller needs to work directly with typed objects | ||
| - **Structured output with Streaming**: Using `RunStreamingAsync` to stream responses while still obtaining structured output by assembling and deserializing the streamed content | ||
| - **StructuredOutput middleware**: Adding structured output support to agents that don't natively support it (like A2A agents or models without structured output capability) by transforming text output into structured data using a chat client | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| Before you begin, ensure you have the following prerequisites: | ||
|
|
||
| - .NET 10 SDK or later | ||
| - Azure OpenAI service endpoint and deployment configured | ||
| - Azure CLI installed and authenticated (for Azure credential authentication) | ||
| - User has the `Cognitive Services OpenAI Contributor` role for the Azure OpenAI resource | ||
|
|
||
| **Note**: This sample uses Azure OpenAI models. For more information, see [how to deploy Azure OpenAI models with Azure AI Foundry](https://learn.microsoft.com/en-us/azure/ai-foundry/how-to/deploy-models-openai). | ||
|
|
||
| **Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure OpenAI resource and have the `Cognitive Services OpenAI Contributor` role. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively). | ||
|
|
||
| ## Environment Variables | ||
|
|
||
| Set the following environment variables: | ||
|
|
||
| ```powershell | ||
| $env:AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/" # Replace with your Azure OpenAI resource endpoint | ||
| $env:AZURE_OPENAI_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini | ||
| ``` | ||
|
|
||
| ## Run the sample | ||
|
|
||
| Navigate to the sample directory and run: | ||
|
|
||
| ```powershell | ||
| cd dotnet/samples/GettingStarted/Agents/Agent_Step05_StructuredOutput | ||
| dotnet run | ||
| ``` | ||
|
|
||
| ## Expected behavior | ||
|
|
||
| The sample will demonstrate four different approaches to structured output: | ||
|
|
||
| 1. **Structured Output with ResponseFormat**: Creates an agent with `ResponseFormat` set to `ForJsonSchema<CityInfo>()`, invokes it with unstructured input, and accesses the structured output via the `Text` property | ||
| 2. **Structured Output with RunAsync<T>**: Creates an agent and uses the generic `RunAsync<CityInfo>()` method to get a typed `AgentResponse<CityInfo>` with the result accessible via the `Result` property | ||
| 3. **Structured Output with RunStreamingAsync**: Creates an agent with JSON schema response format, streams the response using `RunStreamingAsync`, assembles the updates using `ToAgentResponseAsync()`, and deserializes the JSON text into a typed object | ||
| 4. **Structured Output with StructuredOutput Middleware**: Uses the `UseStructuredOutput` method on `AIAgentBuilder` to add structured output support to agents that don't natively support it | ||
|
|
||
| Each approach will output information about the capital of France (Paris) in a structured format. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
dotnet/src/Microsoft.Agents.AI/StructuredOutput/AIAgentBuilderExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using Microsoft.Extensions.AI; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| namespace Microsoft.Agents.AI; | ||
|
|
||
| /// <summary> | ||
| /// Provides extension methods for adding structured output capabilities to <see cref="AIAgentBuilder"/> instances. | ||
| /// </summary> | ||
| public static class AIAgentBuilderExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds structured output capabilities to the agent pipeline, enabling conversion of text responses to structured JSON format. | ||
| /// </summary> | ||
| /// <param name="builder">The <see cref="AIAgentBuilder"/> to which structured output support will be added.</param> | ||
| /// <param name="chatClient"> | ||
| /// The chat client used to transform text responses into structured JSON format. | ||
| /// If <see langword="null"/>, the chat client will be resolved from the service provider. | ||
| /// </param> | ||
| /// <param name="optionsFactory"> | ||
| /// An optional factory function that returns the <see cref="StructuredOutputAgentOptions"/> instance to use. | ||
| /// This allows for fine-tuning the structured output behavior such as setting the response format or system message. | ||
| /// </param> | ||
| /// <returns>The <see cref="AIAgentBuilder"/> with structured output capabilities added, enabling method chaining.</returns> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// A <see cref="ChatResponseFormatJson"/> must be specified either through the | ||
| /// <see cref="AgentRunOptions.ResponseFormat"/> at runtime or the <see cref="StructuredOutputAgentOptions.ChatOptions"/> | ||
| /// provided during configuration. | ||
| /// </para> | ||
| /// </remarks> | ||
| public static AIAgentBuilder UseStructuredOutput( | ||
| this AIAgentBuilder builder, | ||
| IChatClient? chatClient = null, | ||
| Func<StructuredOutputAgentOptions>? optionsFactory = null) => | ||
| Throw.IfNull(builder).Use((innerAgent, services) => | ||
| { | ||
| chatClient ??= services?.GetService<IChatClient>() | ||
| ?? throw new InvalidOperationException($"No {nameof(IChatClient)} was provided and none could be resolved from the service provider. Either provide an {nameof(IChatClient)} explicitly or register one in the dependency injection container."); | ||
|
|
||
| return new StructuredOutputAgent(innerAgent, chatClient, optionsFactory?.Invoke()); | ||
| }); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.