-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
ClientCore.cs
1521 lines (1314 loc) · 71.3 KB
/
ClientCore.cs
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.AI.OpenAI;
using Azure.Core;
using Azure.Core.Pipeline;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Http;
#pragma warning disable CA2208 // Instantiate argument exceptions correctly
namespace Microsoft.SemanticKernel.Connectors.OpenAI;
/// <summary>
/// Base class for AI clients that provides common functionality for interacting with OpenAI services.
/// </summary>
internal abstract class ClientCore
{
private const string ModelProvider = "openai";
private const int MaxResultsPerPrompt = 128;
/// <summary>
/// The maximum number of auto-invokes that can be in-flight at any given time as part of the current
/// asynchronous chain of execution.
/// </summary>
/// <remarks>
/// This is a fail-safe mechanism. If someone accidentally manages to set up execution settings in such a way that
/// auto-invocation is invoked recursively, and in particular where a prompt function is able to auto-invoke itself,
/// we could end up in an infinite loop. This const is a backstop against that happening. We should never come close
/// to this limit, but if we do, auto-invoke will be disabled for the current flow in order to prevent runaway execution.
/// With the current setup, the way this could possibly happen is if a prompt function is configured with built-in
/// execution settings that opt-in to auto-invocation of everything in the kernel, in which case the invocation of that
/// prompt function could advertize itself as a candidate for auto-invocation. We don't want to outright block that,
/// if that's something a developer has asked to do (e.g. it might be invoked with different arguments than its parent
/// was invoked with), but we do want to limit it. This limit is arbitrary and can be tweaked in the future and/or made
/// configurable should need arise.
/// </remarks>
private const int MaxInflightAutoInvokes = 128;
/// <summary>Singleton tool used when tool call count drops to 0 but we need to supply tools to keep the service happy.</summary>
private static readonly ChatCompletionsFunctionToolDefinition s_nonInvocableFunctionTool = new() { Name = "NonInvocableTool" };
/// <summary>Tracking <see cref="AsyncLocal{Int32}"/> for <see cref="MaxInflightAutoInvokes"/>.</summary>
private static readonly AsyncLocal<int> s_inflightAutoInvokes = new();
internal ClientCore(ILogger? logger = null)
{
this.Logger = logger ?? NullLogger.Instance;
}
/// <summary>
/// Model Id or Deployment Name
/// </summary>
internal string DeploymentOrModelName { get; set; } = string.Empty;
/// <summary>
/// OpenAI / Azure OpenAI Client
/// </summary>
internal abstract OpenAIClient Client { get; }
internal Uri? Endpoint { get; set; } = null;
/// <summary>
/// Logger instance
/// </summary>
internal ILogger Logger { get; set; }
/// <summary>
/// Storage for AI service attributes.
/// </summary>
internal Dictionary<string, object?> Attributes { get; } = [];
/// <summary>
/// Instance of <see cref="Meter"/> for metrics.
/// </summary>
private static readonly Meter s_meter = new("Microsoft.SemanticKernel.Connectors.OpenAI");
/// <summary>
/// Instance of <see cref="Counter{T}"/> to keep track of the number of prompt tokens used.
/// </summary>
private static readonly Counter<int> s_promptTokensCounter =
s_meter.CreateCounter<int>(
name: "semantic_kernel.connectors.openai.tokens.prompt",
unit: "{token}",
description: "Number of prompt tokens used");
/// <summary>
/// Instance of <see cref="Counter{T}"/> to keep track of the number of completion tokens used.
/// </summary>
private static readonly Counter<int> s_completionTokensCounter =
s_meter.CreateCounter<int>(
name: "semantic_kernel.connectors.openai.tokens.completion",
unit: "{token}",
description: "Number of completion tokens used");
/// <summary>
/// Instance of <see cref="Counter{T}"/> to keep track of the total number of tokens used.
/// </summary>
private static readonly Counter<int> s_totalTokensCounter =
s_meter.CreateCounter<int>(
name: "semantic_kernel.connectors.openai.tokens.total",
unit: "{token}",
description: "Number of tokens used");
/// <summary>
/// Creates completions for the prompt and settings.
/// </summary>
/// <param name="prompt">The prompt to complete.</param>
/// <param name="executionSettings">Execution settings for the completion API.</param>
/// <param name="kernel">The <see cref="Kernel"/> containing services, plugins, and other state for use throughout the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>Completions generated by the remote model</returns>
internal async Task<IReadOnlyList<TextContent>> GetTextResultsAsync(
string prompt,
PromptExecutionSettings? executionSettings,
Kernel? kernel,
CancellationToken cancellationToken = default)
{
OpenAIPromptExecutionSettings textExecutionSettings = OpenAIPromptExecutionSettings.FromExecutionSettings(executionSettings, OpenAIPromptExecutionSettings.DefaultTextMaxTokens);
ValidateMaxTokens(textExecutionSettings.MaxTokens);
var options = CreateCompletionsOptions(prompt, textExecutionSettings, this.DeploymentOrModelName);
Completions? responseData = null;
List<TextContent> responseContent;
using (var activity = ModelDiagnostics.StartCompletionActivity(this.Endpoint, this.DeploymentOrModelName, ModelProvider, prompt, textExecutionSettings))
{
try
{
responseData = (await RunRequestAsync(() => this.Client.GetCompletionsAsync(options, cancellationToken)).ConfigureAwait(false)).Value;
if (responseData.Choices.Count == 0)
{
throw new KernelException("Text completions not found");
}
}
catch (Exception ex) when (activity is not null)
{
activity.SetError(ex);
if (responseData != null)
{
// Capture available metadata even if the operation failed.
activity
.SetResponseId(responseData.Id)
.SetPromptTokenUsage(responseData.Usage.PromptTokens)
.SetCompletionTokenUsage(responseData.Usage.CompletionTokens);
}
throw;
}
responseContent = responseData.Choices.Select(choice => new TextContent(choice.Text, this.DeploymentOrModelName, choice, Encoding.UTF8, GetTextChoiceMetadata(responseData, choice))).ToList();
activity?.SetCompletionResponse(responseContent, responseData.Usage.PromptTokens, responseData.Usage.CompletionTokens);
}
this.CaptureUsageDetails(responseData.Usage);
return responseContent;
}
internal async IAsyncEnumerable<StreamingTextContent> GetStreamingTextContentsAsync(
string prompt,
PromptExecutionSettings? executionSettings,
Kernel? kernel,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
OpenAIPromptExecutionSettings textExecutionSettings = OpenAIPromptExecutionSettings.FromExecutionSettings(executionSettings, OpenAIPromptExecutionSettings.DefaultTextMaxTokens);
ValidateMaxTokens(textExecutionSettings.MaxTokens);
var options = CreateCompletionsOptions(prompt, textExecutionSettings, this.DeploymentOrModelName);
using var activity = ModelDiagnostics.StartCompletionActivity(this.Endpoint, this.DeploymentOrModelName, ModelProvider, prompt, textExecutionSettings);
StreamingResponse<Completions> response;
try
{
response = await RunRequestAsync(() => this.Client.GetCompletionsStreamingAsync(options, cancellationToken)).ConfigureAwait(false);
}
catch (Exception ex) when (activity is not null)
{
activity.SetError(ex);
throw;
}
var responseEnumerator = response.ConfigureAwait(false).GetAsyncEnumerator();
List<OpenAIStreamingTextContent>? streamedContents = activity is not null ? [] : null;
try
{
while (true)
{
try
{
if (!await responseEnumerator.MoveNextAsync())
{
break;
}
}
catch (Exception ex) when (activity is not null)
{
activity.SetError(ex);
throw;
}
Completions completions = responseEnumerator.Current;
foreach (Choice choice in completions.Choices)
{
var openAIStreamingTextContent = new OpenAIStreamingTextContent(
choice.Text, choice.Index, this.DeploymentOrModelName, choice, GetTextChoiceMetadata(completions, choice));
streamedContents?.Add(openAIStreamingTextContent);
yield return openAIStreamingTextContent;
}
}
}
finally
{
activity?.EndStreaming(streamedContents);
await responseEnumerator.DisposeAsync();
}
}
private static Dictionary<string, object?> GetTextChoiceMetadata(Completions completions, Choice choice)
{
return new Dictionary<string, object?>(8)
{
{ nameof(completions.Id), completions.Id },
{ nameof(completions.Created), completions.Created },
{ nameof(completions.PromptFilterResults), completions.PromptFilterResults },
{ nameof(completions.Usage), completions.Usage },
{ nameof(choice.ContentFilterResults), choice.ContentFilterResults },
// Serialization of this struct behaves as an empty object {}, need to cast to string to avoid it.
{ nameof(choice.FinishReason), choice.FinishReason?.ToString() },
{ nameof(choice.LogProbabilityModel), choice.LogProbabilityModel },
{ nameof(choice.Index), choice.Index },
};
}
private static Dictionary<string, object?> GetChatChoiceMetadata(ChatCompletions completions, ChatChoice chatChoice)
{
return new Dictionary<string, object?>(12)
{
{ nameof(completions.Id), completions.Id },
{ nameof(completions.Created), completions.Created },
{ nameof(completions.PromptFilterResults), completions.PromptFilterResults },
{ nameof(completions.SystemFingerprint), completions.SystemFingerprint },
{ nameof(completions.Usage), completions.Usage },
{ nameof(chatChoice.ContentFilterResults), chatChoice.ContentFilterResults },
// Serialization of this struct behaves as an empty object {}, need to cast to string to avoid it.
{ nameof(chatChoice.FinishReason), chatChoice.FinishReason?.ToString() },
{ nameof(chatChoice.FinishDetails), chatChoice.FinishDetails },
{ nameof(chatChoice.LogProbabilityInfo), chatChoice.LogProbabilityInfo },
{ nameof(chatChoice.Index), chatChoice.Index },
{ nameof(chatChoice.Enhancements), chatChoice.Enhancements },
};
}
private static Dictionary<string, object?> GetResponseMetadata(StreamingChatCompletionsUpdate completions)
{
return new Dictionary<string, object?>(4)
{
{ nameof(completions.Id), completions.Id },
{ nameof(completions.Created), completions.Created },
{ nameof(completions.SystemFingerprint), completions.SystemFingerprint },
// Serialization of this struct behaves as an empty object {}, need to cast to string to avoid it.
{ nameof(completions.FinishReason), completions.FinishReason?.ToString() },
};
}
private static Dictionary<string, object?> GetResponseMetadata(AudioTranscription audioTranscription)
{
return new Dictionary<string, object?>(3)
{
{ nameof(audioTranscription.Language), audioTranscription.Language },
{ nameof(audioTranscription.Duration), audioTranscription.Duration },
{ nameof(audioTranscription.Segments), audioTranscription.Segments }
};
}
/// <summary>
/// Generates an embedding from the given <paramref name="data"/>.
/// </summary>
/// <param name="data">List of strings to generate embeddings for</param>
/// <param name="kernel">The <see cref="Kernel"/> containing services, plugins, and other state for use throughout the operation.</param>
/// <param name="dimensions">The number of dimensions the resulting output embeddings should have. Only supported in "text-embedding-3" and later models.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>List of embeddings</returns>
internal async Task<IList<ReadOnlyMemory<float>>> GetEmbeddingsAsync(
IList<string> data,
Kernel? kernel,
int? dimensions,
CancellationToken cancellationToken)
{
var result = new List<ReadOnlyMemory<float>>(data.Count);
if (data.Count > 0)
{
var embeddingsOptions = new EmbeddingsOptions(this.DeploymentOrModelName, data)
{
Dimensions = dimensions
};
var response = await RunRequestAsync(() => this.Client.GetEmbeddingsAsync(embeddingsOptions, cancellationToken)).ConfigureAwait(false);
var embeddings = response.Value.Data;
if (embeddings.Count != data.Count)
{
throw new KernelException($"Expected {data.Count} text embedding(s), but received {embeddings.Count}");
}
for (var i = 0; i < embeddings.Count; i++)
{
result.Add(embeddings[i].Embedding);
}
}
return result;
}
internal async Task<IReadOnlyList<TextContent>> GetTextContentFromAudioAsync(
AudioContent content,
PromptExecutionSettings? executionSettings,
CancellationToken cancellationToken)
{
Verify.NotNull(content.Data);
OpenAIAudioToTextExecutionSettings? audioExecutionSettings = OpenAIAudioToTextExecutionSettings.FromExecutionSettings(executionSettings);
Verify.ValidFilename(audioExecutionSettings?.Filename);
var audioOptions = new AudioTranscriptionOptions
{
AudioData = BinaryData.FromBytes(content.Data.Value),
DeploymentName = this.DeploymentOrModelName,
Filename = audioExecutionSettings.Filename,
Language = audioExecutionSettings.Language,
Prompt = audioExecutionSettings.Prompt,
ResponseFormat = audioExecutionSettings.ResponseFormat,
Temperature = audioExecutionSettings.Temperature
};
AudioTranscription responseData = (await RunRequestAsync(() => this.Client.GetAudioTranscriptionAsync(audioOptions, cancellationToken)).ConfigureAwait(false)).Value;
return [new(responseData.Text, this.DeploymentOrModelName, metadata: GetResponseMetadata(responseData))];
}
/// <summary>
/// Generate a new chat message
/// </summary>
/// <param name="chat">Chat history</param>
/// <param name="executionSettings">Execution settings for the completion API.</param>
/// <param name="kernel">The <see cref="Kernel"/> containing services, plugins, and other state for use throughout the operation.</param>
/// <param name="cancellationToken">Async cancellation token</param>
/// <returns>Generated chat message in string format</returns>
internal async Task<IReadOnlyList<ChatMessageContent>> GetChatMessageContentsAsync(
ChatHistory chat,
PromptExecutionSettings? executionSettings,
Kernel? kernel,
CancellationToken cancellationToken = default)
{
Verify.NotNull(chat);
// Convert the incoming execution settings to OpenAI settings.
OpenAIPromptExecutionSettings chatExecutionSettings = OpenAIPromptExecutionSettings.FromExecutionSettings(executionSettings);
bool autoInvoke = kernel is not null && chatExecutionSettings.ToolCallBehavior?.MaximumAutoInvokeAttempts > 0 && s_inflightAutoInvokes.Value < MaxInflightAutoInvokes;
ValidateMaxTokens(chatExecutionSettings.MaxTokens);
ValidateAutoInvoke(autoInvoke, chatExecutionSettings.ResultsPerPrompt);
// Create the Azure SDK ChatCompletionOptions instance from all available information.
var chatOptions = CreateChatCompletionsOptions(chatExecutionSettings, chat, kernel, this.DeploymentOrModelName);
for (int requestIndex = 1; ; requestIndex++)
{
// Make the request.
ChatCompletions? responseData = null;
List<OpenAIChatMessageContent> responseContent;
using (var activity = ModelDiagnostics.StartCompletionActivity(this.Endpoint, this.DeploymentOrModelName, ModelProvider, chat, chatExecutionSettings))
{
try
{
responseData = (await RunRequestAsync(() => this.Client.GetChatCompletionsAsync(chatOptions, cancellationToken)).ConfigureAwait(false)).Value;
this.CaptureUsageDetails(responseData.Usage);
if (responseData.Choices.Count == 0)
{
throw new KernelException("Chat completions not found");
}
}
catch (Exception ex) when (activity is not null)
{
activity.SetError(ex);
if (responseData != null)
{
// Capture available metadata even if the operation failed.
activity
.SetResponseId(responseData.Id)
.SetPromptTokenUsage(responseData.Usage.PromptTokens)
.SetCompletionTokenUsage(responseData.Usage.CompletionTokens);
}
throw;
}
responseContent = responseData.Choices.Select(chatChoice => this.GetChatMessage(chatChoice, responseData)).ToList();
activity?.SetCompletionResponse(responseContent, responseData.Usage.PromptTokens, responseData.Usage.CompletionTokens);
}
// If we don't want to attempt to invoke any functions, just return the result.
// Or if we are auto-invoking but we somehow end up with other than 1 choice even though only 1 was requested, similarly bail.
if (!autoInvoke || responseData.Choices.Count != 1)
{
return responseContent;
}
Debug.Assert(kernel is not null);
// Get our single result and extract the function call information. If this isn't a function call, or if it is
// but we're unable to find the function or extract the relevant information, just return the single result.
// Note that we don't check the FinishReason and instead check whether there are any tool calls, as the service
// may return a FinishReason of "stop" even if there are tool calls to be made, in particular if a required tool
// is specified.
ChatChoice resultChoice = responseData.Choices[0];
OpenAIChatMessageContent result = this.GetChatMessage(resultChoice, responseData);
if (result.ToolCalls.Count == 0)
{
return [result];
}
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Tool requests: {Requests}", result.ToolCalls.Count);
}
if (this.Logger.IsEnabled(LogLevel.Trace))
{
this.Logger.LogTrace("Function call requests: {Requests}", string.Join(", ", result.ToolCalls.OfType<ChatCompletionsFunctionToolCall>().Select(ftc => $"{ftc.Name}({ftc.Arguments})")));
}
// Add the original assistant message to the chatOptions; this is required for the service
// to understand the tool call responses. Also add the result message to the caller's chat
// history: if they don't want it, they can remove it, but this makes the data available,
// including metadata like usage.
chatOptions.Messages.Add(GetRequestMessage(resultChoice.Message));
chat.Add(result);
// We must send back a response for every tool call, regardless of whether we successfully executed it or not.
// If we successfully execute it, we'll add the result. If we don't, we'll add an error.
for (int toolCallIndex = 0; toolCallIndex < result.ToolCalls.Count; toolCallIndex++)
{
ChatCompletionsToolCall toolCall = result.ToolCalls[toolCallIndex];
// We currently only know about function tool calls. If it's anything else, we'll respond with an error.
if (toolCall is not ChatCompletionsFunctionToolCall functionToolCall)
{
AddResponseMessage(chatOptions, chat, result: null, "Error: Tool call was not a function call.", toolCall, this.Logger);
continue;
}
// Parse the function call arguments.
OpenAIFunctionToolCall? openAIFunctionToolCall;
try
{
openAIFunctionToolCall = new(functionToolCall);
}
catch (JsonException)
{
AddResponseMessage(chatOptions, chat, result: null, "Error: Function call arguments were invalid JSON.", toolCall, this.Logger);
continue;
}
// Make sure the requested function is one we requested. If we're permitting any kernel function to be invoked,
// then we don't need to check this, as it'll be handled when we look up the function in the kernel to be able
// to invoke it. If we're permitting only a specific list of functions, though, then we need to explicitly check.
if (chatExecutionSettings.ToolCallBehavior?.AllowAnyRequestedKernelFunction is not true &&
!IsRequestableTool(chatOptions, openAIFunctionToolCall))
{
AddResponseMessage(chatOptions, chat, result: null, "Error: Function call request for a function that wasn't defined.", toolCall, this.Logger);
continue;
}
// Find the function in the kernel and populate the arguments.
if (!kernel!.Plugins.TryGetFunctionAndArguments(openAIFunctionToolCall, out KernelFunction? function, out KernelArguments? functionArgs))
{
AddResponseMessage(chatOptions, chat, result: null, "Error: Requested function could not be found.", toolCall, this.Logger);
continue;
}
// Now, invoke the function, and add the resulting tool call message to the chat options.
FunctionResult functionResult = new(function) { Culture = kernel.Culture };
AutoFunctionInvocationContext invocationContext = new(kernel, function, functionResult, chat)
{
Arguments = functionArgs,
RequestSequenceIndex = requestIndex - 1,
FunctionSequenceIndex = toolCallIndex,
FunctionCount = result.ToolCalls.Count
};
s_inflightAutoInvokes.Value++;
try
{
invocationContext = await OnAutoFunctionInvocationAsync(kernel, invocationContext, async (context) =>
{
// Check if filter requested termination.
if (context.Terminate)
{
return;
}
// Note that we explicitly do not use executionSettings here; those pertain to the all-up operation and not necessarily to any
// further calls made as part of this function invocation. In particular, we must not use function calling settings naively here,
// as the called function could in turn telling the model about itself as a possible candidate for invocation.
context.Result = await function.InvokeAsync(kernel, invocationContext.Arguments, cancellationToken: cancellationToken).ConfigureAwait(false);
}).ConfigureAwait(false);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
{
AddResponseMessage(chatOptions, chat, null, $"Error: Exception while invoking function. {e.Message}", toolCall, this.Logger);
continue;
}
finally
{
s_inflightAutoInvokes.Value--;
}
// Apply any changes from the auto function invocation filters context to final result.
functionResult = invocationContext.Result;
object functionResultValue = functionResult.GetValue<object>() ?? string.Empty;
var stringResult = ProcessFunctionResult(functionResultValue, chatExecutionSettings.ToolCallBehavior);
AddResponseMessage(chatOptions, chat, stringResult, errorMessage: null, functionToolCall, this.Logger);
// If filter requested termination, returning latest function result.
if (invocationContext.Terminate)
{
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Filter requested termination of automatic function invocation.");
}
return [chat.Last()];
}
static void AddResponseMessage(ChatCompletionsOptions chatOptions, ChatHistory chat, string? result, string? errorMessage, ChatCompletionsToolCall toolCall, ILogger logger)
{
// Log any error
if (errorMessage is not null && logger.IsEnabled(LogLevel.Debug))
{
Debug.Assert(result is null);
logger.LogDebug("Failed to handle tool request ({ToolId}). {Error}", toolCall.Id, errorMessage);
}
// Add the tool response message to the chat options
result ??= errorMessage ?? string.Empty;
chatOptions.Messages.Add(new ChatRequestToolMessage(result, toolCall.Id));
// Add the tool response message to the chat history.
var message = new ChatMessageContent(role: AuthorRole.Tool, content: result, metadata: new Dictionary<string, object?> { { OpenAIChatMessageContent.ToolIdProperty, toolCall.Id } });
if (toolCall is ChatCompletionsFunctionToolCall functionCall)
{
// Add an item of type FunctionResultContent to the ChatMessageContent.Items collection in addition to the function result stored as a string in the ChatMessageContent.Content property.
// This will enable migration to the new function calling model and facilitate the deprecation of the current one in the future.
var functionName = FunctionName.Parse(functionCall.Name, OpenAIFunction.NameSeparator);
message.Items.Add(new FunctionResultContent(functionName.Name, functionName.PluginName, functionCall.Id, result));
}
chat.Add(message);
}
}
// Update tool use information for the next go-around based on having completed another iteration.
Debug.Assert(chatExecutionSettings.ToolCallBehavior is not null);
// Set the tool choice to none. If we end up wanting to use tools, we'll reset it to the desired value.
chatOptions.ToolChoice = ChatCompletionsToolChoice.None;
chatOptions.Tools.Clear();
if (requestIndex >= chatExecutionSettings.ToolCallBehavior!.MaximumUseAttempts)
{
// Don't add any tools as we've reached the maximum attempts limit.
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Maximum use ({MaximumUse}) reached; removing the tool.", chatExecutionSettings.ToolCallBehavior!.MaximumUseAttempts);
}
}
else
{
// Regenerate the tool list as necessary. The invocation of the function(s) could have augmented
// what functions are available in the kernel.
chatExecutionSettings.ToolCallBehavior.ConfigureOptions(kernel, chatOptions);
}
// Having already sent tools and with tool call information in history, the service can become unhappy ("[] is too short - 'tools'")
// if we don't send any tools in subsequent requests, even if we say not to use any.
if (chatOptions.ToolChoice == ChatCompletionsToolChoice.None)
{
Debug.Assert(chatOptions.Tools.Count == 0);
chatOptions.Tools.Add(s_nonInvocableFunctionTool);
}
// Disable auto invocation if we've exceeded the allowed limit.
if (requestIndex >= chatExecutionSettings.ToolCallBehavior!.MaximumAutoInvokeAttempts)
{
autoInvoke = false;
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Maximum auto-invoke ({MaximumAutoInvoke}) reached.", chatExecutionSettings.ToolCallBehavior!.MaximumAutoInvokeAttempts);
}
}
}
}
internal async IAsyncEnumerable<OpenAIStreamingChatMessageContent> GetStreamingChatMessageContentsAsync(
ChatHistory chat,
PromptExecutionSettings? executionSettings,
Kernel? kernel,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Verify.NotNull(chat);
OpenAIPromptExecutionSettings chatExecutionSettings = OpenAIPromptExecutionSettings.FromExecutionSettings(executionSettings);
ValidateMaxTokens(chatExecutionSettings.MaxTokens);
bool autoInvoke = kernel is not null && chatExecutionSettings.ToolCallBehavior?.MaximumAutoInvokeAttempts > 0 && s_inflightAutoInvokes.Value < MaxInflightAutoInvokes;
ValidateAutoInvoke(autoInvoke, chatExecutionSettings.ResultsPerPrompt);
var chatOptions = CreateChatCompletionsOptions(chatExecutionSettings, chat, kernel, this.DeploymentOrModelName);
StringBuilder? contentBuilder = null;
Dictionary<int, string>? toolCallIdsByIndex = null;
Dictionary<int, string>? functionNamesByIndex = null;
Dictionary<int, StringBuilder>? functionArgumentBuildersByIndex = null;
for (int requestIndex = 1; ; requestIndex++)
{
// Reset state
contentBuilder?.Clear();
toolCallIdsByIndex?.Clear();
functionNamesByIndex?.Clear();
functionArgumentBuildersByIndex?.Clear();
// Stream the response.
IReadOnlyDictionary<string, object?>? metadata = null;
string? streamedName = null;
ChatRole? streamedRole = default;
CompletionsFinishReason finishReason = default;
using (var activity = ModelDiagnostics.StartCompletionActivity(this.Endpoint, this.DeploymentOrModelName, ModelProvider, chat, chatExecutionSettings))
{
// Make the request.
StreamingResponse<StreamingChatCompletionsUpdate> response;
try
{
response = await RunRequestAsync(() => this.Client.GetChatCompletionsStreamingAsync(chatOptions, cancellationToken)).ConfigureAwait(false);
}
catch (Exception ex) when (activity is not null)
{
activity.SetError(ex);
throw;
}
var responseEnumerator = response.ConfigureAwait(false).GetAsyncEnumerator();
List<OpenAIStreamingChatMessageContent>? streamedContents = activity is not null ? [] : null;
try
{
while (true)
{
try
{
if (!await responseEnumerator.MoveNextAsync())
{
break;
}
}
catch (Exception ex) when (activity is not null)
{
activity.SetError(ex);
throw;
}
StreamingChatCompletionsUpdate update = responseEnumerator.Current;
metadata = GetResponseMetadata(update);
streamedRole ??= update.Role;
streamedName ??= update.AuthorName;
finishReason = update.FinishReason ?? default;
// If we're intending to invoke function calls, we need to consume that function call information.
if (autoInvoke)
{
if (update.ContentUpdate is { Length: > 0 } contentUpdate)
{
(contentBuilder ??= new()).Append(contentUpdate);
}
OpenAIFunctionToolCall.TrackStreamingToolingUpdate(update.ToolCallUpdate, ref toolCallIdsByIndex, ref functionNamesByIndex, ref functionArgumentBuildersByIndex);
}
var openAIStreamingChatMessageContent = new OpenAIStreamingChatMessageContent(update, update.ChoiceIndex ?? 0, this.DeploymentOrModelName, metadata) { AuthorName = streamedName };
streamedContents?.Add(openAIStreamingChatMessageContent);
yield return openAIStreamingChatMessageContent;
}
}
finally
{
activity?.EndStreaming(streamedContents);
await responseEnumerator.DisposeAsync();
}
}
// If we don't have a function to invoke, we're done.
// Note that we don't check the FinishReason and instead check whether there are any tool calls, as the service
// may return a FinishReason of "stop" even if there are tool calls to be made, in particular if a required tool
// is specified.
if (!autoInvoke ||
toolCallIdsByIndex is not { Count: > 0 })
{
yield break;
}
// Get any response content that was streamed.
string content = contentBuilder?.ToString() ?? string.Empty;
// Translate all entries into ChatCompletionsFunctionToolCall instances.
ChatCompletionsFunctionToolCall[] toolCalls = OpenAIFunctionToolCall.ConvertToolCallUpdatesToChatCompletionsFunctionToolCalls(
ref toolCallIdsByIndex, ref functionNamesByIndex, ref functionArgumentBuildersByIndex);
// Log the requests
if (this.Logger.IsEnabled(LogLevel.Trace))
{
this.Logger.LogTrace("Function call requests: {Requests}", string.Join(", ", toolCalls.Select(fcr => $"{fcr.Name}({fcr.Arguments})")));
}
else if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Function call requests: {Requests}", toolCalls.Length);
}
// Add the original assistant message to the chatOptions; this is required for the service
// to understand the tool call responses.
chatOptions.Messages.Add(GetRequestMessage(streamedRole ?? default, content, streamedName, toolCalls));
chat.Add(new OpenAIChatMessageContent(streamedRole ?? default, content, this.DeploymentOrModelName, toolCalls, metadata) { AuthorName = streamedName });
// Respond to each tooling request.
for (int toolCallIndex = 0; toolCallIndex < toolCalls.Length; toolCallIndex++)
{
ChatCompletionsFunctionToolCall toolCall = toolCalls[toolCallIndex];
// We currently only know about function tool calls. If it's anything else, we'll respond with an error.
if (string.IsNullOrEmpty(toolCall.Name))
{
AddResponseMessage(chatOptions, chat, streamedRole, toolCall, metadata, result: null, "Error: Tool call was not a function call.", this.Logger);
continue;
}
// Parse the function call arguments.
OpenAIFunctionToolCall? openAIFunctionToolCall;
try
{
openAIFunctionToolCall = new(toolCall);
}
catch (JsonException)
{
AddResponseMessage(chatOptions, chat, streamedRole, toolCall, metadata, result: null, "Error: Function call arguments were invalid JSON.", this.Logger);
continue;
}
// Make sure the requested function is one we requested. If we're permitting any kernel function to be invoked,
// then we don't need to check this, as it'll be handled when we look up the function in the kernel to be able
// to invoke it. If we're permitting only a specific list of functions, though, then we need to explicitly check.
if (chatExecutionSettings.ToolCallBehavior?.AllowAnyRequestedKernelFunction is not true &&
!IsRequestableTool(chatOptions, openAIFunctionToolCall))
{
AddResponseMessage(chatOptions, chat, streamedRole, toolCall, metadata, result: null, "Error: Function call request for a function that wasn't defined.", this.Logger);
continue;
}
// Find the function in the kernel and populate the arguments.
if (!kernel!.Plugins.TryGetFunctionAndArguments(openAIFunctionToolCall, out KernelFunction? function, out KernelArguments? functionArgs))
{
AddResponseMessage(chatOptions, chat, streamedRole, toolCall, metadata, result: null, "Error: Requested function could not be found.", this.Logger);
continue;
}
// Now, invoke the function, and add the resulting tool call message to the chat options.
FunctionResult functionResult = new(function) { Culture = kernel.Culture };
AutoFunctionInvocationContext invocationContext = new(kernel, function, functionResult, chat)
{
Arguments = functionArgs,
RequestSequenceIndex = requestIndex - 1,
FunctionSequenceIndex = toolCallIndex,
FunctionCount = toolCalls.Length
};
s_inflightAutoInvokes.Value++;
try
{
invocationContext = await OnAutoFunctionInvocationAsync(kernel, invocationContext, async (context) =>
{
// Check if filter requested termination.
if (context.Terminate)
{
return;
}
// Note that we explicitly do not use executionSettings here; those pertain to the all-up operation and not necessarily to any
// further calls made as part of this function invocation. In particular, we must not use function calling settings naively here,
// as the called function could in turn telling the model about itself as a possible candidate for invocation.
context.Result = await function.InvokeAsync(kernel, invocationContext.Arguments, cancellationToken: cancellationToken).ConfigureAwait(false);
}).ConfigureAwait(false);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
{
AddResponseMessage(chatOptions, chat, streamedRole, toolCall, metadata, result: null, $"Error: Exception while invoking function. {e.Message}", this.Logger);
continue;
}
finally
{
s_inflightAutoInvokes.Value--;
}
// Apply any changes from the auto function invocation filters context to final result.
functionResult = invocationContext.Result;
object functionResultValue = functionResult.GetValue<object>() ?? string.Empty;
var stringResult = ProcessFunctionResult(functionResultValue, chatExecutionSettings.ToolCallBehavior);
AddResponseMessage(chatOptions, chat, streamedRole, toolCall, metadata, stringResult, errorMessage: null, this.Logger);
// If filter requested termination, breaking request iteration loop.
if (invocationContext.Terminate)
{
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Filter requested termination of automatic function invocation.");
}
yield break;
}
static void AddResponseMessage(
ChatCompletionsOptions chatOptions, ChatHistory chat, ChatRole? streamedRole, ChatCompletionsToolCall tool, IReadOnlyDictionary<string, object?>? metadata,
string? result, string? errorMessage, ILogger logger)
{
if (errorMessage is not null && logger.IsEnabled(LogLevel.Debug))
{
Debug.Assert(result is null);
logger.LogDebug("Failed to handle tool request ({ToolId}). {Error}", tool.Id, errorMessage);
}
// Add the tool response message to both the chat options and to the chat history.
result ??= errorMessage ?? string.Empty;
chatOptions.Messages.Add(new ChatRequestToolMessage(result, tool.Id));
chat.AddMessage(AuthorRole.Tool, result, metadata: new Dictionary<string, object?> { { OpenAIChatMessageContent.ToolIdProperty, tool.Id } });
}
}
// Update tool use information for the next go-around based on having completed another iteration.
Debug.Assert(chatExecutionSettings.ToolCallBehavior is not null);
// Set the tool choice to none. If we end up wanting to use tools, we'll reset it to the desired value.
chatOptions.ToolChoice = ChatCompletionsToolChoice.None;
chatOptions.Tools.Clear();
if (requestIndex >= chatExecutionSettings.ToolCallBehavior!.MaximumUseAttempts)
{
// Don't add any tools as we've reached the maximum attempts limit.
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Maximum use ({MaximumUse}) reached; removing the tool.", chatExecutionSettings.ToolCallBehavior!.MaximumUseAttempts);
}
}
else
{
// Regenerate the tool list as necessary. The invocation of the function(s) could have augmented
// what functions are available in the kernel.
chatExecutionSettings.ToolCallBehavior.ConfigureOptions(kernel, chatOptions);
}
// Having already sent tools and with tool call information in history, the service can become unhappy ("[] is too short - 'tools'")
// if we don't send any tools in subsequent requests, even if we say not to use any.
if (chatOptions.ToolChoice == ChatCompletionsToolChoice.None)
{
Debug.Assert(chatOptions.Tools.Count == 0);
chatOptions.Tools.Add(s_nonInvocableFunctionTool);
}
// Disable auto invocation if we've exceeded the allowed limit.
if (requestIndex >= chatExecutionSettings.ToolCallBehavior!.MaximumAutoInvokeAttempts)
{
autoInvoke = false;
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Maximum auto-invoke ({MaximumAutoInvoke}) reached.", chatExecutionSettings.ToolCallBehavior!.MaximumAutoInvokeAttempts);
}
}
}
}
/// <summary>Checks if a tool call is for a function that was defined.</summary>
private static bool IsRequestableTool(ChatCompletionsOptions options, OpenAIFunctionToolCall ftc)
{
IList<ChatCompletionsToolDefinition> tools = options.Tools;
for (int i = 0; i < tools.Count; i++)
{
if (tools[i] is ChatCompletionsFunctionToolDefinition def &&
string.Equals(def.Name, ftc.FullyQualifiedName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
internal async IAsyncEnumerable<StreamingTextContent> GetChatAsTextStreamingContentsAsync(
string prompt,
PromptExecutionSettings? executionSettings,
Kernel? kernel,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
OpenAIPromptExecutionSettings chatSettings = OpenAIPromptExecutionSettings.FromExecutionSettings(executionSettings);
ChatHistory chat = CreateNewChat(prompt, chatSettings);
await foreach (var chatUpdate in this.GetStreamingChatMessageContentsAsync(chat, executionSettings, kernel, cancellationToken).ConfigureAwait(false))
{
yield return new StreamingTextContent(chatUpdate.Content, chatUpdate.ChoiceIndex, chatUpdate.ModelId, chatUpdate, Encoding.UTF8, chatUpdate.Metadata);
}
}
internal async Task<IReadOnlyList<TextContent>> GetChatAsTextContentsAsync(
string text,
PromptExecutionSettings? executionSettings,
Kernel? kernel,
CancellationToken cancellationToken = default)
{
OpenAIPromptExecutionSettings chatSettings = OpenAIPromptExecutionSettings.FromExecutionSettings(executionSettings);
ChatHistory chat = CreateNewChat(text, chatSettings);
return (await this.GetChatMessageContentsAsync(chat, chatSettings, kernel, cancellationToken).ConfigureAwait(false))
.Select(chat => new TextContent(chat.Content, chat.ModelId, chat.Content, Encoding.UTF8, chat.Metadata))
.ToList();
}
internal void AddAttribute(string key, string? value)
{
if (!string.IsNullOrEmpty(value))
{
this.Attributes.Add(key, value);
}
}
/// <summary>Gets options to use for an OpenAIClient</summary>
/// <param name="httpClient">Custom <see cref="HttpClient"/> for HTTP requests.</param>
/// <param name="serviceVersion">Optional API version.</param>
/// <returns>An instance of <see cref="OpenAIClientOptions"/>.</returns>
internal static OpenAIClientOptions GetOpenAIClientOptions(HttpClient? httpClient, OpenAIClientOptions.ServiceVersion? serviceVersion = null)
{
OpenAIClientOptions options = serviceVersion is not null ?
new(serviceVersion.Value) :
new();
options.Diagnostics.ApplicationId = HttpHeaderConstant.Values.UserAgent;
options.AddPolicy(new AddHeaderRequestPolicy(HttpHeaderConstant.Names.SemanticKernelVersion, HttpHeaderConstant.Values.GetAssemblyVersion(typeof(ClientCore))), HttpPipelinePosition.PerCall);
if (httpClient is not null)
{
options.Transport = new HttpClientTransport(httpClient);
options.RetryPolicy = new RetryPolicy(maxRetries: 0); // Disable Azure SDK retry policy if and only if a custom HttpClient is provided.
options.Retry.NetworkTimeout = Timeout.InfiniteTimeSpan; // Disable Azure SDK default timeout
}
return options;
}
/// <summary>
/// Create a new empty chat instance
/// </summary>
/// <param name="text">Optional chat instructions for the AI service</param>
/// <param name="executionSettings">Execution settings</param>
/// <returns>Chat object</returns>
private static ChatHistory CreateNewChat(string? text = null, OpenAIPromptExecutionSettings? executionSettings = null)