|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using System.Linq; |
| 3 | +using System.Net.Http.Headers; |
| 4 | +using System.Text; |
| 5 | +using System.Text.Json; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | +using Microsoft.Extensions.Options; |
| 8 | +using ModelContextProtocol.Client; |
| 9 | +using OpenAI.Responses; |
| 10 | + |
| 11 | +namespace EssentialCSharp.Chat.Common.Services; |
| 12 | + |
| 13 | +public partial class LocalChatService : IChatCompletionService |
| 14 | +{ |
| 15 | + private const int MaxConversationMessages = 20; |
| 16 | + private readonly AIOptions _Options; |
| 17 | + private readonly IHttpClientFactory _HttpClientFactory; |
| 18 | + private readonly ILogger<LocalChatService> _Logger; |
| 19 | + private readonly ConcurrentDictionary<string, List<LocalChatMessage>> _ConversationHistory = new(); |
| 20 | + |
| 21 | + public bool IsAvailable => true; |
| 22 | + |
| 23 | + public LocalChatService(IOptions<AIOptions> options, IHttpClientFactory httpClientFactory, ILogger<LocalChatService> logger) |
| 24 | + { |
| 25 | + _Options = options.Value; |
| 26 | + _HttpClientFactory = httpClientFactory; |
| 27 | + _Logger = logger; |
| 28 | + } |
| 29 | + |
| 30 | + public async Task<(string response, string responseId)> GetChatCompletion( |
| 31 | + string prompt, |
| 32 | + string? systemPrompt = null, |
| 33 | + string? previousResponseId = null, |
| 34 | + McpClient? mcpClient = null, |
| 35 | +#pragma warning disable OPENAI001 |
| 36 | + IEnumerable<ResponseTool>? tools = null, |
| 37 | + ResponseReasoningEffortLevel? reasoningEffortLevel = null, |
| 38 | +#pragma warning restore OPENAI001 |
| 39 | + bool enableContextualSearch = false, |
| 40 | + string? endUserId = null, |
| 41 | + CancellationToken cancellationToken = default) |
| 42 | + { |
| 43 | + var (client, history, jsonPayload) = PrepareRequest(prompt, systemPrompt, previousResponseId); |
| 44 | + |
| 45 | + HttpResponseMessage response; |
| 46 | + using var request = new HttpRequestMessage(HttpMethod.Post, "/v1/chat/completions") |
| 47 | + { |
| 48 | + Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json") |
| 49 | + }; |
| 50 | + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "local-dev-key"); |
| 51 | + |
| 52 | + try |
| 53 | + { |
| 54 | + response = await client.SendAsync(request, cancellationToken); |
| 55 | + } |
| 56 | + catch (HttpRequestException ex) |
| 57 | + { |
| 58 | + throw new ChatBackendUnavailableException("Local AI backend is unavailable.", ex); |
| 59 | + } |
| 60 | + catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested) |
| 61 | + { |
| 62 | + throw new ChatBackendUnavailableException("Local AI backend timed out.", ex); |
| 63 | + } |
| 64 | + |
| 65 | + using (response) |
| 66 | + { |
| 67 | + var body = await response.Content.ReadAsStringAsync(cancellationToken); |
| 68 | + |
| 69 | + if (!response.IsSuccessStatusCode) |
| 70 | + { |
| 71 | + LogLocalRequestFailed(_Logger, (int)response.StatusCode, body); |
| 72 | + throw new ChatBackendUnavailableException("Local AI backend returned a non-success status."); |
| 73 | + } |
| 74 | + |
| 75 | + try |
| 76 | + { |
| 77 | + var (text, responseId) = ParseResponse(body); |
| 78 | + history.Add(new LocalChatMessage("user", prompt)); |
| 79 | + history.Add(new LocalChatMessage("assistant", text)); |
| 80 | + _ConversationHistory[responseId] = history.TakeLast(MaxConversationMessages).ToList(); |
| 81 | + return (text, responseId); |
| 82 | + } |
| 83 | + catch (Exception ex) when (ex is JsonException || ex is InvalidOperationException || ex is NotSupportedException) |
| 84 | + { |
| 85 | + throw new ChatBackendUnavailableException("Local AI backend returned an invalid response.", ex); |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + public async IAsyncEnumerable<(string text, string? responseId)> GetChatCompletionStream( |
| 91 | + string prompt, |
| 92 | + string? systemPrompt = null, |
| 93 | + string? previousResponseId = null, |
| 94 | + McpClient? mcpClient = null, |
| 95 | +#pragma warning disable OPENAI001 |
| 96 | + IEnumerable<ResponseTool>? tools = null, |
| 97 | + ResponseReasoningEffortLevel? reasoningEffortLevel = null, |
| 98 | +#pragma warning restore OPENAI001 |
| 99 | + bool enableContextualSearch = false, |
| 100 | + string? endUserId = null, |
| 101 | + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 102 | + { |
| 103 | + var (response, responseId) = await GetChatCompletion( |
| 104 | + prompt, |
| 105 | + systemPrompt, |
| 106 | + previousResponseId, |
| 107 | + mcpClient, |
| 108 | + tools, |
| 109 | + reasoningEffortLevel, |
| 110 | + enableContextualSearch, |
| 111 | + endUserId, |
| 112 | + cancellationToken); |
| 113 | + |
| 114 | + if (!string.IsNullOrEmpty(response)) |
| 115 | + { |
| 116 | + yield return (response, responseId: null); |
| 117 | + } |
| 118 | + |
| 119 | + yield return (string.Empty, responseId); |
| 120 | + } |
| 121 | + |
| 122 | + private (HttpClient Client, List<LocalChatMessage> History, string JsonPayload) PrepareRequest( |
| 123 | + string prompt, |
| 124 | + string? systemPrompt, |
| 125 | + string? previousResponseId = null) |
| 126 | + { |
| 127 | + var client = _HttpClientFactory.CreateClient("LocalAIChat"); |
| 128 | + var effectiveSystemPrompt = string.IsNullOrWhiteSpace(systemPrompt) ? _Options.SystemPrompt : systemPrompt; |
| 129 | + var history = ResolveHistory(previousResponseId); |
| 130 | + |
| 131 | + var messages = new List<object> { new { role = "system", content = effectiveSystemPrompt } }; |
| 132 | + messages.AddRange(history.Select(m => new { role = m.Role, content = m.Content })); |
| 133 | + messages.Add(new { role = "user", content = prompt }); |
| 134 | + |
| 135 | + var payload = new |
| 136 | + { |
| 137 | + model = _Options.LocalChatModel, |
| 138 | + messages, |
| 139 | + stream = false |
| 140 | + }; |
| 141 | + |
| 142 | + return (client, history, JsonSerializer.Serialize(payload)); |
| 143 | + } |
| 144 | + |
| 145 | + private List<LocalChatMessage> ResolveHistory(string? previousResponseId) |
| 146 | + { |
| 147 | + if (string.IsNullOrWhiteSpace(previousResponseId)) |
| 148 | + return []; |
| 149 | + |
| 150 | + return _ConversationHistory.TryGetValue(previousResponseId, out var history) |
| 151 | + ? [.. history] |
| 152 | + : []; |
| 153 | + } |
| 154 | + |
| 155 | + private static (string Text, string ResponseId) ParseResponse(string body) |
| 156 | + { |
| 157 | + using var doc = JsonDocument.Parse(body); |
| 158 | + var root = doc.RootElement; |
| 159 | + |
| 160 | + string responseId = root.TryGetProperty("id", out var idProp) && idProp.ValueKind == JsonValueKind.String |
| 161 | + ? idProp.GetString() ?? Guid.NewGuid().ToString("N") |
| 162 | + : Guid.NewGuid().ToString("N"); |
| 163 | + |
| 164 | + if (root.TryGetProperty("choices", out var choices) |
| 165 | + && choices.ValueKind == JsonValueKind.Array |
| 166 | + && choices.GetArrayLength() > 0) |
| 167 | + { |
| 168 | + var choice = choices[0]; |
| 169 | + if (choice.TryGetProperty("message", out var message) |
| 170 | + && message.TryGetProperty("content", out var content) |
| 171 | + && content.ValueKind == JsonValueKind.String) |
| 172 | + { |
| 173 | + return (content.GetString() ?? string.Empty, responseId); |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + if (root.TryGetProperty("message", out var ollamaMessage) |
| 178 | + && ollamaMessage.TryGetProperty("content", out var ollamaContent) |
| 179 | + && ollamaContent.ValueKind == JsonValueKind.String) |
| 180 | + { |
| 181 | + return (ollamaContent.GetString() ?? string.Empty, responseId); |
| 182 | + } |
| 183 | + |
| 184 | + throw new InvalidOperationException("Local AI response did not contain any content."); |
| 185 | + } |
| 186 | + |
| 187 | + [LoggerMessage(Level = LogLevel.Warning, Message = "Local chat request failed with status {StatusCode}. Body: {Body}")] |
| 188 | + private static partial void LogLocalRequestFailed(ILogger logger, int statusCode, string body); |
| 189 | + |
| 190 | + private sealed record LocalChatMessage(string Role, string Content); |
| 191 | +} |
0 commit comments