diff --git a/Olive.OpenAI/Olive.OpenAI/Olive.OpenAI.csproj b/Olive.OpenAI/Olive.OpenAI/Olive.OpenAI.csproj index 6db92020..055b6138 100644 --- a/Olive.OpenAI/Olive.OpenAI/Olive.OpenAI.csproj +++ b/Olive.OpenAI/Olive.OpenAI/Olive.OpenAI.csproj @@ -2,7 +2,7 @@ netstandard2.0 - 2.1.190 + 2.1.191 diff --git a/Olive.OpenAI/Olive.OpenAI/OpenAI.cs b/Olive.OpenAI/Olive.OpenAI/OpenAI.cs index 72592298..758a2aa9 100644 --- a/Olive.OpenAI/Olive.OpenAI/OpenAI.cs +++ b/Olive.OpenAI/Olive.OpenAI/OpenAI.cs @@ -19,31 +19,35 @@ public OpenAI(string? key = null) var model = Olive.Config.Get("OpenAI:Models:ChatModel").Or("gpt-4o"); var apiKey = key.Or(Olive.Config.Get("OpenAI:Key")); - if (key.IsEmpty()) + if (apiKey.IsEmpty()) { throw new ArgumentException("The api key was not provided. Please set it in the AppSettings or webConfig in the OpenAI:APIKey entry"); } - ChatClient client = new(model, apiKey); + _client = new(model, apiKey); } public async Task GetResponse(string[] messages, string instruction = null) { - if (messages.None()) - { - throw new ArgumentException("There are no messages"); - } - var chatMessages = new List(); - if (instruction.HasValue()) - { - chatMessages.Add(new SystemChatMessage(instruction)); - } - chatMessages.AddRange(messages.Select(x => new UserChatMessage(x))); - + var chatMessages = GetChatMessages(messages, instruction); ChatCompletion completion = await this._client.CompleteChatAsync(chatMessages); return completion.Content[0].Text; } public async IAsyncEnumerable GetResponseStream(string[] messages, string instruction = null) + { + var chatMessages = GetChatMessages(messages, instruction); + var completionUpdates = this._client.CompleteChatStreamingAsync(chatMessages); + await foreach (var completionUpdate in completionUpdates) + { + if (completionUpdate.ContentUpdate.Count > 0) + { + var response = completionUpdate.ContentUpdate[0].Text; + yield return response; + } + } + } + + List GetChatMessages(string[] messages, string instruction = null) { if (messages.None()) { @@ -56,16 +60,7 @@ public async IAsyncEnumerable GetResponseStream(string[] messages, strin chatMessages.Add(new SystemChatMessage(instruction)); } chatMessages.AddRange(messages.Select(x => new UserChatMessage(x))); - - var completionUpdates = this._client.CompleteChatStreamingAsync(chatMessages); - await foreach (var completionUpdate in completionUpdates) - { - if (completionUpdate.ContentUpdate.Count > 0) - { - var response = completionUpdate.ContentUpdate[0].Text; - yield return response; - } - } + return chatMessages; } }