-
Couldn't load subscription status.
- Fork 618
.NET: Enable access to hosted AIAgents via OpenAI Chat Completions #1302
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
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
94abdac
non-streaming chat completion
DeagleGross 06ed6b3
support streaming
DeagleGross dfb6ffd
simplify frontend clients + nit
DeagleGross 2b29c1b
nit
DeagleGross dff06e8
Merge branch 'main' into dmkorolev/chat-completions
DeagleGross adaa80f
use baseaddress
DeagleGross 6037933
rm unnecessary
DeagleGross 5d34024
refactor
DeagleGross c47c4b8
remove conversation id for chatcompletions agent client
DeagleGross 8698381
Merge branch 'main' into dmkorolev/chat-completions
DeagleGross 43b664f
Merge branch 'main' into dmkorolev/chat-completions
DeagleGross 79cb9a5
Merge branch 'main' into dmkorolev/chat-completions
DeagleGross f3478c2
Merge branch 'main' into dmkorolev/chat-completions
DeagleGross ffd142f
Merge branch 'main' into dmkorolev/chat-completions
DeagleGross 3250bdb
nits
DeagleGross 57f066c
Merge branch 'main' into dmkorolev/chat-completions
DeagleGross 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
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
37 changes: 37 additions & 0 deletions
37
dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIChatCompletionsAgentClient.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,37 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System.ClientModel; | ||
| using System.ClientModel.Primitives; | ||
| using System.Runtime.CompilerServices; | ||
| using Microsoft.Agents.AI; | ||
| using Microsoft.Extensions.AI; | ||
| using OpenAI; | ||
| using OpenAI.Chat; | ||
| using ChatMessage = Microsoft.Extensions.AI.ChatMessage; | ||
|
|
||
| namespace AgentWebChat.Web; | ||
|
|
||
| /// <summary> | ||
| /// Is a simple frontend client which exercises the ability of exposed agent to communicate via OpenAI ChatCompletions protocol. | ||
| /// </summary> | ||
| internal sealed class OpenAIChatCompletionsAgentClient(HttpClient httpClient) : AgentClientBase | ||
| { | ||
| public async override IAsyncEnumerable<AgentRunResponseUpdate> RunStreamingAsync( | ||
| string agentName, | ||
| IList<ChatMessage> messages, | ||
| string? threadId = null, | ||
| [EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
| { | ||
| OpenAIClientOptions options = new() | ||
| { | ||
| Endpoint = new Uri(httpClient.BaseAddress!, $"/{agentName}/v1/"), | ||
| Transport = new HttpClientPipelineTransport(httpClient) | ||
| }; | ||
|
|
||
| var openAiClient = new ChatClient(model: "myModel!", credential: new ApiKeyCredential("dummy-key"), options: options).AsIChatClient(); | ||
| await foreach (var update in openAiClient.GetStreamingResponseAsync(messages, cancellationToken: cancellationToken)) | ||
| { | ||
| yield return new AgentRunResponseUpdate(update); | ||
| } | ||
| } | ||
| } |
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
105 changes: 105 additions & 0 deletions
105
...src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AIAgentChatCompletionsProcessor.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,105 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System.Buffers; | ||
| using System.ClientModel.Primitives; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
| using System.Net.ServerSentEvents; | ||
| using System.Runtime.CompilerServices; | ||
| using System.Text.Json; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Agents.AI.Hosting.OpenAI.ChatCompletions.Utils; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Http.Features; | ||
| using OpenAI.Chat; | ||
| using ChatMessage = Microsoft.Extensions.AI.ChatMessage; | ||
|
|
||
| namespace Microsoft.Agents.AI.Hosting.OpenAI.ChatCompletions; | ||
|
|
||
| internal sealed class AIAgentChatCompletionsProcessor | ||
| { | ||
| private readonly AIAgent _agent; | ||
|
|
||
| public AIAgentChatCompletionsProcessor(AIAgent agent) | ||
| { | ||
| this._agent = agent; | ||
| } | ||
|
|
||
| public async Task<IResult> CreateChatCompletionAsync(ChatCompletionOptions chatCompletionOptions, CancellationToken cancellationToken) | ||
| { | ||
| AgentThread? agentThread = null; // not supported to resolve from conversationId | ||
|
|
||
| var inputItems = chatCompletionOptions.GetMessages(); | ||
| var chatMessages = inputItems.AsChatMessages(); | ||
|
|
||
| if (chatCompletionOptions.GetStream()) | ||
| { | ||
| return new OpenAIStreamingChatCompletionResult(this._agent, chatMessages); | ||
| } | ||
|
|
||
| var agentResponse = await this._agent.RunAsync(chatMessages, agentThread, cancellationToken: cancellationToken).ConfigureAwait(false); | ||
| return new OpenAIChatCompletionResult(agentResponse); | ||
| } | ||
|
|
||
| private sealed class OpenAIChatCompletionResult(AgentRunResponse agentRunResponse) : IResult | ||
| { | ||
| public async Task ExecuteAsync(HttpContext httpContext) | ||
| { | ||
| // note: OpenAI SDK types provide their own serialization implementation | ||
| // so we cant simply return IResult wrap for the typed-object. | ||
| // instead writing to the response body can be done. | ||
|
|
||
| var cancellationToken = httpContext.RequestAborted; | ||
| var response = httpContext.Response; | ||
|
|
||
| var chatResponse = agentRunResponse.AsChatResponse(); | ||
| var openAIChatCompletion = chatResponse.AsOpenAIChatCompletion(); | ||
| var openAIChatCompletionJsonModel = openAIChatCompletion as IJsonModel<ChatCompletion>; | ||
| Debug.Assert(openAIChatCompletionJsonModel is not null); | ||
|
|
||
| var writer = new Utf8JsonWriter(response.BodyWriter, new JsonWriterOptions { SkipValidation = false }); | ||
| openAIChatCompletionJsonModel.Write(writer, ModelReaderWriterOptions.Json); | ||
| await writer.FlushAsync(cancellationToken).ConfigureAwait(false); | ||
| } | ||
| } | ||
|
|
||
| private sealed class OpenAIStreamingChatCompletionResult(AIAgent agent, IEnumerable<ChatMessage> chatMessages) : IResult | ||
| { | ||
| public Task ExecuteAsync(HttpContext httpContext) | ||
| { | ||
| var cancellationToken = httpContext.RequestAborted; | ||
| var response = httpContext.Response; | ||
|
|
||
| // Set SSE headers | ||
| response.Headers.ContentType = "text/event-stream"; | ||
| response.Headers.CacheControl = "no-cache,no-store"; | ||
| response.Headers.Connection = "keep-alive"; | ||
| response.Headers.ContentEncoding = "identity"; | ||
| httpContext.Features.GetRequiredFeature<IHttpResponseBodyFeature>().DisableBuffering(); | ||
|
|
||
| return SseFormatter.WriteAsync( | ||
| source: this.GetStreamingResponsesAsync(cancellationToken), | ||
| destination: response.Body, | ||
| itemFormatter: (sseItem, bufferWriter) => | ||
| { | ||
| var sseDataJsonModel = (IJsonModel<StreamingChatCompletionUpdate>)sseItem.Data; | ||
| var json = sseDataJsonModel.Write(ModelReaderWriterOptions.Json); | ||
| bufferWriter.Write(json); | ||
| }, | ||
| cancellationToken); | ||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private async IAsyncEnumerable<SseItem<StreamingChatCompletionUpdate>> GetStreamingResponsesAsync([EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
| { | ||
| AgentThread? agentThread = null; | ||
|
|
||
| var agentRunResponseUpdates = agent.RunStreamingAsync(chatMessages, thread: agentThread, cancellationToken: cancellationToken); | ||
| var chatResponseUpdates = agentRunResponseUpdates.AsChatResponseUpdatesAsync(); | ||
| await foreach (var streamingChatCompletionUpdate in chatResponseUpdates.AsOpenAIStreamingChatCompletionUpdatesAsync(cancellationToken).ConfigureAwait(false)) | ||
| { | ||
| yield return new SseItem<StreamingChatCompletionUpdate>(streamingChatCompletionUpdate); | ||
| } | ||
| } | ||
| } | ||
| } | ||
52 changes: 52 additions & 0 deletions
52
...rosoft.Agents.AI.Hosting.OpenAI/ChatCompletions/Utils/ChatCompletionsOptionsExtensions.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,52 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Reflection; | ||
| using Microsoft.Shared.Diagnostics; | ||
| using OpenAI.Chat; | ||
|
|
||
| namespace Microsoft.Agents.AI.Hosting.OpenAI.ChatCompletions.Utils; | ||
|
|
||
| [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1810:Initialize reference type static fields inline", Justification = "Specifically for accessing hidden members")] | ||
| [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1065:Do not raise exceptions in unexpected locations", Justification = "Specifically for accessing hidden members")] | ||
| internal static class ChatCompletionsOptionsExtensions | ||
| { | ||
| private static readonly Func<ChatCompletionOptions, bool?> _getStreamNullable; | ||
| private static readonly Func<ChatCompletionOptions, IList<ChatMessage>> _getMessages; | ||
|
|
||
| static ChatCompletionsOptionsExtensions() | ||
| { | ||
| // OpenAI SDK does not have a simple way to get the input as a c# object. | ||
| // However, it does parse most of the interesting fields into internal properties of `ChatCompletionsOptions` object. | ||
|
|
||
| // --- Stream (internal bool? Stream { get; set; }) --- | ||
| const string streamPropName = "Stream"; | ||
| var streamProp = typeof(ChatCompletionOptions).GetProperty(streamPropName, BindingFlags.Instance | BindingFlags.NonPublic) | ||
| ?? throw new MissingMemberException(typeof(ChatCompletionOptions).FullName!, streamPropName); | ||
| var streamGetter = streamProp.GetGetMethod(nonPublic: true) ?? throw new MissingMethodException($"{streamPropName} getter not found."); | ||
DeagleGross marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| _getStreamNullable = streamGetter.CreateDelegate<Func<ChatCompletionOptions, bool?>>(); | ||
|
|
||
| // --- Messages (internal IList<OpenAI.Chat.ChatMessage> Messages { get; set; }) --- | ||
| const string inputPropName = "Messages"; | ||
| var inputProp = typeof(ChatCompletionOptions).GetProperty(inputPropName, BindingFlags.Instance | BindingFlags.NonPublic) | ||
| ?? throw new MissingMemberException(typeof(ChatCompletionOptions).FullName!, inputPropName); | ||
| var inputGetter = inputProp.GetGetMethod(nonPublic: true) | ||
| ?? throw new MissingMethodException($"{inputPropName} getter not found."); | ||
|
|
||
| _getMessages = inputGetter.CreateDelegate<Func<ChatCompletionOptions, IList<ChatMessage>>>(); | ||
| } | ||
|
|
||
| public static IList<ChatMessage> GetMessages(this ChatCompletionOptions options) | ||
| { | ||
| Throw.IfNull(options); | ||
| return _getMessages(options); | ||
| } | ||
|
|
||
| public static bool GetStream(this ChatCompletionOptions options) | ||
| { | ||
| Throw.IfNull(options); | ||
| return _getStreamNullable(options) ?? false; | ||
DeagleGross marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
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.