| | | 1 | | using System.Net.Http.Headers; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | using System.Text; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | |
| | | 6 | | using Microsoft.Extensions.AI; |
| | | 7 | | |
| | | 8 | | namespace NexusLabs.Needlr.Copilot; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// <see cref="IChatClient"/> implementation that calls the GitHub Copilot chat completions |
| | | 12 | | /// API directly (raw model endpoint, no CLI agent harness). Only tools explicitly provided |
| | | 13 | | /// via <see cref="ChatOptions.Tools"/> are sent; no built-in Copilot CLI tools are injected. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <remarks> |
| | | 16 | | /// <para> |
| | | 17 | | /// Authentication follows a two-step flow: a GitHub OAuth token (discovered from |
| | | 18 | | /// <c>apps.json</c>, environment variables, or an explicit value) is exchanged for a |
| | | 19 | | /// short-lived Copilot API bearer token via the internal GitHub API endpoint. |
| | | 20 | | /// </para> |
| | | 21 | | /// <para> |
| | | 22 | | /// Plug this into Needlr's agent framework via |
| | | 23 | | /// <c>.UsingChatClient(new CopilotChatClient())</c> — no Copilot-specific |
| | | 24 | | /// syringe extensions required. |
| | | 25 | | /// </para> |
| | | 26 | | /// </remarks> |
| | | 27 | | /// <example> |
| | | 28 | | /// <code> |
| | | 29 | | /// // Minimal usage — auto-discovers token from Copilot CLI login: |
| | | 30 | | /// IChatClient client = new CopilotChatClient(); |
| | | 31 | | /// |
| | | 32 | | /// // With explicit model and token: |
| | | 33 | | /// IChatClient client = new CopilotChatClient(new CopilotChatClientOptions |
| | | 34 | | /// { |
| | | 35 | | /// DefaultModel = "gpt-5.4", |
| | | 36 | | /// GitHubToken = "gho_xxx", |
| | | 37 | | /// }); |
| | | 38 | | /// </code> |
| | | 39 | | /// </example> |
| | | 40 | | public sealed class CopilotChatClient : IChatClient |
| | | 41 | | { |
| | | 42 | | private readonly ICopilotTokenProvider _tokenProvider; |
| | | 43 | | private readonly HttpClient _httpClient; |
| | | 44 | | private readonly CopilotChatClientOptions _options; |
| | | 45 | | private readonly bool _ownsHttpClient; |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Creates a new <see cref="CopilotChatClient"/> with optional configuration and HTTP client. |
| | | 49 | | /// Token discovery uses <see cref="CopilotChatClientOptions.TokenSource"/>. |
| | | 50 | | /// </summary> |
| | | 51 | | /// <param name="options">Configuration options. Uses defaults when <c>null</c>.</param> |
| | | 52 | | /// <param name="httpClient"> |
| | | 53 | | /// Optional HTTP client (shared with token provider). Created internally if <c>null</c>. |
| | | 54 | | /// Pass a pre-configured <see cref="HttpClient"/> to control timeout and other HTTP settings. |
| | | 55 | | /// The default <see cref="HttpClient.Timeout"/> (100 seconds) may be too short for long-running |
| | | 56 | | /// agent pipelines — consider increasing it for workloads with large context windows. |
| | | 57 | | /// </param> |
| | | 58 | | /// <example> |
| | | 59 | | /// <code> |
| | | 60 | | /// // Default timeout (100s) — suitable for short interactions |
| | | 61 | | /// var client = new CopilotChatClient(options); |
| | | 62 | | /// |
| | | 63 | | /// // Extended timeout for pipeline workloads with large context windows |
| | | 64 | | /// var httpClient = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; |
| | | 65 | | /// var client = new CopilotChatClient(options, httpClient); |
| | | 66 | | /// </code> |
| | | 67 | | /// </example> |
| | | 68 | | public CopilotChatClient(CopilotChatClientOptions? options = null, HttpClient? httpClient = null) |
| | 12 | 69 | | : this( |
| | 12 | 70 | | new CopilotTokenProvider(options ?? new CopilotChatClientOptions(), httpClient), |
| | 12 | 71 | | options, |
| | 12 | 72 | | httpClient) |
| | | 73 | | { |
| | 12 | 74 | | } |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// Creates a new <see cref="CopilotChatClient"/> with a custom token provider. |
| | | 78 | | /// </summary> |
| | | 79 | | /// <param name="tokenProvider">Supplies Copilot API bearer tokens.</param> |
| | | 80 | | /// <param name="options">Configuration options. Uses defaults when <c>null</c>.</param> |
| | | 81 | | /// <param name="httpClient"> |
| | | 82 | | /// Optional HTTP client. Created internally if <c>null</c>. Pass a pre-configured |
| | | 83 | | /// <see cref="HttpClient"/> to control <see cref="HttpClient.Timeout"/> and other |
| | | 84 | | /// HTTP settings for long-running agent pipelines. |
| | | 85 | | /// </param> |
| | 12 | 86 | | public CopilotChatClient( |
| | 12 | 87 | | ICopilotTokenProvider tokenProvider, |
| | 12 | 88 | | CopilotChatClientOptions? options = null, |
| | 12 | 89 | | HttpClient? httpClient = null) |
| | | 90 | | { |
| | 12 | 91 | | _tokenProvider = tokenProvider ?? throw new ArgumentNullException(nameof(tokenProvider)); |
| | 12 | 92 | | _options = options ?? new CopilotChatClientOptions(); |
| | 12 | 93 | | _ownsHttpClient = httpClient is null; |
| | 12 | 94 | | _httpClient = httpClient ?? new HttpClient(); |
| | 12 | 95 | | } |
| | | 96 | | |
| | | 97 | | /// <inheritdoc /> |
| | 1 | 98 | | public ChatClientMetadata Metadata => new("github-copilot"); |
| | | 99 | | |
| | | 100 | | /// <inheritdoc /> |
| | | 101 | | public async Task<ChatResponse> GetResponseAsync( |
| | | 102 | | IEnumerable<ChatMessage> chatMessages, |
| | | 103 | | ChatOptions? options = null, |
| | | 104 | | CancellationToken cancellationToken = default) |
| | | 105 | | { |
| | 6 | 106 | | var messageList = chatMessages as IList<ChatMessage> ?? chatMessages.ToList(); |
| | 6 | 107 | | var request = BuildRequest(messageList, options, stream: false); |
| | 6 | 108 | | using var httpResponse = await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); |
| | | 109 | | |
| | 6 | 110 | | var body = await httpResponse.Content |
| | 6 | 111 | | .ReadAsStringAsync(cancellationToken) |
| | 6 | 112 | | .ConfigureAwait(false); |
| | | 113 | | |
| | 6 | 114 | | var response = JsonSerializer.Deserialize(body, CopilotJsonContext.Default.ChatCompletionResponse) |
| | 6 | 115 | | ?? throw new InvalidOperationException("Copilot API returned null response."); |
| | | 116 | | |
| | 6 | 117 | | return MapToChatResponse(response, options); |
| | 6 | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <inheritdoc /> |
| | | 121 | | public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync( |
| | | 122 | | IEnumerable<ChatMessage> chatMessages, |
| | | 123 | | ChatOptions? options = null, |
| | | 124 | | [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| | | 125 | | { |
| | 5 | 126 | | var messageList = chatMessages as IList<ChatMessage> ?? chatMessages.ToList(); |
| | 5 | 127 | | var request = BuildRequest(messageList, options, stream: true); |
| | 5 | 128 | | using var httpResponse = await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); |
| | | 129 | | |
| | 5 | 130 | | using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| | 5 | 131 | | using var reader = new StreamReader(stream, Encoding.UTF8); |
| | | 132 | | |
| | | 133 | | // Accumulate streaming tool call chunks by index. The OpenAI streaming |
| | | 134 | | // protocol sends tool calls incrementally: the first chunk for an index |
| | | 135 | | // carries the id and function name, subsequent chunks append argument |
| | | 136 | | // fragments. We buffer these and emit complete FunctionCallContent items |
| | | 137 | | // only on the final chunk (when finish_reason is "tool_calls" or the |
| | | 138 | | // stream ends). |
| | 5 | 139 | | var pendingToolCalls = new Dictionary<int, (string Id, string Name, StringBuilder Args)>(); |
| | | 140 | | |
| | | 141 | | while (true) |
| | | 142 | | { |
| | 39 | 143 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 144 | | |
| | 39 | 145 | | var line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false); |
| | | 146 | | |
| | 39 | 147 | | if (line is null) |
| | | 148 | | { |
| | | 149 | | break; |
| | | 150 | | } |
| | | 151 | | |
| | 39 | 152 | | if (string.IsNullOrWhiteSpace(line) || line.StartsWith(':')) |
| | | 153 | | { |
| | | 154 | | continue; |
| | | 155 | | } |
| | | 156 | | |
| | 22 | 157 | | if (!line.StartsWith("data: ", StringComparison.Ordinal)) |
| | | 158 | | { |
| | | 159 | | continue; |
| | | 160 | | } |
| | | 161 | | |
| | 22 | 162 | | var data = line["data: ".Length..]; |
| | | 163 | | |
| | 22 | 164 | | if (data is "[DONE]") |
| | | 165 | | { |
| | | 166 | | break; |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | ChatCompletionChunk? chunk; |
| | | 170 | | try |
| | | 171 | | { |
| | 17 | 172 | | chunk = JsonSerializer.Deserialize(data, CopilotJsonContext.Default.ChatCompletionChunk); |
| | 16 | 173 | | } |
| | 1 | 174 | | catch (JsonException) |
| | | 175 | | { |
| | 1 | 176 | | continue; |
| | | 177 | | } |
| | | 178 | | |
| | 16 | 179 | | if (chunk is null) |
| | | 180 | | { |
| | | 181 | | continue; |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | // Accumulate tool call fragments |
| | 16 | 185 | | var choice = chunk.Choices.FirstOrDefault(); |
| | 16 | 186 | | if (choice?.Delta?.ToolCalls is { Count: > 0 }) |
| | | 187 | | { |
| | 40 | 188 | | foreach (var tc in choice.Delta.ToolCalls) |
| | | 189 | | { |
| | 11 | 190 | | if (tc.Function is null) continue; |
| | | 191 | | |
| | 11 | 192 | | if (!pendingToolCalls.TryGetValue(tc.Index, out var pending)) |
| | | 193 | | { |
| | 4 | 194 | | pending = (tc.Id ?? "", tc.Function.Name ?? "", new StringBuilder()); |
| | 4 | 195 | | pendingToolCalls[tc.Index] = pending; |
| | | 196 | | } |
| | | 197 | | |
| | 11 | 198 | | if (!string.IsNullOrEmpty(tc.Function.Arguments)) |
| | | 199 | | { |
| | 7 | 200 | | pending.Args.Append(tc.Function.Arguments); |
| | | 201 | | } |
| | | 202 | | |
| | | 203 | | // Update with id/name if this chunk carries them |
| | 11 | 204 | | if (!string.IsNullOrEmpty(tc.Id)) |
| | | 205 | | { |
| | 4 | 206 | | pendingToolCalls[tc.Index] = pending with { Id = tc.Id }; |
| | | 207 | | } |
| | 11 | 208 | | if (!string.IsNullOrEmpty(tc.Function.Name)) |
| | | 209 | | { |
| | 4 | 210 | | pendingToolCalls[tc.Index] = pending with { Name = tc.Function.Name }; |
| | | 211 | | } |
| | | 212 | | } |
| | | 213 | | } |
| | | 214 | | |
| | | 215 | | // Emit completed tool calls when finish_reason signals completion |
| | 16 | 216 | | if (choice?.FinishReason == "tool_calls" && pendingToolCalls.Count > 0) |
| | | 217 | | { |
| | 3 | 218 | | var update = new ChatResponseUpdate |
| | 3 | 219 | | { |
| | 3 | 220 | | ModelId = chunk.Model, |
| | 3 | 221 | | CreatedAt = chunk.Created > 0 ? DateTimeOffset.FromUnixTimeSeconds(chunk.Created) : null, |
| | 3 | 222 | | FinishReason = ChatFinishReason.ToolCalls, |
| | 3 | 223 | | Role = ChatRole.Assistant, |
| | 3 | 224 | | }; |
| | | 225 | | |
| | | 226 | | foreach (var (_, tc) in pendingToolCalls.OrderBy(kvp => kvp.Key)) |
| | | 227 | | { |
| | 4 | 228 | | IDictionary<string, object?>? args = null; |
| | 4 | 229 | | var argsJson = tc.Args.ToString(); |
| | 4 | 230 | | if (!string.IsNullOrEmpty(argsJson)) |
| | | 231 | | { |
| | | 232 | | try |
| | | 233 | | { |
| | 4 | 234 | | args = JsonSerializer.Deserialize<Dictionary<string, object?>>( |
| | 4 | 235 | | argsJson, CopilotJsonContext.Default.Options); |
| | 4 | 236 | | } |
| | 0 | 237 | | catch (JsonException) |
| | | 238 | | { |
| | 0 | 239 | | args = new Dictionary<string, object?> { ["_raw"] = argsJson }; |
| | 0 | 240 | | } |
| | | 241 | | } |
| | | 242 | | |
| | 4 | 243 | | update.Contents.Add(new FunctionCallContent(tc.Id, tc.Name, args)); |
| | | 244 | | } |
| | | 245 | | |
| | 3 | 246 | | pendingToolCalls.Clear(); |
| | 3 | 247 | | yield return update; |
| | | 248 | | continue; |
| | | 249 | | } |
| | | 250 | | |
| | | 251 | | // Emit non-tool-call updates normally (text content, usage, etc.) |
| | 13 | 252 | | var normalUpdate = MapToStreamingUpdate(chunk, skipToolCalls: true); |
| | 13 | 253 | | if (normalUpdate is not null) |
| | | 254 | | { |
| | 13 | 255 | | yield return normalUpdate; |
| | | 256 | | } |
| | | 257 | | } |
| | 5 | 258 | | } |
| | | 259 | | |
| | | 260 | | /// <inheritdoc /> |
| | | 261 | | public object? GetService(Type serviceType, object? key = null) |
| | | 262 | | { |
| | 0 | 263 | | if (serviceType == typeof(IChatClient)) |
| | | 264 | | { |
| | 0 | 265 | | return this; |
| | | 266 | | } |
| | | 267 | | |
| | 0 | 268 | | return null; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | /// <inheritdoc /> |
| | | 272 | | public void Dispose() |
| | | 273 | | { |
| | 12 | 274 | | if (_ownsHttpClient) |
| | | 275 | | { |
| | 1 | 276 | | _httpClient.Dispose(); |
| | | 277 | | } |
| | | 278 | | |
| | 12 | 279 | | if (_tokenProvider is IDisposable disposable) |
| | | 280 | | { |
| | 12 | 281 | | disposable.Dispose(); |
| | | 282 | | } |
| | 12 | 283 | | } |
| | | 284 | | |
| | | 285 | | private ChatCompletionRequest BuildRequest( |
| | | 286 | | IList<ChatMessage> messages, |
| | | 287 | | ChatOptions? options, |
| | | 288 | | bool stream) |
| | | 289 | | { |
| | 11 | 290 | | var model = options?.ModelId ?? _options.DefaultModel; |
| | | 291 | | |
| | 11 | 292 | | var request = new ChatCompletionRequest |
| | 11 | 293 | | { |
| | 11 | 294 | | Model = model, |
| | 11 | 295 | | Messages = MapMessages(messages), |
| | 11 | 296 | | Stream = stream, |
| | 11 | 297 | | Temperature = options?.Temperature, |
| | 11 | 298 | | TopP = options?.TopP, |
| | 11 | 299 | | MaxTokens = options?.MaxOutputTokens, |
| | 11 | 300 | | FrequencyPenalty = options?.FrequencyPenalty, |
| | 11 | 301 | | PresencePenalty = options?.PresencePenalty, |
| | 11 | 302 | | }; |
| | | 303 | | |
| | 11 | 304 | | if (options?.StopSequences is { Count: > 0 } stops) |
| | | 305 | | { |
| | 0 | 306 | | request.Stop = [.. stops]; |
| | | 307 | | } |
| | | 308 | | |
| | 11 | 309 | | if (options?.Tools is { Count: > 0 } tools) |
| | | 310 | | { |
| | 0 | 311 | | request.Tools = MapTools(tools); |
| | | 312 | | } |
| | | 313 | | |
| | 11 | 314 | | return request; |
| | | 315 | | } |
| | | 316 | | |
| | | 317 | | private static List<RequestMessage> MapMessages(IList<ChatMessage> messages) |
| | | 318 | | { |
| | 11 | 319 | | var result = new List<RequestMessage>(messages.Count); |
| | | 320 | | |
| | 52 | 321 | | foreach (var msg in messages) |
| | | 322 | | { |
| | 15 | 323 | | var role = msg.Role.Value switch |
| | 15 | 324 | | { |
| | 0 | 325 | | "system" => "system", |
| | 11 | 326 | | "user" => "user", |
| | 2 | 327 | | "assistant" => "assistant", |
| | 2 | 328 | | "tool" => "tool", |
| | 0 | 329 | | _ => msg.Role.Value, |
| | 15 | 330 | | }; |
| | | 331 | | |
| | | 332 | | // Handle tool result messages — one RequestMessage per FunctionResultContent. |
| | | 333 | | // MAF may pack multiple tool results into a single ChatMessage when the model |
| | | 334 | | // made parallel tool calls. The Copilot API (OpenAI format) requires a separate |
| | | 335 | | // "tool" message for each tool_call_id. |
| | 15 | 336 | | var functionResults = msg.Contents.OfType<FunctionResultContent>() |
| | 4 | 337 | | .Where(fr => !string.IsNullOrEmpty(fr.CallId)) |
| | 15 | 338 | | .ToList(); |
| | 15 | 339 | | if (functionResults.Count > 0) |
| | | 340 | | { |
| | 12 | 341 | | foreach (var fr in functionResults) |
| | | 342 | | { |
| | 4 | 343 | | result.Add(new RequestMessage |
| | 4 | 344 | | { |
| | 4 | 345 | | Role = role, |
| | 4 | 346 | | Content = SerializeToolResult(fr.Result), |
| | 4 | 347 | | ToolCallId = fr.CallId ?? "", |
| | 4 | 348 | | }); |
| | | 349 | | } |
| | | 350 | | |
| | | 351 | | continue; |
| | | 352 | | } |
| | | 353 | | |
| | | 354 | | // Handle assistant messages with tool calls |
| | 13 | 355 | | var functionCalls = msg.Contents.OfType<FunctionCallContent>() |
| | 6 | 356 | | .Where(fc => !string.IsNullOrEmpty(fc.Name)) |
| | 13 | 357 | | .ToList(); |
| | 13 | 358 | | if (functionCalls.Count > 0) |
| | | 359 | | { |
| | 2 | 360 | | var textContent = string.Join("", msg.Contents |
| | 2 | 361 | | .OfType<TextContent>() |
| | 2 | 362 | | .Select(t => t.Text)); |
| | | 363 | | |
| | 2 | 364 | | result.Add(new RequestMessage |
| | 2 | 365 | | { |
| | 2 | 366 | | Role = role, |
| | 2 | 367 | | Content = string.IsNullOrEmpty(textContent) ? null : textContent, |
| | 4 | 368 | | ToolCalls = functionCalls.Select(fc => new RequestToolCall |
| | 4 | 369 | | { |
| | 4 | 370 | | Id = fc.CallId ?? "", |
| | 4 | 371 | | Type = "function", |
| | 4 | 372 | | Function = new RequestToolCallFunction |
| | 4 | 373 | | { |
| | 4 | 374 | | Name = fc.Name, |
| | 4 | 375 | | Arguments = fc.Arguments is not null |
| | 4 | 376 | | ? JsonSerializer.Serialize(fc.Arguments, CopilotJsonContext.Default.Options) |
| | 4 | 377 | | : "{}", |
| | 4 | 378 | | }, |
| | 4 | 379 | | }).ToList(), |
| | 2 | 380 | | }); |
| | 2 | 381 | | continue; |
| | | 382 | | } |
| | | 383 | | |
| | | 384 | | // Regular text message |
| | 11 | 385 | | var text = string.Join("", msg.Contents |
| | 11 | 386 | | .OfType<TextContent>() |
| | 22 | 387 | | .Select(t => t.Text)); |
| | | 388 | | |
| | 11 | 389 | | result.Add(new RequestMessage |
| | 11 | 390 | | { |
| | 11 | 391 | | Role = role, |
| | 11 | 392 | | Content = text, |
| | 11 | 393 | | }); |
| | | 394 | | } |
| | | 395 | | |
| | 11 | 396 | | return result; |
| | | 397 | | } |
| | | 398 | | |
| | | 399 | | private static List<RequestTool> MapTools(IList<AITool> tools) |
| | | 400 | | { |
| | 0 | 401 | | var result = new List<RequestTool>(tools.Count); |
| | | 402 | | |
| | 0 | 403 | | foreach (var tool in tools) |
| | | 404 | | { |
| | 0 | 405 | | if (tool is not AIFunction func) |
| | | 406 | | { |
| | | 407 | | continue; |
| | | 408 | | } |
| | | 409 | | |
| | 0 | 410 | | var parameters = func.JsonSchema is { } schema |
| | 0 | 411 | | ? JsonSerializer.Deserialize<object>(schema.GetRawText()) |
| | 0 | 412 | | : null; |
| | | 413 | | |
| | 0 | 414 | | result.Add(new RequestTool |
| | 0 | 415 | | { |
| | 0 | 416 | | Type = "function", |
| | 0 | 417 | | Function = new RequestToolFunction |
| | 0 | 418 | | { |
| | 0 | 419 | | Name = func.Name, |
| | 0 | 420 | | Description = func.Description, |
| | 0 | 421 | | Parameters = parameters, |
| | 0 | 422 | | }, |
| | 0 | 423 | | }); |
| | | 424 | | } |
| | | 425 | | |
| | 0 | 426 | | return result; |
| | | 427 | | } |
| | | 428 | | |
| | | 429 | | private async Task<HttpResponseMessage> SendRequestAsync( |
| | | 430 | | ChatCompletionRequest request, |
| | | 431 | | CancellationToken cancellationToken) |
| | | 432 | | { |
| | 11 | 433 | | var token = await _tokenProvider.GetTokenAsync(cancellationToken).ConfigureAwait(false); |
| | 11 | 434 | | var url = $"{_options.CopilotApiBaseUrl.TrimEnd('/')}/chat/completions"; |
| | | 435 | | |
| | 11 | 436 | | for (int attempt = 0; ; attempt++) |
| | | 437 | | { |
| | 11 | 438 | | var jsonBody = JsonSerializer.Serialize( |
| | 11 | 439 | | request, CopilotJsonContext.Default.ChatCompletionRequest); |
| | | 440 | | |
| | 11 | 441 | | using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) |
| | 11 | 442 | | { |
| | 11 | 443 | | Content = new StringContent(jsonBody, Encoding.UTF8, "application/json"), |
| | 11 | 444 | | }; |
| | | 445 | | |
| | 11 | 446 | | httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); |
| | 11 | 447 | | httpRequest.Headers.Add("Accept", request.Stream ? "text/event-stream" : "application/json"); |
| | 11 | 448 | | httpRequest.Headers.Add("Copilot-Integration-Id", _options.IntegrationId); |
| | 11 | 449 | | httpRequest.Headers.Add("Editor-Version", _options.EditorVersion); |
| | 11 | 450 | | httpRequest.Headers.Add("Editor-Plugin-Version", "needlr-copilot/1.0.0"); |
| | 11 | 451 | | httpRequest.Headers.Add("X-GitHub-Api-Version", "2025-05-01"); |
| | 11 | 452 | | httpRequest.Headers.Add("Openai-Intent", "conversation-agent"); |
| | 11 | 453 | | httpRequest.Headers.Add("X-Interaction-Type", "conversation-agent"); |
| | 11 | 454 | | httpRequest.Headers.Add("X-Initiator", "user"); |
| | 11 | 455 | | httpRequest.Headers.UserAgent.ParseAdd(_options.IntegrationId); |
| | | 456 | | |
| | 11 | 457 | | var httpResponse = await _httpClient.SendAsync( |
| | 11 | 458 | | httpRequest, |
| | 11 | 459 | | request.Stream ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead, |
| | 11 | 460 | | cancellationToken).ConfigureAwait(false); |
| | | 461 | | |
| | 11 | 462 | | if (httpResponse.IsSuccessStatusCode) |
| | | 463 | | { |
| | 11 | 464 | | return httpResponse; |
| | | 465 | | } |
| | | 466 | | |
| | 0 | 467 | | if (httpResponse.StatusCode == System.Net.HttpStatusCode.TooManyRequests |
| | 0 | 468 | | && attempt < _options.MaxRetries) |
| | | 469 | | { |
| | 0 | 470 | | var delay = GetRetryDelay(httpResponse, attempt); |
| | 0 | 471 | | httpResponse.Dispose(); |
| | 0 | 472 | | await Task.Delay(delay, cancellationToken).ConfigureAwait(false); |
| | 0 | 473 | | continue; |
| | | 474 | | } |
| | | 475 | | |
| | 0 | 476 | | var errorBody = await httpResponse.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 477 | | httpResponse.Dispose(); |
| | 0 | 478 | | throw new HttpRequestException( |
| | 0 | 479 | | $"Copilot API request failed ({httpResponse.StatusCode}): {errorBody}"); |
| | | 480 | | } |
| | 11 | 481 | | } |
| | | 482 | | |
| | | 483 | | private TimeSpan GetRetryDelay(HttpResponseMessage response, int attempt) |
| | | 484 | | { |
| | 0 | 485 | | if (response.Headers.RetryAfter?.Delta is { } delta) |
| | | 486 | | { |
| | 0 | 487 | | return delta; |
| | | 488 | | } |
| | | 489 | | |
| | 0 | 490 | | if (response.Headers.RetryAfter?.Date is { } date) |
| | | 491 | | { |
| | 0 | 492 | | var wait = date - DateTimeOffset.UtcNow; |
| | 0 | 493 | | if (wait > TimeSpan.Zero) |
| | | 494 | | { |
| | 0 | 495 | | return wait; |
| | | 496 | | } |
| | | 497 | | } |
| | | 498 | | |
| | 0 | 499 | | var ms = _options.RetryBaseDelayMs * (1 << attempt); |
| | 0 | 500 | | return TimeSpan.FromMilliseconds(ms); |
| | | 501 | | } |
| | | 502 | | |
| | | 503 | | private ChatResponse MapToChatResponse(ChatCompletionResponse response, ChatOptions? options) |
| | | 504 | | { |
| | 6 | 505 | | var messages = new List<ChatMessage>(); |
| | | 506 | | |
| | 24 | 507 | | foreach (var choice in response.Choices) |
| | | 508 | | { |
| | 6 | 509 | | var msg = choice.Message; |
| | 6 | 510 | | if (msg is null) continue; |
| | | 511 | | |
| | 6 | 512 | | var chatMsg = new ChatMessage( |
| | 6 | 513 | | new ChatRole(msg.Role ?? "assistant"), |
| | 6 | 514 | | []); |
| | | 515 | | |
| | 6 | 516 | | if (!string.IsNullOrEmpty(msg.Content)) |
| | | 517 | | { |
| | 5 | 518 | | chatMsg.Contents.Add(new TextContent(msg.Content)); |
| | | 519 | | } |
| | | 520 | | |
| | 6 | 521 | | if (msg.ToolCalls is { Count: > 0 }) |
| | | 522 | | { |
| | 4 | 523 | | foreach (var tc in msg.ToolCalls) |
| | | 524 | | { |
| | 1 | 525 | | if (tc.Function is null) continue; |
| | | 526 | | |
| | 1 | 527 | | IDictionary<string, object?>? args = null; |
| | 1 | 528 | | if (!string.IsNullOrEmpty(tc.Function.Arguments)) |
| | | 529 | | { |
| | | 530 | | try |
| | | 531 | | { |
| | 1 | 532 | | args = JsonSerializer.Deserialize<Dictionary<string, object?>>( |
| | 1 | 533 | | tc.Function.Arguments, |
| | 1 | 534 | | CopilotJsonContext.Default.Options); |
| | 1 | 535 | | } |
| | 0 | 536 | | catch (JsonException) |
| | | 537 | | { |
| | 0 | 538 | | args = new Dictionary<string, object?> { ["_raw"] = tc.Function.Arguments }; |
| | 0 | 539 | | } |
| | | 540 | | } |
| | | 541 | | |
| | 1 | 542 | | chatMsg.Contents.Add(new FunctionCallContent( |
| | 1 | 543 | | tc.Id ?? "", |
| | 1 | 544 | | tc.Function.Name ?? "", |
| | 1 | 545 | | args)); |
| | | 546 | | } |
| | | 547 | | } |
| | | 548 | | |
| | 6 | 549 | | messages.Add(chatMsg); |
| | | 550 | | } |
| | | 551 | | |
| | 6 | 552 | | var chatResponse = new ChatResponse(messages) |
| | 6 | 553 | | { |
| | 6 | 554 | | ModelId = response.Model ?? options?.ModelId ?? _options.DefaultModel, |
| | 6 | 555 | | FinishReason = MapFinishReason(response.Choices.FirstOrDefault()?.FinishReason), |
| | 6 | 556 | | CreatedAt = DateTimeOffset.FromUnixTimeSeconds(response.Created), |
| | 6 | 557 | | }; |
| | | 558 | | |
| | 6 | 559 | | if (response.Id is not null) |
| | | 560 | | { |
| | 6 | 561 | | chatResponse.AdditionalProperties ??= new AdditionalPropertiesDictionary(); |
| | 6 | 562 | | chatResponse.AdditionalProperties["completion_id"] = response.Id; |
| | | 563 | | } |
| | | 564 | | |
| | 6 | 565 | | if (response.Usage is { } usage) |
| | | 566 | | { |
| | 2 | 567 | | chatResponse.Usage = new UsageDetails |
| | 2 | 568 | | { |
| | 2 | 569 | | InputTokenCount = usage.PromptTokens, |
| | 2 | 570 | | OutputTokenCount = usage.CompletionTokens, |
| | 2 | 571 | | TotalTokenCount = usage.TotalTokens, |
| | 2 | 572 | | }; |
| | | 573 | | } |
| | | 574 | | |
| | 6 | 575 | | return chatResponse; |
| | | 576 | | } |
| | | 577 | | |
| | | 578 | | private static ChatResponseUpdate? MapToStreamingUpdate(ChatCompletionChunk chunk, bool skipToolCalls = false) |
| | | 579 | | { |
| | 13 | 580 | | var choice = chunk.Choices.FirstOrDefault(); |
| | 13 | 581 | | var delta = choice?.Delta; |
| | | 582 | | |
| | 13 | 583 | | if (delta is null && chunk.Usage is null) |
| | | 584 | | { |
| | 0 | 585 | | return null; |
| | | 586 | | } |
| | | 587 | | |
| | 13 | 588 | | var update = new ChatResponseUpdate |
| | 13 | 589 | | { |
| | 13 | 590 | | ModelId = chunk.Model, |
| | 13 | 591 | | CreatedAt = chunk.Created > 0 ? DateTimeOffset.FromUnixTimeSeconds(chunk.Created) : null, |
| | 13 | 592 | | FinishReason = MapFinishReason(choice?.FinishReason), |
| | 13 | 593 | | Role = delta?.Role is not null ? new ChatRole(delta.Role) : null, |
| | 13 | 594 | | }; |
| | | 595 | | |
| | 13 | 596 | | if (chunk.Id is not null) |
| | | 597 | | { |
| | 13 | 598 | | update.AdditionalProperties ??= new AdditionalPropertiesDictionary(); |
| | 13 | 599 | | update.AdditionalProperties["completion_id"] = chunk.Id; |
| | | 600 | | } |
| | | 601 | | |
| | 13 | 602 | | if (!string.IsNullOrEmpty(delta?.Content)) |
| | | 603 | | { |
| | 3 | 604 | | update.Contents.Add(new TextContent(delta!.Content)); |
| | | 605 | | } |
| | | 606 | | |
| | 13 | 607 | | if (!skipToolCalls && delta?.ToolCalls is { Count: > 0 }) |
| | | 608 | | { |
| | 0 | 609 | | foreach (var tc in delta.ToolCalls) |
| | | 610 | | { |
| | 0 | 611 | | if (tc.Function is null) continue; |
| | | 612 | | |
| | 0 | 613 | | IDictionary<string, object?>? args = null; |
| | 0 | 614 | | if (!string.IsNullOrEmpty(tc.Function.Arguments)) |
| | | 615 | | { |
| | | 616 | | try |
| | | 617 | | { |
| | 0 | 618 | | args = JsonSerializer.Deserialize<Dictionary<string, object?>>( |
| | 0 | 619 | | tc.Function.Arguments, |
| | 0 | 620 | | CopilotJsonContext.Default.Options); |
| | 0 | 621 | | } |
| | 0 | 622 | | catch (JsonException) |
| | | 623 | | { |
| | 0 | 624 | | args = new Dictionary<string, object?> { ["_raw"] = tc.Function.Arguments }; |
| | 0 | 625 | | } |
| | | 626 | | } |
| | | 627 | | |
| | 0 | 628 | | update.Contents.Add(new FunctionCallContent( |
| | 0 | 629 | | tc.Id ?? "", |
| | 0 | 630 | | tc.Function.Name ?? "", |
| | 0 | 631 | | args)); |
| | | 632 | | } |
| | | 633 | | } |
| | | 634 | | |
| | 13 | 635 | | if (chunk.Usage is { } usage) |
| | | 636 | | { |
| | 0 | 637 | | update.Contents.Add(new UsageContent(new UsageDetails |
| | 0 | 638 | | { |
| | 0 | 639 | | InputTokenCount = usage.PromptTokens, |
| | 0 | 640 | | OutputTokenCount = usage.CompletionTokens, |
| | 0 | 641 | | TotalTokenCount = usage.TotalTokens, |
| | 0 | 642 | | })); |
| | | 643 | | } |
| | | 644 | | |
| | 13 | 645 | | return update; |
| | | 646 | | } |
| | | 647 | | |
| | 19 | 648 | | private static ChatFinishReason? MapFinishReason(string? reason) => reason switch |
| | 19 | 649 | | { |
| | 7 | 650 | | "stop" => ChatFinishReason.Stop, |
| | 0 | 651 | | "length" => ChatFinishReason.Length, |
| | 1 | 652 | | "tool_calls" => ChatFinishReason.ToolCalls, |
| | 0 | 653 | | "content_filter" => ChatFinishReason.ContentFilter, |
| | 11 | 654 | | null => null, |
| | 0 | 655 | | _ => new ChatFinishReason(reason), |
| | 19 | 656 | | }; |
| | | 657 | | |
| | | 658 | | /// <summary> |
| | | 659 | | /// Serializes a tool result for inclusion in a chat message to the API. |
| | | 660 | | /// <see cref="JsonElement"/> values are rendered to raw JSON text. Strings |
| | | 661 | | /// are returned as-is. All other types are JSON-serialized. |
| | | 662 | | /// </summary> |
| | | 663 | | private static string SerializeToolResult(object? result) |
| | | 664 | | { |
| | 4 | 665 | | if (result is null) |
| | | 666 | | { |
| | 0 | 667 | | return ""; |
| | | 668 | | } |
| | | 669 | | |
| | 4 | 670 | | if (result is JsonElement jsonElement) |
| | | 671 | | { |
| | 0 | 672 | | return jsonElement.GetRawText(); |
| | | 673 | | } |
| | | 674 | | |
| | 4 | 675 | | if (result is string s) |
| | | 676 | | { |
| | 4 | 677 | | return s; |
| | | 678 | | } |
| | | 679 | | |
| | | 680 | | try |
| | | 681 | | { |
| | 0 | 682 | | return JsonSerializer.Serialize(result, result.GetType()); |
| | | 683 | | } |
| | 0 | 684 | | catch (JsonException) |
| | | 685 | | { |
| | 0 | 686 | | return result.ToString() ?? ""; |
| | | 687 | | } |
| | 0 | 688 | | } |
| | | 689 | | } |