|
| 1 | +using Azure; |
| 2 | +using Azure.AI.OpenAI; |
| 3 | +using BotSharp.Abstraction; |
| 4 | +using BotSharp.Abstraction.Models; |
| 5 | +using System; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.IO; |
| 8 | +using System.Threading.Tasks; |
| 9 | + |
| 10 | +namespace BotSharp.Platform.AzureAi; |
| 11 | + |
| 12 | +public class ChatCompletionHandler : IChatCompletionHandler |
| 13 | +{ |
| 14 | + private readonly AzureAiSettings _settings; |
| 15 | + |
| 16 | + public ChatCompletionHandler(AzureAiSettings settings) |
| 17 | + { |
| 18 | + _settings = settings; |
| 19 | + } |
| 20 | + |
| 21 | + public async Task GetChatCompletionsAsync(string text, |
| 22 | + Func<string> GetInstruction, |
| 23 | + Func<List<RoleDialogModel>> GetChatHistory, |
| 24 | + Func<string, Task> onChunkReceived, |
| 25 | + Func<Task> onChunkCompleted) |
| 26 | + { |
| 27 | + var client = new OpenAIClient(new Uri(_settings.Endpoint), new AzureKeyCredential(_settings.ApiKey)); |
| 28 | + var chatCompletionsOptions = PrepareOptions(text, GetInstruction, GetChatHistory); |
| 29 | + |
| 30 | + var response = await client.GetChatCompletionsStreamingAsync(_settings.DeploymentModel, chatCompletionsOptions); |
| 31 | + using StreamingChatCompletions streaming = response.Value; |
| 32 | + |
| 33 | + string content = ""; |
| 34 | + await foreach (var choice in streaming.GetChoicesStreaming()) |
| 35 | + { |
| 36 | + await foreach (var message in choice.GetMessageStreaming()) |
| 37 | + { |
| 38 | + if (message.Content == null) |
| 39 | + continue; |
| 40 | + Console.Write(message.Content); |
| 41 | + content += message.Content; |
| 42 | + await onChunkReceived(message.Content); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + Console.WriteLine(); |
| 47 | + await onChunkCompleted(); |
| 48 | + } |
| 49 | + |
| 50 | + private ChatCompletionsOptions PrepareOptions(string text, |
| 51 | + Func<string> GetInstruction, |
| 52 | + Func<List<RoleDialogModel>> GetChatHistory) |
| 53 | + { |
| 54 | + var prompt = File.ReadAllText(_settings.InstructionFile); |
| 55 | + var chatCompletionsOptions = new ChatCompletionsOptions() |
| 56 | + { |
| 57 | + Messages = |
| 58 | + { |
| 59 | + new ChatMessage(ChatRole.System, prompt) |
| 60 | + } |
| 61 | + }; |
| 62 | + |
| 63 | + return chatCompletionsOptions; |
| 64 | + } |
| 65 | +} |
0 commit comments