-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
318 lines (281 loc) · 11.2 KB
/
Copy pathProgram.cs
File metadata and controls
318 lines (281 loc) · 11.2 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
#pragma warning disable MAAI001 // AIContextProvider is an evaluation-purposes-only API in this package version.
using System.Runtime.CompilerServices;
using System.Text.Json;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using MongoDB.AgentFramework;
using MongoDB.Bson;
using MongoDB.Driver;
MemoryAndRagOptions command = MemoryAndRagOptions.Parse(args);
MemoryAndRagSettings settings = MemoryAndRagSettings.Load();
var embeddingGenerator = new SampleEmbeddingGenerator();
var retrievalScope = new MongoDBMemoryScope(
applicationId: "memory-rag-sample",
userId: settings.MemoryUserId);
MongoDBMemoryScope storageScope = retrievalScope.WithSession(settings.MemorySessionId);
await using var memoryProvider = new MongoDBMemoryProvider(
settings.ConnectionString,
settings.DatabaseName,
settings.MemoryCollectionName,
embeddingGenerator,
vectorDimensions: 3,
_ => new MongoDBMemoryProvider.State(retrievalScope, storageScope),
options: new MongoDBMemoryProviderOptions
{
MaxResults = 3,
NumCandidates = 30,
PersistenceFailFast = true,
});
var ragOptions = new MongoDBRAGProviderOptions
{
SearchMode = MongoDBSearchMode.VectorAnn,
VectorIndexName = settings.RagVectorIndexName,
TopK = 3,
MandatoryFilter = MongoDBRAGFilter.Equal("tenant_id", settings.RagTenantId),
};
await using var ragProvider = new MongoDBRAGProvider(
settings.ConnectionString,
settings.DatabaseName,
settings.RagCollectionName,
embeddingGenerator,
vectorDimensions: 3,
ragOptions);
using var client = new MongoClient(settings.ConnectionString);
IMongoCollection<BsonDocument> ragCollection = client
.GetDatabase(settings.DatabaseName)
.GetCollection<BsonDocument>(settings.RagCollectionName);
var ragVectorDefinition = new MongoDBVectorSearchIndexDefinition(
settings.RagVectorIndexName,
vectorFieldName: "embedding",
vectorDimensions: 3,
similarity: "cosine",
filterFieldPaths: ["tenant_id"]);
await using var ragIndexManager = new MongoDBRAGIndexManager(ragCollection, ragVectorDefinition);
var ragContextProvider = new MongoDBRAGContextProvider(ragProvider);
var agent = new FixtureAgent(memoryProvider, ragContextProvider);
if (command.ValidateOnly)
{
Console.WriteLine("Validated Memory plus RAG configuration.");
return;
}
long cleaned = 0;
try
{
await memoryProvider.ValidateVectorSearchIndexAsync();
await ragIndexManager.ValidateVectorSearchIndexAsync();
int seeded = await memoryProvider.StoreAsync(
[
new ChatMessage(
ChatRole.User,
"A prior conversation established that approvals require tenant-scoped access controls.")
],
storageScope);
Console.WriteLine($"Seeded {seeded} scoped memory message(s).");
AgentResponse response = await agent.RunAsync(
"What do prior context and authoritative sources say about access?",
session: null,
options: null,
cancellationToken: default);
Console.WriteLine(response.Text);
}
finally
{
if (!command.KeepMemory)
{
cleaned = await memoryProvider.ClearSessionAsync(settings.MemorySessionId, retrievalScope);
Console.WriteLine($"Cleared {cleaned} memory record(s) from session '{settings.MemorySessionId}'.");
}
}
internal sealed record MemoryAndRagOptions(bool ValidateOnly, bool KeepMemory)
{
public static MemoryAndRagOptions Parse(string[] args)
{
bool validateOnly = false;
bool keepMemory = false;
foreach (string arg in args)
{
switch (arg)
{
case "--validate-only":
validateOnly = true;
break;
case "--keep":
keepMemory = true;
break;
default:
throw new ArgumentException("Usage: dotnet run --project ... -- [--validate-only] [--keep]");
}
}
return new(validateOnly, keepMemory);
}
}
internal sealed record MemoryAndRagSettings(
string ConnectionString,
string DatabaseName,
string MemoryCollectionName,
string MemoryUserId,
string MemorySessionId,
string RagCollectionName,
string RagVectorIndexName,
string RagTenantId)
{
public static MemoryAndRagSettings Load() =>
new(
Required("MONGODB_URI"),
Required("MONGODB_DATABASE"),
Required("MONGODB_MEMORY_COLLECTION"),
Required("MONGODB_MEMORY_USER_ID"),
Required("MONGODB_MEMORY_SESSION_ID"),
Required("MONGODB_RAG_COLLECTION"),
Required("MONGODB_RAG_VECTOR_INDEX"),
Required("MONGODB_RAG_TENANT"));
private static string Required(string name)
{
string? value = Environment.GetEnvironmentVariable(name)?.Trim();
return !string.IsNullOrWhiteSpace(value)
? value
: throw new InvalidOperationException($"Set {name} before running Memory plus RAG.");
}
}
internal sealed class FixtureSession : AgentSession
{
public FixtureSession()
{
}
public FixtureSession(AgentSessionStateBag stateBag)
: base(stateBag)
{
}
}
internal sealed class FixtureAgent : AIAgent
{
private readonly MongoDBMemoryProvider _memoryProvider;
private readonly MongoDBRAGContextProvider _ragContextProvider;
public FixtureAgent(
MongoDBMemoryProvider memoryProvider,
MongoDBRAGContextProvider ragContextProvider)
{
_memoryProvider = memoryProvider;
_ragContextProvider = ragContextProvider;
}
protected override ValueTask<AgentSession> CreateSessionCoreAsync(CancellationToken cancellationToken) =>
ValueTask.FromResult<AgentSession>(new FixtureSession());
protected override ValueTask<JsonElement> SerializeSessionCoreAsync(
AgentSession session,
JsonSerializerOptions? jsonSerializerOptions,
CancellationToken cancellationToken) =>
ValueTask.FromResult(session.StateBag.Serialize());
protected override ValueTask<AgentSession> DeserializeSessionCoreAsync(
JsonElement serializedSession,
JsonSerializerOptions? jsonSerializerOptions,
CancellationToken cancellationToken) =>
ValueTask.FromResult<AgentSession>(new FixtureSession(AgentSessionStateBag.Deserialize(serializedSession)));
protected override async Task<AgentResponse> RunCoreAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session,
AgentRunOptions? options,
CancellationToken cancellationToken)
{
List<ChatMessage> requestMessages = messages.ToList();
var invokingContext = new AIContextProvider.InvokingContext(
this,
session,
new AIContext { Messages = requestMessages });
AIContext memoryContext = await _memoryProvider.InvokingAsync(invokingContext, cancellationToken);
AIContext ragContext = await _ragContextProvider.InvokingAsync(invokingContext, cancellationToken);
string memorySummary = FormatMemoryContext(memoryContext.Messages);
string ragSummary = FormatRagContext(ragContext.Messages);
if (memorySummary.Contains("no conversational memory", StringComparison.Ordinal))
{
throw new InvalidOperationException("The Memory provider returned no context for the seeded sample turn.");
}
if (ragSummary.Contains("no authoritative RAG context", StringComparison.Ordinal))
{
throw new InvalidOperationException(
"The RAG provider returned no context. Preload tenant-scoped vector-search documents before running " +
"Memory plus RAG.");
}
var response = new AgentResponse(
new ChatMessage(
ChatRole.Assistant,
$"Memory context: {memorySummary}{Environment.NewLine}RAG context: {ragSummary}"));
await _memoryProvider.InvokedAsync(
new AIContextProvider.InvokedContext(
this,
session,
requestMessages,
response.Messages),
cancellationToken);
return response;
}
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session,
AgentRunOptions? options,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
AgentResponse response = await RunCoreAsync(messages, session, options, cancellationToken);
foreach (AgentResponseUpdate update in response.ToAgentResponseUpdates())
{
yield return update;
}
}
private static string FormatMemoryContext(IEnumerable<ChatMessage>? messages)
{
List<string> recalled = (messages ?? [])
.Select(static message => message.Text)
.Where(static text => !string.IsNullOrWhiteSpace(text))
.ToList();
return recalled.Count == 0
? "no conversational memory"
: string.Join(" | ", recalled);
}
private static string FormatRagContext(IEnumerable<ChatMessage>? messages)
{
List<string> citations = (messages ?? [])
.Select(static message =>
{
string source = message.AdditionalProperties?.TryGetValue("_rag_source_name", out object? sourceName) == true &&
sourceName is string sourceNameText &&
!string.IsNullOrWhiteSpace(sourceNameText)
? sourceNameText
: message.AdditionalProperties?.TryGetValue("_rag_id", out object? id) == true
? Convert.ToString(id, System.Globalization.CultureInfo.InvariantCulture) ?? "unknown"
: "unknown";
return $"[{source}] {message.Text}";
})
.Where(static text => !string.IsNullOrWhiteSpace(text))
.ToList();
return citations.Count == 0
? "no authoritative RAG context"
: string.Join(" | ", citations);
}
}
internal sealed class SampleEmbeddingGenerator : IEmbeddingGenerator<string, Embedding<float>>
{
public Task<GeneratedEmbeddings<Embedding<float>>> GenerateAsync(
IEnumerable<string> values,
EmbeddingGenerationOptions? options = null,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(
new GeneratedEmbeddings<Embedding<float>>(
values.Select(static value => new Embedding<float>(ToVector(value)))));
}
public object? GetService(Type serviceType, object? serviceKey = null) => null;
public void Dispose()
{
}
private static float[] ToVector(string value)
{
string normalized = value.ToLowerInvariant();
return normalized.Contains("access", StringComparison.Ordinal) ||
normalized.Contains("tenant", StringComparison.Ordinal) ||
normalized.Contains("approval", StringComparison.Ordinal)
? [1.0f, 0.0f, 0.0f]
: normalized.Contains("memory", StringComparison.Ordinal)
? [0.0f, 1.0f, 0.0f]
: [0.0f, 0.0f, 1.0f];
}
}