Skip to content

Commit 3eabc60

Browse files
authored
Merge pull request #755 from unoplatform/dev/erli/chatgpt-openai-sdk
feat: ChatGPT - Use OpenAI official SDK
2 parents 38338ca + c648b69 commit 3eabc60

File tree

10 files changed

+54
-87
lines changed

10 files changed

+54
-87
lines changed

UI/ChatGPT/src/ChatGPT/App.xaml.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,15 @@ protected override void OnLaunched(LaunchActivatedEventArgs args)
4242
{
4343
var section = context.Configuration.GetSection(nameof(AppConfig));
4444
var apiKey = section[nameof(AppConfig.ApiKey)];
45-
var useMockService = apiKey is null or { Length: 0 };
4645

47-
if (useMockService)
46+
if (apiKey is null or { Length: 0 })
4847
{
4948
services.AddSingleton<IChatService, MockChatService>();
5049
}
5150
else
5251
{
5352
services
54-
.AddSingleton<OpenAiOptions, ChatAiOptions>()
55-
.AddSingleton<IChatCompletionService, OpenAIService>()
53+
.AddSingleton(new ChatClient("gpt-3.5-turbo", apiKey))
5654
.AddSingleton<IChatService, ChatService>();
5755
}
5856

UI/ChatGPT/src/ChatGPT/Business/Models/ChatAiOptions.cs

Lines changed: 0 additions & 11 deletions
This file was deleted.

UI/ChatGPT/src/ChatGPT/ChatGPT.csproj

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929
Configuration;
3030
</UnoFeatures>
3131
</PropertyGroup>
32-
33-
<ItemGroup>
34-
<PackageReference Include="Betalgo.OpenAI" />
35-
</ItemGroup>
32+
<ItemGroup>
33+
<PackageReference Include="OpenAI" />
34+
</ItemGroup>
3635
</Project>

UI/ChatGPT/src/ChatGPT/GlobalUsings.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66
global using ChatGPT.Business.Models;
77
global using ChatGPT.Presentation;
88
global using ChatGPT.Services;
9+
global using ChatGPT.Business;
10+
global using OpenAI.Chat;
911
global using ApplicationExecutionState = Windows.ApplicationModel.Activation.ApplicationExecutionState;
10-
global using Color = Windows.UI.Color;
11-
global using OpenAI;
12-
global using OpenAI.Interfaces;
13-
global using OpenAI.Managers;
12+
global using Color = Windows.UI.Color;

UI/ChatGPT/src/ChatGPT/Presentation/MainModel.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
using ChatGPT.Business;
2-
using ChatGPT.Services;
3-
4-
namespace ChatGPT.Presentation;
1+
namespace ChatGPT.Presentation;
52

63
public partial record MainModel
74
{

UI/ChatGPT/src/ChatGPT/Presentation/Message.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using ChatGPT.Business;
2-
3-
namespace ChatGPT.Presentation;
1+
namespace ChatGPT.Presentation;
42

53
public partial record Message(Guid Id, Source Source, Status Status, string? Content)
64
{
Lines changed: 38 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,37 @@
1-
using ChatGPT.Business;
2-
using OpenAI.Interfaces;
3-
using OpenAI.ObjectModels;
4-
using OpenAI.ObjectModels.RequestModels;
5-
using OpenAI.ObjectModels.ResponseModels;
1+
using System.ClientModel;
62
using System.Runtime.CompilerServices;
73
using System.Text;
84

95
namespace ChatGPT.Services;
10-
public class ChatService(IChatCompletionService client) : IChatService
6+
public class ChatService : IChatService
117
{
12-
private readonly IChatCompletionService _client = client;
13-
148
private const string systemPrompt = "You are Uno ChatGPT Sample, a helpful assistant helping users to learn more about how to develop using Uno Platform.";
159

10+
private readonly ChatClient _client;
11+
12+
public ChatService(ChatClient client)
13+
{
14+
_client = client;
15+
}
16+
1617
public async ValueTask<ChatResponse> AskAsync(ChatRequest chatRequest, CancellationToken ct = default)
1718
{
1819
try
1920
{
2021
var request = ToCompletionRequest(chatRequest);
21-
var result = await _client.CreateCompletion(request, cancellationToken: ct);
22+
ChatCompletion result = await _client.CompleteChatAsync(request);
2223

23-
if (result.Successful)
24+
return result.FinishReason switch
2425
{
25-
var response = result.Choices.Select(choice => choice.Message.Content);
26-
27-
return new ChatResponse(string.Join("", response));
28-
}
29-
else
30-
{
31-
return new ChatResponse(result.Error?.Message, IsError: true);
32-
}
26+
ChatFinishReason.Stop => new ChatResponse(result.ToString()),
27+
ChatFinishReason.Length => new ChatResponse("Incomplete model output due to MaxTokens parameter or token limit exceeded.", IsError: true),
28+
ChatFinishReason.ContentFilter => new ChatResponse("Omitted content due to a content filter flag.", IsError: true),
29+
_ => new ChatResponse(result.FinishReason.ToString())
30+
};
3331
}
34-
catch (Exception)
32+
catch (Exception ex)
3533
{
36-
return new ChatResponse(IsError: true);
34+
return new ChatResponse($"Something went wrong: {ex.Message}", IsError: true);
3735
}
3836
}
3937

@@ -43,56 +41,46 @@ public async IAsyncEnumerable<ChatResponse> AskAsStream(ChatRequest chatRequest,
4341
var response = new ChatResponse();
4442
var content = new StringBuilder();
4543

46-
IAsyncEnumerator<ChatCompletionCreateResponse>? responseStream = default;
44+
IAsyncEnumerator<StreamingChatCompletionUpdate>? responseStream = default;
45+
4746
while (!response.IsError)
4847
{
4948
try
5049
{
51-
responseStream ??= _client.CreateCompletionAsStream(request).GetAsyncEnumerator(ct);
50+
responseStream ??= _client.CompleteChatStreamingAsync(request).GetAsyncEnumerator(ct);
51+
5252
if (await responseStream.MoveNextAsync())
5353
{
54-
if (responseStream.Current.Successful)
54+
foreach (var updatePart in responseStream.Current.ContentUpdate)
5555
{
56-
foreach (var choice in responseStream.Current.Choices)
57-
{
58-
content.Append(choice.Message.Content);
59-
}
60-
response = response with { Message = content.ToString() };
61-
}
62-
else
63-
{
64-
response = response with { Message = responseStream.Current.Error?.Message, IsError = true };
56+
content.Append(updatePart.Text);
6557
}
58+
59+
response = response with { Message = content.ToString() };
6660
}
6761
else
6862
{
6963
yield break;
7064
}
7165
}
72-
catch (Exception)
66+
catch (Exception ex)
7367
{
74-
response = response with { IsError = true };
68+
response = response with { Message = $"Something went wrong: {ex.Message}", IsError = true };
7569
}
7670

7771
yield return response;
7872
}
7973
}
8074

81-
private ChatCompletionCreateRequest ToCompletionRequest(ChatRequest request)
82-
{
83-
var history = request.History;
84-
var requestMessages = new List<ChatMessage>(history.Count + 1)
85-
{
86-
ChatMessage.FromSystem(systemPrompt)
87-
};
88-
requestMessages.AddRange(history.Select(entry => entry.IsUser
89-
? ChatMessage.FromUser(entry.Message)
90-
: ChatMessage.FromAssistant(entry.Message)));
75+
private ChatMessage[] ToCompletionRequest(ChatRequest request)
76+
=> request.History
77+
.Select(ConvertMessage)
78+
.Prepend(ChatMessage.CreateSystemMessage(systemPrompt))
79+
.ToArray();
80+
9181

92-
return new ChatCompletionCreateRequest()
93-
{
94-
Messages = requestMessages,
95-
Model = Models.Gpt_3_5_Turbo
96-
};
97-
}
82+
private ChatMessage ConvertMessage(ChatEntry entry)
83+
=> entry.IsUser
84+
? ChatMessage.CreateUserMessage(entry.Message)
85+
: ChatMessage.CreateAssistantMessage(entry.Message);
9886
}

UI/ChatGPT/src/ChatGPT/Services/IChatService.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using ChatGPT.Business;
2-
3-
namespace ChatGPT.Services;
1+
namespace ChatGPT.Services;
42
public interface IChatService
53
{
64
ValueTask<ChatResponse> AskAsync(ChatRequest request, CancellationToken ct = default);

UI/ChatGPT/src/ChatGPT/Services/MockChatService.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using ChatGPT.Business;
2-
using System.Runtime.CompilerServices;
1+
using System.Runtime.CompilerServices;
32
using System.Text;
43

54
namespace ChatGPT.Services;

UI/ChatGPT/src/Directory.Packages.props

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
See https://aka.platform.uno/using-uno-sdk for more information.
66
-->
77
<ItemGroup>
8-
<PackageVersion Include="Betalgo.OpenAI" Version="7.4.3" />
98
</ItemGroup>
10-
</Project>
9+
<ItemGroup>
10+
<PackageVersion Include="OpenAI" Version="2.0.0-beta.7" />
11+
</ItemGroup>
12+
</Project>

0 commit comments

Comments
 (0)