forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatCompletionAgent.cs
372 lines (314 loc) · 14.8 KB
/
ChatCompletionAgent.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
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SemanticKernel.Agents.Extensions;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Services;
namespace Microsoft.SemanticKernel.Agents;
/// <summary>
/// Represents a <see cref="Agent"/> specialization based on <see cref="IChatCompletionService"/>.
/// </summary>
/// <remarks>
/// NOTE: Enable <see cref="PromptExecutionSettings.FunctionChoiceBehavior"/> for agent plugins
/// (<see cref="Agent.Arguments"/>).
/// </remarks>
public sealed class ChatCompletionAgent : ChatHistoryAgent
{
/// <summary>
/// Initializes a new instance of the <see cref="ChatCompletionAgent"/> class.
/// </summary>
public ChatCompletionAgent() { }
/// <summary>
/// Initializes a new instance of the <see cref="ChatCompletionAgent"/> class from
/// a <see cref="PromptTemplateConfig"/>.
/// </summary>
/// <param name="templateConfig">The prompt template configuration.</param>
/// <param name="templateFactory">The prompt template factory used to produce the <see cref="IPromptTemplate"/> for the agent.</param>
public ChatCompletionAgent(
PromptTemplateConfig templateConfig,
IPromptTemplateFactory templateFactory)
{
this.Name = templateConfig.Name;
this.Description = templateConfig.Description;
this.Instructions = templateConfig.Template;
this.Arguments = new(templateConfig.ExecutionSettings.Values);
this.Template = templateFactory.Create(templateConfig);
}
/// <summary>
/// Gets the role used for agent instructions. Defaults to "system".
/// </summary>
/// <remarks>
/// Certain versions of "O*" series (deep reasoning) models require the instructions
/// to be provided as "developer" role. Other versions support neither role and
/// an agent targeting such a model cannot provide instructions. Agent functionality
/// will be dictated entirely by the provided plugins.
/// </remarks>
public AuthorRole InstructionsRole { get; init; } = AuthorRole.System;
/// <inheritdoc/>
public override async IAsyncEnumerable<AgentResponseItem<ChatMessageContent>> InvokeAsync(
ICollection<ChatMessageContent> messages,
AgentThread? thread = null,
AgentInvokeOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Verify.NotNull(messages);
var chatHistoryAgentThread = await this.EnsureThreadExistsWithMessagesAsync(
messages,
thread,
() => new ChatHistoryAgentThread(),
cancellationToken).ConfigureAwait(false);
// Invoke Chat Completion with the updated chat history.
var chatHistory = new ChatHistory();
await foreach (var existingMessage in chatHistoryAgentThread.GetMessagesAsync(cancellationToken).ConfigureAwait(false))
{
chatHistory.Add(existingMessage);
}
var invokeResults = this.InternalInvokeAsync(
this.GetDisplayName(),
chatHistory,
async (m) =>
{
await this.NotifyThreadOfNewMessage(chatHistoryAgentThread, m, cancellationToken).ConfigureAwait(false);
if (options?.OnNewMessage is not null)
{
await options.OnNewMessage(m).ConfigureAwait(false);
}
},
options?.KernelArguments,
options?.Kernel,
options?.AdditionalInstructions,
cancellationToken);
// Notify the thread of new messages and return them to the caller.
await foreach (var result in invokeResults.ConfigureAwait(false))
{
// 1. During AutoInvoke = true, the function call content is provided via the callback
// above, since it is not returned as part of the regular response to the user.
// 2. During AutoInvoke = false, the function call content is returned directly as a
// regular response here.
// 3. If the user Terminates the function call, via a filter, the function call content
// is also returned as part of the regular response here.
//
// In the first case, we don't want to add the function call content to the thread here
// since it should already have been added in the callback above.
// In the second case, we shouldn't add the function call content to the thread, since
// we don't know if the user will execute the call. They should add it themselves.
// In the third case, we don't want to add the function call content to the thread either,
// since the filter terminated the call, and therefore won't get executed.
if (!result.Items.Any(i => i is FunctionCallContent || i is FunctionResultContent))
{
await this.NotifyThreadOfNewMessage(chatHistoryAgentThread, result, cancellationToken).ConfigureAwait(false);
if (options?.OnNewMessage is not null)
{
await options.OnNewMessage(result).ConfigureAwait(false);
}
}
yield return new(result, chatHistoryAgentThread);
}
}
/// <inheritdoc/>
[Obsolete("Use InvokeAsync with AgentThread instead.")]
public override IAsyncEnumerable<ChatMessageContent> InvokeAsync(
ChatHistory history,
KernelArguments? arguments = null,
Kernel? kernel = null,
CancellationToken cancellationToken = default)
{
string agentName = this.GetDisplayName();
return ActivityExtensions.RunWithActivityAsync(
() => ModelDiagnostics.StartAgentInvocationActivity(this.Id, agentName, this.Description),
() => this.InternalInvokeAsync(agentName, history, (m) => Task.CompletedTask, arguments, kernel, null, cancellationToken),
cancellationToken);
}
/// <inheritdoc/>
public override async IAsyncEnumerable<AgentResponseItem<StreamingChatMessageContent>> InvokeStreamingAsync(
ICollection<ChatMessageContent> messages,
AgentThread? thread = null,
AgentInvokeOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Verify.NotNull(messages);
var chatHistoryAgentThread = await this.EnsureThreadExistsWithMessagesAsync(
messages,
thread,
() => new ChatHistoryAgentThread(),
cancellationToken).ConfigureAwait(false);
// Invoke Chat Completion with the updated chat history.
var chatHistory = new ChatHistory();
await foreach (var existingMessage in chatHistoryAgentThread.GetMessagesAsync(cancellationToken).ConfigureAwait(false))
{
chatHistory.Add(existingMessage);
}
string agentName = this.GetDisplayName();
var invokeResults = this.InternalInvokeStreamingAsync(
agentName,
chatHistory,
async (m) =>
{
await this.NotifyThreadOfNewMessage(chatHistoryAgentThread, m, cancellationToken).ConfigureAwait(false);
if (options?.OnNewMessage is not null)
{
await options.OnNewMessage(m).ConfigureAwait(false);
}
},
options?.KernelArguments,
options?.Kernel,
options?.AdditionalInstructions,
cancellationToken);
await foreach (var result in invokeResults.ConfigureAwait(false))
{
yield return new(result, chatHistoryAgentThread);
}
}
/// <inheritdoc/>
[Obsolete("Use InvokeStreamingAsync with AgentThread instead.")]
public override IAsyncEnumerable<StreamingChatMessageContent> InvokeStreamingAsync(
ChatHistory history,
KernelArguments? arguments = null,
Kernel? kernel = null,
CancellationToken cancellationToken = default)
{
string agentName = this.GetDisplayName();
return ActivityExtensions.RunWithActivityAsync(
() => ModelDiagnostics.StartAgentInvocationActivity(this.Id, agentName, this.Description),
() => this.InternalInvokeStreamingAsync(
agentName,
history,
(newMessage) => Task.CompletedTask,
arguments,
kernel,
null,
cancellationToken),
cancellationToken);
}
/// <inheritdoc/>
[Experimental("SKEXP0110")]
protected override Task<AgentChannel> RestoreChannelAsync(string channelState, CancellationToken cancellationToken)
{
ChatHistory history =
JsonSerializer.Deserialize<ChatHistory>(channelState) ??
throw new KernelException("Unable to restore channel: invalid state.");
return Task.FromResult<AgentChannel>(new ChatHistoryChannel(history));
}
internal static (IChatCompletionService service, PromptExecutionSettings? executionSettings) GetChatCompletionService(Kernel kernel, KernelArguments? arguments)
{
(IChatCompletionService chatCompletionService, PromptExecutionSettings? executionSettings) =
kernel.ServiceSelector.SelectAIService<IChatCompletionService>(
kernel,
arguments?.ExecutionSettings,
arguments ?? []);
return (chatCompletionService, executionSettings);
}
#region private
private async Task<ChatHistory> SetupAgentChatHistoryAsync(
IReadOnlyList<ChatMessageContent> history,
KernelArguments? arguments,
Kernel kernel,
string? additionalInstructions,
CancellationToken cancellationToken)
{
ChatHistory chat = [];
string? instructions = await this.RenderInstructionsAsync(kernel, arguments, cancellationToken).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(instructions))
{
chat.Add(new ChatMessageContent(this.InstructionsRole, instructions) { AuthorName = this.Name });
}
if (!string.IsNullOrWhiteSpace(additionalInstructions))
{
chat.Add(new ChatMessageContent(AuthorRole.System, additionalInstructions) { AuthorName = this.Name });
}
chat.AddRange(history);
return chat;
}
private async IAsyncEnumerable<ChatMessageContent> InternalInvokeAsync(
string agentName,
ChatHistory history,
Func<ChatMessageContent, Task> onNewToolMessage,
KernelArguments? arguments = null,
Kernel? kernel = null,
string? additionalInstructions = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
kernel ??= this.Kernel;
(IChatCompletionService chatCompletionService, PromptExecutionSettings? executionSettings) = GetChatCompletionService(kernel, arguments);
ChatHistory chat = await this.SetupAgentChatHistoryAsync(history, arguments, kernel, additionalInstructions, cancellationToken).ConfigureAwait(false);
int messageCount = chat.Count;
Type serviceType = chatCompletionService.GetType();
this.Logger.LogAgentChatServiceInvokingAgent(nameof(InvokeAsync), this.Id, agentName, serviceType);
IReadOnlyList<ChatMessageContent> messages =
await chatCompletionService.GetChatMessageContentsAsync(
chat,
executionSettings,
kernel,
cancellationToken).ConfigureAwait(false);
this.Logger.LogAgentChatServiceInvokedAgent(nameof(InvokeAsync), this.Id, agentName, serviceType, messages.Count);
// Capture mutated messages related function calling / tools
for (int messageIndex = messageCount; messageIndex < chat.Count; messageIndex++)
{
ChatMessageContent message = chat[messageIndex];
message.AuthorName = this.Name;
history.Add(message);
await onNewToolMessage(message).ConfigureAwait(false);
}
foreach (ChatMessageContent message in messages)
{
message.AuthorName = this.Name;
yield return message;
}
}
private async IAsyncEnumerable<StreamingChatMessageContent> InternalInvokeStreamingAsync(
string agentName,
ChatHistory history,
Func<ChatMessageContent, Task> onNewMessage,
KernelArguments? arguments = null,
Kernel? kernel = null,
string? additionalInstructions = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
kernel ??= this.Kernel;
(IChatCompletionService chatCompletionService, PromptExecutionSettings? executionSettings) = GetChatCompletionService(kernel, arguments);
ChatHistory chat = await this.SetupAgentChatHistoryAsync(history, arguments, kernel, additionalInstructions, cancellationToken).ConfigureAwait(false);
int messageCount = chat.Count;
Type serviceType = chatCompletionService.GetType();
this.Logger.LogAgentChatServiceInvokingAgent(nameof(InvokeAsync), this.Id, agentName, serviceType);
IAsyncEnumerable<StreamingChatMessageContent> messages =
chatCompletionService.GetStreamingChatMessageContentsAsync(
chat,
executionSettings,
kernel,
cancellationToken);
this.Logger.LogAgentChatServiceInvokedStreamingAgent(nameof(InvokeAsync), this.Id, agentName, serviceType);
AuthorRole? role = null;
StringBuilder builder = new();
await foreach (StreamingChatMessageContent message in messages.ConfigureAwait(false))
{
role = message.Role;
message.Role ??= AuthorRole.Assistant;
message.AuthorName = this.Name;
builder.Append(message.ToString());
yield return message;
}
// Capture mutated messages related function calling / tools
for (int messageIndex = messageCount; messageIndex < chat.Count; messageIndex++)
{
ChatMessageContent message = chat[messageIndex];
message.AuthorName = this.Name;
await onNewMessage(message).ConfigureAwait(false);
history.Add(message);
}
// Do not duplicate terminated function result to history
if (role != AuthorRole.Tool)
{
await onNewMessage(new(role ?? AuthorRole.Assistant, builder.ToString()) { AuthorName = this.Name }).ConfigureAwait(false);
history.Add(new(role ?? AuthorRole.Assistant, builder.ToString()) { AuthorName = this.Name });
}
}
#endregion
}