Repository navigation
Expand file tree
/
Copy pathToolsE2ETests.cs
More file actions
653 lines (559 loc) · 26.1 KB
/
Copy pathToolsE2ETests.cs
File metadata and controls
653 lines (559 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using GitHub.Copilot.Rpc;
using GitHub.Copilot.Test.Harness;
using Microsoft.Extensions.AI;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Xunit;
using Xunit.Abstractions;
namespace GitHub.Copilot.Test.E2E;
public partial class ToolsE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "tools", output)
{
private const string ApplyPatchInput = "*** Begin Patch\n*** End Patch";
private const string ApplyPatchResult = "patched by the host";
[Fact]
public async Task Invokes_Built_In_Tools()
{
await File.WriteAllTextAsync(
Path.Combine(Ctx.WorkDir, "README.md"),
"# ELIZA, the only chatbot you'll ever need");
var session = await CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
});
await session.SendAsync(new MessageOptions
{
Prompt = "What's the first line of README.md in this directory?"
});
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
Assert.Contains("ELIZA", assistantMessage!.Data.Content ?? string.Empty);
}
[Fact]
public async Task Invokes_Custom_Tool()
{
var session = await CreateSessionAsync(new SessionConfig
{
Tools = [AIFunctionFactory.Create(EncryptString, "encrypt_string")],
OnPermissionRequest = PermissionHandler.ApproveAll,
});
await session.SendAsync(new MessageOptions
{
Prompt = "Use encrypt_string to encrypt this string: Hello"
});
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
Assert.Contains("HELLO", assistantMessage!.Data.Content ?? string.Empty);
[Description("Encrypts a string")]
static string EncryptString([Description("String to encrypt")] string input)
=> input.ToUpperInvariant();
}
[Fact]
public async Task Low_Level_Tool_Definition()
{
string currentPhase = string.Empty;
var session = await CreateSessionAsync(new SessionConfig
{
Tools =
[
AIFunctionFactory.Create(SetCurrentPhase, new AIFunctionFactoryOptions
{
Name = "set_current_phase",
Description = "Sets the current phase of the agent",
}),
AIFunctionFactory.Create(SearchItems, new AIFunctionFactoryOptions
{
Name = "search_items",
Description = "Search for items by keyword",
}),
],
AvailableTools = new ToolSet().AddCustom("*").AddBuiltIn("web_fetch"),
OnPermissionRequest = PermissionHandler.ApproveAll,
});
await session.SendAsync(new MessageOptions
{
Prompt = "First, set the current phase to 'analyzing'. Then search for items with keyword 'copilot'. Report the phase and search results."
});
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
var content = assistantMessage!.Data.Content ?? string.Empty;
Assert.NotEmpty(content);
Assert.Contains("analyzing", content, StringComparison.OrdinalIgnoreCase);
Assert.True(content.Contains("item_alpha", StringComparison.OrdinalIgnoreCase)
|| content.Contains("item_beta", StringComparison.OrdinalIgnoreCase),
$"Expected content to mention item_alpha or item_beta, got: {content}");
Assert.Equal("analyzing", currentPhase);
Task<string> SetCurrentPhase(string phase)
{
currentPhase = phase;
return Task.FromResult($"Phase set to {phase}");
}
Task<string> SearchItems(AIFunctionArguments args)
{
Assert.Equal("copilot", args["keyword"]?.ToString());
return Task.FromResult("Found: item_alpha, item_beta");
}
}
[Fact]
public async Task Handles_Tool_Calling_Errors()
{
var getUserLocation = AIFunctionFactory.Create(
() => { throw new Exception("Melbourne"); }, "get_user_location", "Gets the user's location");
var session = await CreateSessionAsync(new SessionConfig
{
Tools = [getUserLocation],
OnPermissionRequest = PermissionHandler.ApproveAll,
});
await session.SendAsync(new MessageOptions { Prompt = "What is my location? If you can't find out, just say 'unknown'." });
var answer = await TestHelper.GetFinalAssistantMessageAsync(session);
// Check the underlying traffic
var traffic = await Ctx.GetExchangesAsync();
var lastConversation = traffic[^1];
var toolCalls = lastConversation.Request.Messages
.Where(m => m.Role == "assistant" && m.ToolCalls != null)
.SelectMany(m => m.ToolCalls!)
.ToList();
Assert.Single(toolCalls);
var toolCall = toolCalls[0];
Assert.Equal("function", toolCall.Type);
Assert.Equal("get_user_location", toolCall.Function.Name);
var toolResults = lastConversation.Request.Messages
.Where(m => m.Role == "tool")
.ToList();
Assert.Single(toolResults);
var toolResult = toolResults[0];
Assert.Equal(toolCall.Id, toolResult.ToolCallId);
Assert.DoesNotContain("Melbourne", toolResult.StringContent);
// Importantly, we're checking that the assistant does not see the
// exception information as if it was the tool's output.
Assert.DoesNotContain("Melbourne", answer?.Data.Content);
Assert.Contains("unknown", answer?.Data.Content?.ToLowerInvariant());
}
[Fact]
public async Task Can_Receive_And_Return_Complex_Types()
{
ToolInvocation? receivedInvocation = null;
var session = await CreateSessionAsync(new SessionConfig
{
Tools = [AIFunctionFactory.Create(PerformDbQuery, "db_query", serializerOptions: ToolsTestsJsonContext.Default.Options)],
OnPermissionRequest = PermissionHandler.ApproveAll,
});
await session.SendAsync(new MessageOptions
{
Prompt =
"Perform a DB query for the 'cities' table using IDs 12 and 19, sorting ascending. " +
"Reply only with lines of the form: [cityname] [population]"
});
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
var responseContent = assistantMessage?.Data.Content!;
Assert.NotNull(assistantMessage);
Assert.NotEmpty(responseContent);
Assert.Contains("Passos", responseContent);
Assert.Contains("San Lorenzo", responseContent);
Assert.Contains("135460", responseContent.Replace(",", ""));
Assert.Contains("204356", responseContent.Replace(",", ""));
// We can access the raw invocation if needed
Assert.Equal(session.SessionId, receivedInvocation!.SessionId);
City[] PerformDbQuery(DbQueryOptions query, AIFunctionArguments rawArgs)
{
Assert.Equal("cities", query.Table);
Assert.Equal([12, 19], query.Ids);
Assert.True(query.SortAscending);
receivedInvocation = (ToolInvocation)rawArgs.Context![typeof(ToolInvocation)]!;
return [new(19, "Passos", 135460), new(12, "San Lorenzo", 204356)];
}
}
record DbQueryOptions(string Table, int[] Ids, bool SortAscending);
record City(int CountryId, string CityName, int Population);
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(DbQueryOptions))]
[JsonSerializable(typeof(City[]))]
[JsonSerializable(typeof(JsonElement))]
private partial class ToolsTestsJsonContext : JsonSerializerContext;
[Fact]
public async Task Overrides_Built_In_Tool_With_Custom_Tool()
{
var session = await CreateSessionAsync(new SessionConfig
{
Tools = [AIFunctionFactory.Create((Delegate)CustomGrep, new AIFunctionFactoryOptions
{
Name = "grep",
AdditionalProperties = new ReadOnlyDictionary<string, object?>(
new Dictionary<string, object?> { ["is_override"] = true })
})],
OnPermissionRequest = PermissionHandler.ApproveAll,
});
await session.SendAsync(new MessageOptions
{
Prompt = "Use grep to search for the word 'hello'"
});
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
Assert.Contains("CUSTOM_GREP_RESULT", assistantMessage!.Data.Content ?? string.Empty);
[Description("A custom grep implementation that overrides the built-in")]
static string CustomGrep([Description("Search query")] string query)
=> $"CUSTOM_GREP_RESULT: {query}";
}
[Theory]
[InlineData("string")]
[InlineData("object")]
[InlineData("JsonElement")]
[InlineData("JsonNode")]
[Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)]
public async Task ApplyPatch_Override_Receives_Freeform_Input_Shapes(string parameterType)
{
foreach (var useCustomToolCall in new[] { true, false })
{
object? receivedInput = null;
var invocationCount = 0;
var handler = new ApplyPatchOverrideRequestHandler(useCustomToolCall);
await using var client = Ctx.CreateClient(options: new CopilotClientOptions
{
Connection = RuntimeConnection.ForStdio(),
RequestHandler = handler,
});
await client.StartAsync();
string CaptureInput(object input)
{
receivedInput = input;
invocationCount++;
return ApplyPatchResult;
}
Delegate applyPatch = parameterType switch
{
"string" => (string input) => CaptureInput(input),
"object" => (object input) => CaptureInput(input),
"JsonElement" => (JsonElement input) => CaptureInput(input),
"JsonNode" => (JsonNode input) => CaptureInput(input),
_ => throw new ArgumentOutOfRangeException(nameof(parameterType)),
};
var tool = CopilotTool.DefineTool(
applyPatch,
new CopilotToolOptions
{
OverridesBuiltInTool = true,
SkipPermission = true,
},
new AIFunctionFactoryOptions
{
Name = "apply_patch",
Description = "Host-implemented apply_patch",
});
await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig
{
Model = "gpt-4o-mini",
Provider = new ProviderConfig
{
Type = "openai",
WireApi = "completions",
BaseUrl = "https://apply-patch.invalid/v1",
ApiKey = "test-key",
ModelId = "gpt-4o-mini",
WireModel = "gpt-4o-mini",
},
Streaming = true,
Tools = [tool],
OnPermissionRequest = PermissionHandler.ApproveAll,
});
var message = await session.SendAndWaitAsync(new MessageOptions { Prompt = "Use apply_patch" });
var input = receivedInput switch
{
string value => value,
JsonElement value => value.GetString(),
JsonNode value => value.GetValue<string>(),
_ => null,
};
Assert.Equal(ApplyPatchInput, input);
Assert.Equal(1, invocationCount);
Assert.Equal("override complete", message?.Data.Content);
var requests = handler.InferenceRequests;
Assert.Equal(2, requests.Count);
AssertApplyPatchOverrideAdvertised(requests[0], parameterType);
AssertApplyPatchResultReachedModel(requests[1]);
}
}
[Fact]
public async Task SkipPermission_Sent_In_Tool_Definition()
{
[Description("A tool that skips permission")]
static string SafeLookup([Description("Lookup ID")] string id)
=> $"RESULT: {id}";
var tool = AIFunctionFactory.Create((Delegate)SafeLookup, new AIFunctionFactoryOptions
{
Name = "safe_lookup",
AdditionalProperties = new ReadOnlyDictionary<string, object?>(
new Dictionary<string, object?> { ["skip_permission"] = true })
});
var didRunPermissionRequest = false;
var session = await CreateSessionAsync(new SessionConfig
{
Tools = [tool],
OnPermissionRequest = (_, _) =>
{
didRunPermissionRequest = true;
return Task.FromResult<PermissionDecision>(PermissionDecision.NoResult());
}
});
await session.SendAsync(new MessageOptions
{
Prompt = "Use safe_lookup to look up 'test123'"
});
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
Assert.Contains("RESULT", assistantMessage!.Data.Content ?? string.Empty);
Assert.False(didRunPermissionRequest);
}
[Fact(Skip = "Behaves as if no content was in the result. Likely that binary results aren't fully implemented yet.")]
public async Task Can_Return_Binary_Result()
{
var session = await CreateSessionAsync(new SessionConfig
{
Tools = [AIFunctionFactory.Create(GetImage, "get_image")],
OnPermissionRequest = PermissionHandler.ApproveAll,
});
await session.SendAsync(new MessageOptions
{
Prompt = "Use get_image. What color is the square in the image?"
});
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
Assert.Contains("yellow", assistantMessage!.Data.Content?.ToLowerInvariant() ?? string.Empty);
static ToolResultAIContent GetImage() => new(new()
{
BinaryResultsForLlm = [new() {
// 2x2 yellow square
Data = "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAADklEQVR4nGP4/5/h/38GABkAA/0k+7UAAAAASUVORK5CYII=",
Type = ToolBinaryResultType.Image,
MimeType = "image/png",
}],
SessionLog = "Returned an image",
});
}
[Fact]
public async Task Invokes_Custom_Tool_With_Permission_Handler()
{
var permissionRequests = new List<PermissionRequest>();
var session = await Ctx.CreateSessionAsync(Client, new SessionConfig
{
Tools = [AIFunctionFactory.Create(EncryptStringForPermission, "encrypt_string")],
OnPermissionRequest = (request, invocation) =>
{
permissionRequests.Add(request);
return Task.FromResult<PermissionDecision>(PermissionDecision.ApproveOnce());
},
});
await session.SendAsync(new MessageOptions
{
Prompt = "Use encrypt_string to encrypt this string: Hello"
});
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
Assert.Contains("HELLO", assistantMessage!.Data.Content ?? string.Empty);
// Should have received a custom-tool permission request with the correct tool name
var customToolRequest = permissionRequests.OfType<PermissionRequestCustomTool>().FirstOrDefault();
Assert.NotNull(customToolRequest);
Assert.Equal("encrypt_string", customToolRequest!.ToolName);
[Description("Encrypts a string")]
static string EncryptStringForPermission([Description("String to encrypt")] string input)
=> input.ToUpperInvariant();
}
[Fact]
public async Task Denies_Custom_Tool_When_Permission_Denied()
{
var toolHandlerCalled = false;
var session = await Ctx.CreateSessionAsync(Client, new SessionConfig
{
Tools = [AIFunctionFactory.Create(EncryptStringDenied, "encrypt_string")],
OnPermissionRequest = async (request, invocation) => PermissionDecision.Reject(),
});
await session.SendAsync(new MessageOptions
{
Prompt = "Use encrypt_string to encrypt this string: Hello"
});
await TestHelper.GetFinalAssistantMessageAsync(session);
// The tool handler should NOT have been called since permission was denied
Assert.False(toolHandlerCalled);
[Description("Encrypts a string")]
string EncryptStringDenied([Description("String to encrypt")] string input)
{
toolHandlerCalled = true;
return input.ToUpperInvariant();
}
}
[Fact]
public async Task Should_Execute_Multiple_Custom_Tools_In_Parallel_Single_Turn()
{
var toolACalled = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var toolBCalled = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var session = await CreateSessionAsync(new SessionConfig
{
Tools =
[
AIFunctionFactory.Create(LookupCity, "lookup_city"),
AIFunctionFactory.Create(LookupCountry, "lookup_country"),
],
OnPermissionRequest = PermissionHandler.ApproveAll,
});
await session.SendAsync(new MessageOptions
{
Prompt = "Use lookup_city with 'Paris' and lookup_country with 'France' at the same time, then combine both results in your reply."
});
// Both tools should have been called
var cityResult = await toolACalled.Task.WaitAsync(TimeSpan.FromSeconds(60));
var countryResult = await toolBCalled.Task.WaitAsync(TimeSpan.FromSeconds(60));
Assert.Equal("Paris", cityResult);
Assert.Equal("France", countryResult);
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
var content = assistantMessage!.Data.Content ?? string.Empty;
Assert.Contains("CITY_PARIS", content);
Assert.Contains("COUNTRY_FRANCE", content);
[Description("Looks up city information")]
string LookupCity([Description("City name")] string city)
{
toolACalled.TrySetResult(city);
return $"CITY_{city.ToUpperInvariant()}";
}
[Description("Looks up country information")]
string LookupCountry([Description("Country name")] string country)
{
toolBCalled.TrySetResult(country);
return $"COUNTRY_{country.ToUpperInvariant()}";
}
}
[Fact]
public async Task Should_Respect_AvailableTools_And_ExcludedTools_Combined()
{
bool excludedToolCalled = false;
var session = await CreateSessionAsync(new SessionConfig
{
Tools =
[
AIFunctionFactory.Create(AllowedTool, "allowed_tool"),
AIFunctionFactory.Create(ExcludedTool, "excluded_tool"),
],
AvailableTools = ["allowed_tool", "excluded_tool"],
ExcludedTools = ["excluded_tool"],
OnPermissionRequest = PermissionHandler.ApproveAll,
});
var result = await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "Use the allowed_tool with input 'test'. Do NOT use excluded_tool.",
});
Assert.NotNull(result);
Assert.Contains("ALLOWED_TEST", result!.Data.Content ?? string.Empty);
Assert.False(excludedToolCalled, "Excluded tool should not have been called");
[Description("An allowed tool")]
string AllowedTool([Description("Input value")] string input) => $"ALLOWED_{input.ToUpperInvariant()}";
[Description("A tool that should be excluded")]
string ExcludedTool([Description("Input value")] string input)
{
excludedToolCalled = true;
return $"EXCLUDED_{input.ToUpperInvariant()}";
}
}
private static void AssertApplyPatchOverrideAdvertised(string requestBody, string parameterType)
{
using var request = JsonDocument.Parse(requestBody);
var applyPatchTools = request.RootElement.GetProperty("tools")
.EnumerateArray()
.Where(tool =>
tool.TryGetProperty("function", out var function)
&& function.TryGetProperty("name", out var functionName)
&& functionName.GetString() == "apply_patch"
|| tool.TryGetProperty("custom", out var custom)
&& custom.TryGetProperty("name", out var customName)
&& customName.GetString() == "apply_patch")
.ToArray();
var applyPatch = Assert.Single(applyPatchTools);
Assert.Equal("function", applyPatch.GetProperty("type").GetString());
var definition = applyPatch.GetProperty("function");
Assert.Equal("apply_patch", definition.GetProperty("name").GetString());
var parameters = definition.GetProperty("parameters");
Assert.Equal("object", parameters.GetProperty("type").GetString());
var inputSchema = parameters.GetProperty("properties").GetProperty("input");
if (parameterType == "string")
{
Assert.Equal("string", inputSchema.GetProperty("type").GetString());
}
else
{
Assert.Equal(JsonValueKind.True, inputSchema.ValueKind);
}
Assert.Contains(parameters.GetProperty("required").EnumerateArray(), item => item.GetString() == "input");
}
private static void AssertApplyPatchResultReachedModel(string requestBody)
{
using var request = JsonDocument.Parse(requestBody);
var toolResult = Assert.Single(
request.RootElement.GetProperty("messages").EnumerateArray(),
message =>
message.GetProperty("role").GetString() == "tool"
&& message.GetProperty("tool_call_id").GetString() == "call-1");
Assert.Equal(ApplyPatchResult, toolResult.GetProperty("content").GetString());
}
private sealed class ApplyPatchOverrideRequestHandler(bool useCustomToolCall) : CopilotRequestHandler
{
private const string CustomToolCallResponse =
"data: {\"id\":\"chatcmpl-tool\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4o-mini\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call-1\",\"type\":\"custom\",\"custom\":{\"name\":\"apply_patch\",\"input\":\"*** Begin Patch\\n*** End Patch\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n" +
"data: [DONE]\n\n";
private const string FunctionToolCallResponse =
"data: {\"id\":\"chatcmpl-tool\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4o-mini\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call-1\",\"type\":\"function\",\"function\":{\"name\":\"apply_patch\",\"arguments\":\"{\\\"input\\\":\\\"*** Begin Patch\\\\n*** End Patch\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n" +
"data: [DONE]\n\n";
private const string FinalResponse =
"data: {\"id\":\"chatcmpl-final\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4o-mini\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"override complete\"},\"finish_reason\":null}]}\n\n" +
"data: {\"id\":\"chatcmpl-final\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"gpt-4o-mini\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n" +
"data: [DONE]\n\n";
private readonly object _lock = new();
private readonly List<string> _inferenceRequests = [];
internal IReadOnlyList<string> InferenceRequests
{
get
{
lock (_lock)
{
return [.. _inferenceRequests];
}
}
}
protected override async Task<HttpResponseMessage> SendRequestAsync(HttpRequestMessage request, CopilotRequestContext ctx)
{
var url = request.RequestUri!.ToString();
if (!RecordingRequestHandler.IsInferenceUrl(url))
{
return RecordingRequestHandler.BuildNonInferenceResponse(url);
}
var requestBody = request.Content is null
? string.Empty
#if NET8_0_OR_GREATER
: await request.Content.ReadAsStringAsync(ctx.CancellationToken).ConfigureAwait(false);
#else
: await request.Content.ReadAsStringAsync().ConfigureAwait(false);
#endif
int requestNumber;
lock (_lock)
{
_inferenceRequests.Add(requestBody);
requestNumber = _inferenceRequests.Count;
}
return requestNumber switch
{
1 => Sse(useCustomToolCall ? CustomToolCallResponse : FunctionToolCallResponse),
2 => Sse(FinalResponse),
_ => throw new InvalidOperationException($"Unexpected inference request #{requestNumber}."),
};
}
private static HttpResponseMessage Sse(string body) => new(HttpStatusCode.OK)
{
Content = new StringContent(body, Encoding.UTF8, "text/event-stream"),
};
}
}