|
| 1 | +using System.Runtime.CompilerServices; |
| 2 | +using Microsoft.Extensions.Options; |
| 3 | +using Microsoft.SemanticKernel; |
| 4 | +using Microsoft.SemanticKernel.ChatCompletion; |
| 5 | +using Microsoft.SemanticKernel.Services; |
| 6 | +using Sdcb.DashScope; |
| 7 | +using Sdcb.DashScope.TextGeneration; |
| 8 | + |
| 9 | +namespace Cnblogs.SemanticKernel.Connectors.DashScope; |
| 10 | + |
| 11 | +public sealed class DashScopeChatCompletionService : IChatCompletionService |
| 12 | +{ |
| 13 | + private readonly DashScopeClient _dashScopeClient; |
| 14 | + private readonly string _modelId; |
| 15 | + private readonly Dictionary<string, object?> _attribues = []; |
| 16 | + |
| 17 | + public DashScopeChatCompletionService( |
| 18 | + IOptions<DashScopeClientOptions> options, |
| 19 | + HttpClient httpClient) |
| 20 | + { |
| 21 | + _dashScopeClient = new(options.Value.ApiKey, httpClient); |
| 22 | + _modelId = options.Value.ModelId; |
| 23 | + _attribues.Add(AIServiceExtensions.ModelIdKey, _modelId); |
| 24 | + } |
| 25 | + |
| 26 | + public IReadOnlyDictionary<string, object?> Attributes => _attribues; |
| 27 | + |
| 28 | + public async Task<IReadOnlyList<ChatMessageContent>> GetChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default) |
| 29 | + { |
| 30 | + var chatMessages = chatHistory.ToChatMessages(); |
| 31 | + var chatParameters = executionSettings?.ToChatParameters(); |
| 32 | + var response = await _dashScopeClient.TextGeneration.Chat(_modelId, chatMessages, chatParameters, cancellationToken); |
| 33 | + return [new ChatMessageContent(new AuthorRole(chatMessages[0].Role), response.Output.Text)]; |
| 34 | + } |
| 35 | + |
| 36 | + public async IAsyncEnumerable<StreamingChatMessageContent> GetStreamingChatMessageContentsAsync( |
| 37 | + ChatHistory chatHistory, |
| 38 | + PromptExecutionSettings? executionSettings = null, |
| 39 | + Kernel? kernel = null, |
| 40 | + [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 41 | + { |
| 42 | + var chatMessages = chatHistory.ToChatMessages(); |
| 43 | + var chatParameters = executionSettings?.ToChatParameters() ?? new ChatParameters(); |
| 44 | + chatParameters.IncrementalOutput = true; |
| 45 | + |
| 46 | + var responses = _dashScopeClient.TextGeneration.ChatStreamed(_modelId, chatMessages, chatParameters, cancellationToken); |
| 47 | + |
| 48 | + await foreach (var response in responses) |
| 49 | + { |
| 50 | + yield return new StreamingChatMessageContent(new AuthorRole(chatMessages[0].Role), response.Output.Text); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments