|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using System.Runtime.CompilerServices; |
| 3 | +using Microsoft.Extensions.AI; |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using Microsoft.Extensions.Options; |
| 6 | +using ModelContextProtocol.Client; |
| 7 | +using OpenAI.Responses; |
| 8 | + |
| 9 | +namespace EssentialCSharp.Chat.Common.Services; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// Local AI chat service using IChatClient (e.g. Ollama via CommunityToolkit.Aspire.OllamaSharp). |
| 13 | +/// Compared to the Azure path: conversation history is in-memory only (lost on restart), |
| 14 | +/// ResponseTool/ReasoningEffortLevel params are silently ignored, and vector search (RAG) |
| 15 | +/// is disabled. Intended for local development without Azure credentials. |
| 16 | +/// </summary> |
| 17 | +public class LocalAIChatService : IAIChatService |
| 18 | +{ |
| 19 | + private readonly IChatClient _chatClient; |
| 20 | + private readonly AIOptions _options; |
| 21 | + private readonly ILogger<LocalAIChatService> _logger; |
| 22 | + |
| 23 | + // Synthetic conversation history keyed by GUID responseId. |
| 24 | + // In-memory only — not shared across instances and lost on restart. |
| 25 | + // ConcurrentDictionary prevents crashes from parallel requests (e.g., two chat tabs). |
| 26 | + private readonly ConcurrentDictionary<string, List<ChatMessage>> _conversations = new(); |
| 27 | + |
| 28 | + public LocalAIChatService( |
| 29 | + IOptions<AIOptions> options, |
| 30 | + IChatClient chatClient, |
| 31 | + ILogger<LocalAIChatService> logger) |
| 32 | + { |
| 33 | + _options = options.Value; |
| 34 | + _chatClient = chatClient; |
| 35 | + _logger = logger; |
| 36 | + } |
| 37 | + |
| 38 | + public async Task<(string response, string responseId)> GetChatCompletion( |
| 39 | + string prompt, |
| 40 | + string? systemPrompt = null, |
| 41 | + string? previousResponseId = null, |
| 42 | + IMcpClient? mcpClient = null, |
| 43 | +#pragma warning disable OPENAI001 |
| 44 | + IEnumerable<ResponseTool>? tools = null, |
| 45 | + ResponseReasoningEffortLevel? reasoningEffortLevel = null, |
| 46 | +#pragma warning restore OPENAI001 |
| 47 | + bool enableContextualSearch = false, |
| 48 | + CancellationToken cancellationToken = default) |
| 49 | + { |
| 50 | + WarnUnsupportedFeatures(tools, reasoningEffortLevel, enableContextualSearch); |
| 51 | + |
| 52 | + var messages = BuildMessages(prompt, systemPrompt, previousResponseId); |
| 53 | + var response = await _chatClient.GetResponseAsync(messages, cancellationToken: cancellationToken); |
| 54 | + var responseText = response.Text ?? string.Empty; |
| 55 | + var responseId = SaveConversation(messages, responseText, previousResponseId); |
| 56 | + return (responseText, responseId); |
| 57 | + } |
| 58 | + |
| 59 | + public async IAsyncEnumerable<(string text, string? responseId)> GetChatCompletionStream( |
| 60 | + string prompt, |
| 61 | + string? systemPrompt = null, |
| 62 | + string? previousResponseId = null, |
| 63 | + IMcpClient? mcpClient = null, |
| 64 | +#pragma warning disable OPENAI001 |
| 65 | + IEnumerable<ResponseTool>? tools = null, |
| 66 | + ResponseReasoningEffortLevel? reasoningEffortLevel = null, |
| 67 | +#pragma warning restore OPENAI001 |
| 68 | + bool enableContextualSearch = false, |
| 69 | + [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 70 | + { |
| 71 | + WarnUnsupportedFeatures(tools, reasoningEffortLevel, enableContextualSearch); |
| 72 | + |
| 73 | + var messages = BuildMessages(prompt, systemPrompt, previousResponseId); |
| 74 | + var fullResponse = new System.Text.StringBuilder(); |
| 75 | + |
| 76 | + await foreach (var update in _chatClient.GetStreamingResponseAsync(messages, cancellationToken: cancellationToken)) |
| 77 | + { |
| 78 | + if (!string.IsNullOrEmpty(update.Text)) |
| 79 | + { |
| 80 | + fullResponse.Append(update.Text); |
| 81 | + yield return (update.Text, null); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + var responseId = SaveConversation(messages, fullResponse.ToString(), previousResponseId); |
| 86 | + yield return (string.Empty, responseId); |
| 87 | + } |
| 88 | + |
| 89 | +#pragma warning disable OPENAI001 |
| 90 | + private void WarnUnsupportedFeatures( |
| 91 | + IEnumerable<ResponseTool>? tools, |
| 92 | + ResponseReasoningEffortLevel? reasoningEffortLevel, |
| 93 | + bool enableContextualSearch) |
| 94 | +#pragma warning restore OPENAI001 |
| 95 | + { |
| 96 | + if (tools is not null || reasoningEffortLevel is not null) |
| 97 | + _logger.LogWarning("LocalAIChatService: ResponseTool and ReasoningEffortLevel are Azure-specific and are ignored in local mode."); |
| 98 | + |
| 99 | + if (enableContextualSearch) |
| 100 | + _logger.LogWarning("LocalAIChatService: Vector search (RAG) is disabled in local mode (Phase 1). Run in Azure mode to enable contextual search."); |
| 101 | + } |
| 102 | + |
| 103 | + private List<ChatMessage> BuildMessages(string prompt, string? systemPrompt, string? previousResponseId) |
| 104 | + { |
| 105 | + var messages = new List<ChatMessage>(); |
| 106 | + |
| 107 | + var sys = string.IsNullOrWhiteSpace(systemPrompt) ? _options.SystemPrompt : systemPrompt; |
| 108 | + if (!string.IsNullOrWhiteSpace(sys)) |
| 109 | + messages.Add(new ChatMessage(ChatRole.System, sys)); |
| 110 | + |
| 111 | + if (previousResponseId is not null && _conversations.TryGetValue(previousResponseId, out var history)) |
| 112 | + messages.AddRange(history); |
| 113 | + |
| 114 | + messages.Add(new ChatMessage(ChatRole.User, prompt)); |
| 115 | + return messages; |
| 116 | + } |
| 117 | + |
| 118 | + private string SaveConversation(List<ChatMessage> messages, string assistantResponse, string? previousResponseId) |
| 119 | + { |
| 120 | + var history = messages.Where(m => m.Role != ChatRole.System).ToList(); |
| 121 | + history.Add(new ChatMessage(ChatRole.Assistant, assistantResponse)); |
| 122 | + |
| 123 | + var newId = Guid.NewGuid().ToString("N"); |
| 124 | + _conversations[newId] = history; |
| 125 | + |
| 126 | + // Remove previous entry to avoid unbounded memory growth. |
| 127 | + // TryRemove is safe on ConcurrentDictionary. |
| 128 | + if (previousResponseId is not null) |
| 129 | + _conversations.TryRemove(previousResponseId, out _); |
| 130 | + |
| 131 | + return newId; |
| 132 | + } |
| 133 | +} |
0 commit comments