forked from microsoft/agent-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLightningAgent.cs
More file actions
233 lines (199 loc) · 7.97 KB
/
LightningAgent.cs
File metadata and controls
233 lines (199 loc) · 7.97 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
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using ManagedCode.AgentLightning.Core.Models;
using ManagedCode.AgentLightning.Core.Resources;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
namespace ManagedCode.AgentLightning.AgentRuntime;
/// <summary>
/// Executes rollouts by delegating to <see cref="IChatClient"/>.
/// </summary>
public sealed class LightningAgent : LitAgentBase<object>, IDisposable
{
private readonly IChatClient _chatClient;
private readonly ILogger<LightningAgent> _logger;
private readonly LightningAgentOptions _options;
private readonly IReadOnlyList<Hook> _hooks;
private readonly TimeProvider _timeProvider;
private bool _disposed;
public LightningAgent(
IChatClient chatClient,
Microsoft.Extensions.Options.IOptions<LightningAgentOptions> options,
IEnumerable<Hook>? hooks,
ILogger<LightningAgent> logger,
TimeProvider? timeProvider = null)
: this(chatClient, options?.Value ?? throw new ArgumentNullException(nameof(options)), hooks, logger, timeProvider)
{
}
public LightningAgent(
IChatClient chatClient,
LightningAgentOptions options,
IEnumerable<Hook>? hooks,
ILogger<LightningAgent> logger,
TimeProvider? timeProvider = null)
{
_chatClient = chatClient ?? throw new ArgumentNullException(nameof(chatClient));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_hooks = hooks?.ToArray() ?? Array.Empty<Hook>();
_timeProvider = timeProvider ?? TimeProvider.System;
}
protected override async Task<LightningExecutionResult> RolloutAsync(
object taskInput,
NamedResources? resources,
RolloutMode? mode,
string? resourcesId,
CancellationToken cancellationToken)
{
ThrowIfDisposed();
var startTimestamp = _timeProvider.GetUtcNow();
var rolloutId = GenerateRolloutId(taskInput);
var rollout = new Rollout(
rolloutId,
taskInput,
startTimestamp,
config: _options.RolloutConfig,
mode: mode,
resourcesId: resourcesId);
var attempt = new Attempt(
rolloutId,
$"{rolloutId}:attempt:1",
sequenceId: 1,
startTimestamp);
if (!string.IsNullOrEmpty(resourcesId))
{
var id = resourcesId!;
rollout.AddMetadata("resources.id", id);
attempt.AddMetadata("resources.id", id);
}
if (resources is { Count: > 0 })
{
var resourceNames = resources.Keys.ToArray();
rollout.AddMetadata("resources.names", resourceNames);
attempt.AddMetadata("resources.names", resourceNames);
}
if (mode is { } rolloutMode)
{
rollout.AddMetadata("mode", rolloutMode.ToString());
}
var context = new LightningContext(this, this, rollout);
await InvokeHooksAsync(h => h.OnTraceStartAsync(context, cancellationToken), cancellationToken).ConfigureAwait(false);
attempt.UpdateStatus(AttemptStatus.Running);
attempt.Touch(startTimestamp);
rollout.TransitionTo(RolloutStatus.Preparing);
await InvokeHooksAsync(h => h.OnRolloutStartAsync(context, cancellationToken), cancellationToken).ConfigureAwait(false);
rollout.TransitionTo(RolloutStatus.Running);
IReadOnlyList<ChatMessage> prompt = _options.BuildPrompt(taskInput);
try
{
var response = await _chatClient
.GetResponseAsync(prompt, _options.ChatOptions, cancellationToken)
.ConfigureAwait(false);
attempt.UpdateStatus(AttemptStatus.Succeeded, _timeProvider.GetUtcNow());
rollout.AddMetadata("modelId", response.ModelId ?? string.Empty);
if (!string.IsNullOrEmpty(response.ResponseId))
{
rollout.AddMetadata("responseId", response.ResponseId);
}
var reward = _options.RewardEvaluator(response);
var triplet = BuildTriplet(prompt, response, reward);
rollout.Complete(_timeProvider.GetUtcNow());
await InvokeHooksAsync(
h => h.OnRolloutEndAsync(context, new ReadOnlyCollection<object>(new object[] { response }), cancellationToken),
cancellationToken).ConfigureAwait(false);
await InvokeHooksAsync(h => h.OnTraceEndAsync(context, cancellationToken), cancellationToken).ConfigureAwait(false);
return new LightningExecutionResult(rollout, attempt, response, triplet);
}
catch (OperationCanceledException)
{
attempt.UpdateStatus(AttemptStatus.Timeout, _timeProvider.GetUtcNow());
rollout.TransitionTo(RolloutStatus.Cancelled);
await InvokeHooksAsync(h => h.OnTraceEndAsync(context, cancellationToken), cancellationToken).ConfigureAwait(false);
throw;
}
catch (Exception ex)
{
_logger.LogError(ex, "Agent {AgentName} failed to execute rollout {RolloutId}.", _options.AgentName, rolloutId);
attempt.UpdateStatus(AttemptStatus.Failed, _timeProvider.GetUtcNow());
rollout.TransitionTo(RolloutStatus.Failed);
await InvokeHooksAsync(
h => h.OnRolloutEndAsync(context, Array.Empty<object>(), cancellationToken),
cancellationToken).ConfigureAwait(false);
await InvokeHooksAsync(h => h.OnTraceEndAsync(context, cancellationToken), cancellationToken).ConfigureAwait(false);
throw;
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_chatClient.Dispose();
_disposed = true;
GC.SuppressFinalize(this);
}
private static Triplet BuildTriplet(IEnumerable<ChatMessage> prompt, ChatResponse response, double? reward)
{
var promptSnapshot = prompt
.Select(
message => new
{
message.Role,
Text = message.Text,
message.AuthorName,
})
.ToArray();
var metadata = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase)
{
["conversationId"] = response.ConversationId,
["finishReason"] = response.FinishReason?.ToString(),
["responseId"] = response.ResponseId,
};
if (response.CreatedAt is { } createdAt)
{
metadata["createdAt"] = createdAt;
}
if (response.ModelId is { Length: > 0 } modelId)
{
metadata["modelId"] = modelId;
}
return new Triplet
{
Prompt = promptSnapshot,
Response = response.Text,
Reward = reward,
Metadata = new ReadOnlyDictionary<string, object?>(metadata),
};
}
private async Task InvokeHooksAsync(Func<Hook, ValueTask> callback, CancellationToken cancellationToken)
{
foreach (var hook in _hooks)
{
cancellationToken.ThrowIfCancellationRequested();
await callback(hook).ConfigureAwait(false);
}
}
private string GenerateRolloutId(object taskInput)
{
static string Sanitize(string value)
{
var cleaned = new string(value.Where(char.IsLetterOrDigit).Take(12).ToArray());
return string.IsNullOrEmpty(cleaned) ? "input" : cleaned;
}
var suffix = taskInput switch
{
string text => Sanitize(text),
_ => Math.Abs(taskInput.GetHashCode()).ToString("X"),
};
return $"{_options.AgentName}-{Guid.NewGuid():N}-{suffix}";
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(LightningAgent));
}
}
}