-
Notifications
You must be signed in to change notification settings - Fork 811
Bring back AsIChatClient for OpenAI AssistantClient #6501
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
2 commits
Select commit
Hold shift + click to select a range
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
446 changes: 446 additions & 0 deletions
446
src/Libraries/Microsoft.Extensions.AI.OpenAI/OpenAIAssistantChatClient.cs
Large diffs are not rendered by default.
Oops, something went wrong.
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
83 changes: 83 additions & 0 deletions
83
...braries/Microsoft.Extensions.AI.OpenAI.Tests/OpenAIAssistantChatClientIntegrationTests.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,83 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. | ||
#pragma warning disable CA1822 // Mark members as static | ||
#pragma warning disable CA2000 // Dispose objects before losing scope | ||
#pragma warning disable S1135 // Track uses of "TODO" tags | ||
#pragma warning disable xUnit1013 // Public method should be marked as test | ||
|
||
using System; | ||
using System.Linq; | ||
using System.Net; | ||
using System.Net.Http; | ||
using System.Text.RegularExpressions; | ||
using System.Threading.Tasks; | ||
using OpenAI.Assistants; | ||
using Xunit; | ||
|
||
namespace Microsoft.Extensions.AI; | ||
|
||
public class OpenAIAssistantChatClientIntegrationTests : ChatClientIntegrationTests | ||
{ | ||
protected override IChatClient? CreateChatClient() | ||
{ | ||
var openAIClient = IntegrationTestHelpers.GetOpenAIClient(); | ||
if (openAIClient is null) | ||
{ | ||
return null; | ||
} | ||
|
||
AssistantClient ac = openAIClient.GetAssistantClient(); | ||
var assistant = | ||
ac.GetAssistants().FirstOrDefault() ?? | ||
ac.CreateAssistant("gpt-4o-mini"); | ||
|
||
return ac.AsIChatClient(assistant.Id); | ||
} | ||
|
||
public override bool FunctionInvokingChatClientSetsConversationId => true; | ||
|
||
// These tests aren't written in a way that works well with threads. | ||
public override Task Caching_AfterFunctionInvocation_FunctionOutputChangedAsync() => Task.CompletedTask; | ||
public override Task Caching_AfterFunctionInvocation_FunctionOutputUnchangedAsync() => Task.CompletedTask; | ||
|
||
// Assistants doesn't support data URIs. | ||
public override Task MultiModal_DescribeImage() => Task.CompletedTask; | ||
public override Task MultiModal_DescribePdf() => Task.CompletedTask; | ||
|
||
// [Fact] // uncomment and run to clear out _all_ threads in your OpenAI account | ||
public async Task DeleteAllThreads() | ||
{ | ||
using HttpClient client = new(new HttpClientHandler | ||
{ | ||
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, | ||
}); | ||
|
||
// These values need to be filled in. The bearer token needs to be sniffed from a browser | ||
// session interacting with the dashboard (e.g. use F12 networking tools to look at request headers | ||
// made to "https://api.openai.com/v1/threads?limit=10" after clicking on Assistants | Threads in the | ||
// OpenAI portal dashboard). | ||
client.DefaultRequestHeaders.Add("authorization", $"Bearer sess-ENTERYOURSESSIONTOKEN"); | ||
client.DefaultRequestHeaders.Add("openai-organization", "org-ENTERYOURORGID"); | ||
client.DefaultRequestHeaders.Add("openai-project", "proj_ENTERYOURPROJECTID"); | ||
|
||
AssistantClient ac = new AssistantClient(Environment.GetEnvironmentVariable("AI:OpenAI:ApiKey")!); | ||
while (true) | ||
{ | ||
string listing = await client.GetStringAsync("https://api.openai.com/v1/threads?limit=100"); | ||
|
||
var matches = Regex.Matches(listing, @"thread_\w+"); | ||
if (matches.Count == 0) | ||
{ | ||
break; | ||
} | ||
|
||
foreach (Match m in matches) | ||
{ | ||
var dr = await ac.DeleteThreadAsync(m.Value); | ||
Assert.True(dr.Value.Deleted); | ||
} | ||
} | ||
} | ||
} |
77 changes: 77 additions & 0 deletions
77
test/Libraries/Microsoft.Extensions.AI.OpenAI.Tests/OpenAIAssistantChatClientTests.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,77 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.ClientModel; | ||
using Azure.AI.OpenAI; | ||
using Microsoft.Extensions.Caching.Distributed; | ||
using Microsoft.Extensions.Caching.Memory; | ||
using OpenAI; | ||
using OpenAI.Assistants; | ||
using Xunit; | ||
|
||
#pragma warning disable S103 // Lines should not be too long | ||
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. | ||
|
||
namespace Microsoft.Extensions.AI; | ||
|
||
public class OpenAIAssistantChatClientTests | ||
{ | ||
[Fact] | ||
public void AsIChatClient_InvalidArgs_Throws() | ||
{ | ||
Assert.Throws<ArgumentNullException>("assistantClient", () => ((AssistantClient)null!).AsIChatClient("assistantId")); | ||
Assert.Throws<ArgumentNullException>("assistantId", () => new AssistantClient("ignored").AsIChatClient(null!)); | ||
} | ||
|
||
[Theory] | ||
[InlineData(false)] | ||
[InlineData(true)] | ||
public void AsIChatClient_OpenAIClient_ProducesExpectedMetadata(bool useAzureOpenAI) | ||
{ | ||
Uri endpoint = new("http://localhost/some/endpoint"); | ||
|
||
var client = useAzureOpenAI ? | ||
new AzureOpenAIClient(endpoint, new ApiKeyCredential("key")) : | ||
new OpenAIClient(new ApiKeyCredential("key"), new OpenAIClientOptions { Endpoint = endpoint }); | ||
|
||
IChatClient[] clients = | ||
[ | ||
client.GetAssistantClient().AsIChatClient("assistantId"), | ||
client.GetAssistantClient().AsIChatClient("assistantId", "threadId"), | ||
]; | ||
|
||
foreach (var chatClient in clients) | ||
{ | ||
var metadata = chatClient.GetService<ChatClientMetadata>(); | ||
Assert.Equal("openai", metadata?.ProviderName); | ||
Assert.Equal(endpoint, metadata?.ProviderUri); | ||
} | ||
} | ||
|
||
[Fact] | ||
public void GetService_AssistantClient_SuccessfullyReturnsUnderlyingClient() | ||
{ | ||
AssistantClient assistantClient = new OpenAIClient("key").GetAssistantClient(); | ||
IChatClient chatClient = assistantClient.AsIChatClient("assistantId"); | ||
|
||
Assert.Same(assistantClient, chatClient.GetService<AssistantClient>()); | ||
|
||
Assert.Null(chatClient.GetService<OpenAIClient>()); | ||
|
||
using IChatClient pipeline = chatClient | ||
.AsBuilder() | ||
.UseFunctionInvocation() | ||
.UseOpenTelemetry() | ||
.UseDistributedCache(new MemoryDistributedCache(Options.Options.Create(new MemoryDistributedCacheOptions()))) | ||
.Build(); | ||
|
||
Assert.NotNull(pipeline.GetService<FunctionInvokingChatClient>()); | ||
Assert.NotNull(pipeline.GetService<DistributedCachingChatClient>()); | ||
Assert.NotNull(pipeline.GetService<CachingChatClient>()); | ||
Assert.NotNull(pipeline.GetService<OpenTelemetryChatClient>()); | ||
|
||
Assert.Same(assistantClient, pipeline.GetService<AssistantClient>()); | ||
Assert.IsType<FunctionInvokingChatClient>(pipeline.GetService<IChatClient>()); | ||
} | ||
} |
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.