-
Notifications
You must be signed in to change notification settings - Fork 2k
.NET:[Breaking] Add support for structured output #3658
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 18 commits into
microsoft:feature-so
from
SergeyMenshykh:add-so-methods
Feb 4, 2026
Merged
Changes from 17 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
a6c49c2
add support for so
SergeyMenshykh 5826e35
restore lost xml comment part
SergeyMenshykh 84a9c74
fix using ordering
SergeyMenshykh 0d8ea68
Update dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgentStructuredO…
SergeyMenshykh 28de92c
Update dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgentStructuredO…
SergeyMenshykh bbc1241
Update dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClie…
SergeyMenshykh 919d052
addressw pr review comments
SergeyMenshykh 0988b8a
Merge branch 'add-so-methods' of https://github.com/SergeyMenshykh/ag…
SergeyMenshykh 0bd9421
address pr review feedback
SergeyMenshykh 90dc17f
address pr review comments
SergeyMenshykh b25c222
Merge branch 'feature-so' into add-so-methods
SergeyMenshykh 5f32326
fix compilation issues after the latest merge with main
SergeyMenshykh 9da8817
remove unnecessry options
SergeyMenshykh b4e44b9
remove RunAsync<object> methods
SergeyMenshykh a7690dd
address code review feedback
SergeyMenshykh d7f0d85
address pr review feedback
SergeyMenshykh 3e39df3
make copy constructor protected
SergeyMenshykh b2b0619
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
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
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
93 changes: 83 additions & 10 deletions
93
dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponse{T}.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 |
|---|---|---|
| @@ -1,30 +1,103 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using Microsoft.Extensions.AI; | ||
| using System; | ||
| #if NET | ||
| using System.Buffers; | ||
| #endif | ||
|
|
||
| #if NET | ||
| using System.Text; | ||
| #endif | ||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
| using System.Text.Json.Serialization.Metadata; | ||
|
|
||
| namespace Microsoft.Agents.AI; | ||
|
|
||
| /// <summary> | ||
| /// Represents the response of the specified type <typeparamref name="T"/> to an <see cref="AIAgent"/> run request. | ||
| /// </summary> | ||
| /// <typeparam name="T">The type of value expected from the agent.</typeparam> | ||
| public abstract class AgentResponse<T> : AgentResponse | ||
| public class AgentResponse<T> : AgentResponse | ||
| { | ||
| /// <summary>Initializes a new instance of the <see cref="AgentResponse{T}"/> class.</summary> | ||
| protected AgentResponse() | ||
| { | ||
| } | ||
| private readonly JsonSerializerOptions _serializerOptions; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="AgentResponse{T}"/> class from an existing <see cref="ChatResponse"/>. | ||
| /// Initializes a new instance of the <see cref="AgentResponse{T}"/> class. | ||
| /// </summary> | ||
| /// <param name="response">The <see cref="ChatResponse"/> from which to populate this <see cref="AgentResponse{T}"/>.</param> | ||
| protected AgentResponse(ChatResponse response) : base(response) | ||
| /// <param name="response">The <see cref="AgentResponse"/> from which to populate this <see cref="AgentResponse{T}"/>.</param> | ||
| /// <param name="serializerOptions">The <see cref="JsonSerializerOptions"/> to use when deserializing the result.</param> | ||
| public AgentResponse(AgentResponse response, JsonSerializerOptions serializerOptions) : base(response) | ||
| { | ||
| this._serializerOptions = serializerOptions; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the result value of the agent response as an instance of <typeparamref name="T"/>. | ||
| /// </summary> | ||
| public abstract T Result { get; } | ||
| [JsonIgnore] | ||
| public virtual T Result | ||
| { | ||
| get | ||
| { | ||
| var structuredOutput = this.GetResultCore(this._serializerOptions, out var failureReason); | ||
| return failureReason switch | ||
| { | ||
| FailureReason.ResultDidNotContainJson => throw new InvalidOperationException("The response did not contain JSON to be deserialized."), | ||
| FailureReason.DeserializationProducedNull => throw new InvalidOperationException("The deserialized response is null."), | ||
| _ => structuredOutput!, | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| private T? GetResultCore(JsonSerializerOptions serializerOptions, out FailureReason? failureReason) | ||
|
SergeyMenshykh marked this conversation as resolved.
Outdated
|
||
| { | ||
| var json = this.Text; | ||
| if (string.IsNullOrEmpty(json)) | ||
| { | ||
| failureReason = FailureReason.ResultDidNotContainJson; | ||
| return default; | ||
| } | ||
|
|
||
| // If there's an exception here, we want it to propagate, since the Result property is meant to throw directly | ||
| T? deserialized = DeserializeFirstTopLevelObject(json!, (JsonTypeInfo<T>)serializerOptions.GetTypeInfo(typeof(T))); | ||
|
|
||
| if (deserialized is null) | ||
| { | ||
| failureReason = FailureReason.DeserializationProducedNull; | ||
| return default; | ||
| } | ||
|
|
||
| failureReason = default; | ||
| return deserialized; | ||
| } | ||
|
|
||
| private static T? DeserializeFirstTopLevelObject(string json, JsonTypeInfo<T> typeInfo) | ||
| { | ||
| #if NET | ||
| // We need to deserialize only the first top-level object as a workaround for a common LLM backend | ||
| // issue. GPT 3.5 Turbo commonly returns multiple top-level objects after doing a function call. | ||
| // See https://community.openai.com/t/2-json-objects-returned-when-using-function-calling-and-json-mode/574348 | ||
| var utf8ByteLength = Encoding.UTF8.GetByteCount(json); | ||
| var buffer = ArrayPool<byte>.Shared.Rent(utf8ByteLength); | ||
| try | ||
| { | ||
| var utf8SpanLength = Encoding.UTF8.GetBytes(json, 0, json.Length, buffer, 0); | ||
| var reader = new Utf8JsonReader(new ReadOnlySpan<byte>(buffer, 0, utf8SpanLength), new() { AllowMultipleValues = true }); | ||
| return JsonSerializer.Deserialize(ref reader, typeInfo); | ||
| } | ||
| finally | ||
| { | ||
| ArrayPool<byte>.Shared.Return(buffer); | ||
| } | ||
| #else | ||
| return JsonSerializer.Deserialize(json, typeInfo); | ||
| #endif | ||
| } | ||
|
|
||
| private enum FailureReason | ||
| { | ||
| ResultDidNotContainJson, | ||
| DeserializationProducedNull | ||
| } | ||
| } | ||
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.