Skip to content

Commit

Permalink
Rename Chat to ChatService; Release 2.4.0
Browse files Browse the repository at this point in the history
  • Loading branch information
rodion-m committed Apr 24, 2023
1 parent 2538e0c commit 67038e0
Show file tree
Hide file tree
Showing 11 changed files with 41 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public static class ServiceCollectionExtensions

public static IServiceCollection AddChatGptInMemoryIntegration(
this IServiceCollection services,
bool injectInMemoryChat = true,
bool injectInMemoryChatService = true,
string credentialsConfigSectionPath = CredentialsConfigSectionPathDefault,
string completionsConfigSectionPath = CchatGPTConfigSectionPathDefault)
{
Expand All @@ -29,14 +29,14 @@ public static IServiceCollection AddChatGptInMemoryIntegration(
}
services.AddChatGptIntegrationCore(credentialsConfigSectionPath, completionsConfigSectionPath);
services.AddSingleton<IChatHistoryStorage, InMemoryChatHistoryStorage>();
if(injectInMemoryChat)
if(injectInMemoryChatService)
{
services.AddScoped<Chat>(CreateChatGptChat);
services.AddScoped<ChatService>(CreateChatService);
}
return services;
}

private static Chat CreateChatGptChat(IServiceProvider provider)
private static ChatService CreateChatService(IServiceProvider provider)
{
ArgumentNullException.ThrowIfNull(provider);
var userId = Guid.Empty.ToString();
Expand Down
2 changes: 1 addition & 1 deletion OpenAI.ChatGpt.AspNetCore/OpenAI.ChatGpt.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<PackageId>OpenAI.ChatGPT.AspNetCore</PackageId>
<PackageProjectUrl>https://github.com/rodion-m/ChatGPT_API_dotnet</PackageProjectUrl>
<Product>OpenAI ChatGPT integration for .NET with DI</Product>
<Version>2.3.0</Version>
<Version>2.4.0</Version>
<Description>OpenAI Chat Completions API (ChatGPT) integration with easy DI supporting (Microsoft.Extensions.DependencyInjection). It allows you to use the API in your .NET applications. Also, the client supports streaming responses (like ChatGPT) via async streams.</Description>
<RepositoryUrl>https://github.com/rodion-m/ChatGPT_API_dotnet</RepositoryUrl>
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<PackageId>OpenAI.ChatGPT.EntityFrameworkCore</PackageId>
<PackageProjectUrl>https://github.com/rodion-m/ChatGPT_API_dotnet</PackageProjectUrl>
<Product>OpenAI ChatGPT integration for .NET with EF Core storage</Product>
<Version>2.3.0</Version>
<Version>2.4.0</Version>
<Description>OpenAI Chat Completions API (ChatGPT) integration with DI and EF Core supporting. It allows you to use the API in your .NET applications. Also, the client supports streaming responses (like ChatGPT) via async streams.</Description>
<RepositoryUrl>https://github.com/rodion-m/ChatGPT_API_dotnet</RepositoryUrl>
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
Expand All @@ -25,8 +25,8 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.4">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
16 changes: 8 additions & 8 deletions OpenAI.ChatGpt/ChatGPT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class ChatGPT : IDisposable
private readonly ITimeProvider _clock;
private readonly ChatGPTConfig? _config;
private readonly OpenAiClient _client;
private Chat? _currentChat;
private ChatService? _currentChat;

/// <summary>
/// Use this constructor to create chat conversation provider for the specific user.
Expand Down Expand Up @@ -53,7 +53,7 @@ public ChatGPT(
/// <summary>
/// If you don't have users and don't want to save messages into database use this method.
/// </summary>
public static Task<Chat> CreateInMemoryChat(
public static Task<ChatService> CreateInMemoryChat(
string apiKey,
ChatGPTConfig? config = null,
UserOrSystemMessage? initialDialog = null,
Expand All @@ -71,7 +71,7 @@ public void Dispose()
}

/// <summary> Continues the last topic or starts a new one.</summary>
public async Task<Chat> ContinueOrStartNewTopic(CancellationToken cancellationToken = default)
public async Task<ChatService> ContinueOrStartNewTopic(CancellationToken cancellationToken = default)
{
if (_currentChat is not null) return _currentChat;
var topic = await _storage.GetMostRecentTopicOrNull(_userId, cancellationToken);
Expand All @@ -81,7 +81,7 @@ public async Task<Chat> ContinueOrStartNewTopic(CancellationToken cancellationTo
}

/// <summary> Starts a new topic. </summary>
public async Task<Chat> StartNewTopic(
public async Task<ChatService> StartNewTopic(
string? name = null,
ChatGPTConfig? config = null,
UserOrSystemMessage? initialDialog = null,
Expand Down Expand Up @@ -110,7 +110,7 @@ private IEnumerable<PersistentChatMessage> ConvertToPersistentMessages(ChatCompl
);
}

public async Task<Chat> SetTopic(Guid topicId, CancellationToken cancellationToken = default)
public async Task<ChatService> SetTopic(Guid topicId, CancellationToken cancellationToken = default)
{
var topic = await _storage.GetTopic(_userId, topicId, cancellationToken);
if (topic is null)
Expand All @@ -120,17 +120,17 @@ public async Task<Chat> SetTopic(Guid topicId, CancellationToken cancellationTok
return await SetTopic(topic, cancellationToken);
}

private Task<Chat> SetTopic(Topic topic, CancellationToken cancellationToken = default)
private Task<ChatService> SetTopic(Topic topic, CancellationToken cancellationToken = default)
{
if (topic == null) throw new ArgumentNullException(nameof(topic));
_currentChat = CreateChat(topic, false, false);
return Task.FromResult(_currentChat);
}

private Chat CreateChat(Topic topic, bool isNew, bool clearOnDisposal)
private ChatService CreateChat(Topic topic, bool isNew, bool clearOnDisposal)
{
if (topic == null) throw new ArgumentNullException(nameof(topic));
return new Chat(_storage, _clock, _client, _userId, topic, isNew, clearOnDisposal);
return new ChatService(_storage, _clock, _client, _userId, topic, isNew, clearOnDisposal);
}

public async Task<IReadOnlyList<Topic>> GetTopics(CancellationToken cancellationToken = default)
Expand Down
4 changes: 2 additions & 2 deletions OpenAI.ChatGpt/Chat.cs → OpenAI.ChatGpt/ChatService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace OpenAI.ChatGpt;
/// </summary>
/// <remarks>Not thread-safe. Use one instance per user.</remarks>
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")]
public class Chat : IDisposable, IAsyncDisposable
public class ChatService : IDisposable, IAsyncDisposable
{
public Topic Topic { get; }
public string UserId { get; }
Expand All @@ -31,7 +31,7 @@ public class Chat : IDisposable, IAsyncDisposable
private readonly bool _clearOnDisposal;
private CancellationTokenSource? _cts;

internal Chat(
internal ChatService(
IChatHistoryStorage chatHistoryStorage,
ITimeProvider clock,
OpenAiClient client,
Expand Down
2 changes: 1 addition & 1 deletion OpenAI.ChatGpt/OpenAI.ChatGpt.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<PackageId>OpenAI.ChatGPT</PackageId>
<PackageProjectUrl>https://github.com/rodion-m/ChatGPT_API_dotnet</PackageProjectUrl>
<Product>OpenAI ChatGPT integration for .NET</Product>
<Version>2.3.0</Version>
<Version>2.4.0</Version>
<Description>.NET integration for ChatGPT with streaming responses supporting (like ChatGPT) via async streams.</Description>
<RepositoryUrl>https://github.com/rodion-m/ChatGPT_API_dotnet</RepositoryUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand Down
12 changes: 6 additions & 6 deletions samples/ChatGpt.BlazorExample/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ else
string _errorMessage = "";
bool _processing = false;
int _totalTokens = 0;
private Chat _chat;
private Chat _chatService;
private string _userId = "test-user-id";

protected override async Task OnInitializedAsync()
Expand All @@ -146,10 +146,10 @@ else

private async Task CreateNewChat()
{
if(_chat != null) await _chat.DisposeAsync();
if(_chatService != null) await _chatService.DisposeAsync();
var chatGpt = await ChatGPTFactory.Create(_userId);
_chat = await chatGpt.ContinueOrStartNewTopic();
_messages = (await _chat.GetMessages()).Select(m => (m.Role, m.Content))
_chatService = await chatGpt.ContinueOrStartNewTopic();
_messages = (await _chatService.GetMessages()).Select(m => (m.Role, m.Content))
.ToList();
}

Expand Down Expand Up @@ -177,14 +177,14 @@ else

// Clear any previous error messages
_errorMessage = "";
var response = await _chat.GetNextMessageResponse(_prompt);
var response = await _chatService.GetNextMessageResponse(_prompt);

// Create a new MessageSave object with the user's prompt and other
// details and add it to the messages list
_messages.Add((ChatCompletionRoles.User, _prompt));
_messages.Add((ChatCompletionRoles.Assistant, response));

_totalTokens = (int) (_chat.LastResponse?.Usage.TotalTokens ?? 0);
_totalTokens = (int) (_chatService.LastResponse?.Usage.TotalTokens ?? 0);
}
catch (Exception ex)
{
Expand Down
4 changes: 2 additions & 2 deletions samples/ChatGpt.ConsoleExample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@

var apiKey = LoadApiKey();
var config = new ChatGPTConfig() { MaxTokens = 300 };
await using Chat chat = await ChatGPT.CreateInMemoryChat(apiKey, config);
await using ChatService chatService = await ChatGPT.CreateInMemoryChat(apiKey, config);

Console.Write("User: ");
while (Console.ReadLine() is { } userMessage)
{
var response = await chat.GetNextMessageResponse(userMessage);
var response = await chatService.GetNextMessageResponse(userMessage);
Console.WriteLine($"ChatGPT: {response.Trim()}");
Console.Write("User: ");
}
Expand Down
10 changes: 5 additions & 5 deletions samples/ChatGpt.SpectreConsoleExample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,21 @@

var name = Console.Ask<string?>("What's your [green]name[/]?") ?? "Me";
var apiKey = LoadApiKey();
await using Chat chat = await ChatGPT.CreateInMemoryChat(
await using ChatService chatService = await ChatGPT.CreateInMemoryChat(
apiKey,
config: new ChatGPTConfig() { MaxTokens = 200 },
initialDialog: Dialog.StartAsSystem($"You are helpful assistant for a person named {name}.")
);
SetupCancellation(chat);
SetupCancellation(chatService);

Console.MarkupLine("[underline yellow]Start chat. Now ask something ChatGPT...[/]");
while (Console.Ask<string>($"[underline green]{name}[/]: ") is { } userMessage)
{
Console.Markup("[underline red]ChatGPT[/]: ");
var stream = chat.StreamNextMessageResponse(userMessage, throwOnCancellation: false);
var stream = chatService.StreamNextMessageResponse(userMessage, throwOnCancellation: false);
await foreach (string chunk in stream.SkipWhile(string.IsNullOrWhiteSpace))
{
if (!chat.IsCancelled) Console.Write(chunk);
if (!chatService.IsCancelled) Console.Write(chunk);
}

Console.WriteLine();
Expand All @@ -39,7 +39,7 @@ string LoadApiKey()
return key;
}

void SetupCancellation(Chat chat)
void SetupCancellation(ChatService chat)
{
System.Console.CancelKeyPress += (_, args) =>
{
Expand Down
14 changes: 7 additions & 7 deletions tests/OpenAI.ChatGpt.IntegrationTests/ChatGptTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ public class ChatGptTests
[Fact]
public async void Stream_chatgpt_response_cancellation_throws_exception()
{
Chat chat = await CreateInMemoryChat();
ChatService chatService = await CreateInMemoryChat();
const string text = "Write numbers from 1 to 50";
await FluentActions.Invoking(
async () =>
{
await foreach (var _ in chat.StreamNextMessageResponse(text))
await foreach (var _ in chatService.StreamNextMessageResponse(text))
{
chat.Stop();
chatService.Stop();
}
})
.Should().ThrowAsync<OperationCanceledException>();
Expand All @@ -21,20 +21,20 @@ await FluentActions.Invoking(
[Fact]
public async void Stream_chatgpt_response_cancellation_with_throwOnCancellation_false_stopped_silently()
{
Chat chat = await CreateInMemoryChat();
ChatService chatService = await CreateInMemoryChat();
const string text = "Write numbers from 1 to 50";
await FluentActions.Invoking(
async () =>
{
await foreach (var _ in chat.StreamNextMessageResponse(text, throwOnCancellation: false))
await foreach (var _ in chatService.StreamNextMessageResponse(text, throwOnCancellation: false))
{
chat.Stop();
chatService.Stop();
}
})
.Should().NotThrowAsync();
}

private static async Task<Chat> CreateInMemoryChat()
private static async Task<ChatService> CreateInMemoryChat()
{
return await ChatGPT.CreateInMemoryChat(Helpers.GetKeyFromEnvironment("OPENAI_API_KEY"),
new ChatGPTConfig()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ public async void AddChatGptInMemoryIntegration_with_Chat_injection_works()
var services = CreateServiceCollection();

// Act
services.AddChatGptInMemoryIntegration(injectInMemoryChat: true);
services.AddChatGptInMemoryIntegration(injectInMemoryChatService: true);

// Assert
await using var provider = services.BuildServiceProvider();

var storage = provider.GetRequiredService<IChatHistoryStorage>();
storage.Should().BeOfType<InMemoryChatHistoryStorage>();

_ = provider.GetRequiredService<Chat>();
_ = provider.GetRequiredService<ChatService>();
}

[Fact]
Expand Down

0 comments on commit 67038e0

Please sign in to comment.