-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
299 lines (274 loc) · 11.6 KB
/
Copy pathProgram.cs
File metadata and controls
299 lines (274 loc) · 11.6 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
#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.Extensions.AI;
using Microsoft.Agents.AI;
using MongoDB.AgentFramework;
using MongoDB.Bson;
using MongoDB.Driver;
// This slice does not implement Vector Search or Search index provisioning (see
// docs/development/rag/dotnet-rag-vector-search.md and docs/development/rag/dotnet-rag-full-text-search.md), so
// the target collection and indexes must already exist. Set MONGODB_RAG_VECTOR_INDEX to a Vector Search index
// (3-dimension, cosine) defined over the "embedding" field of the target collection before running this sample.
// Set MONGODB_RAG_SEARCH_INDEX to a Search index defined over the "text" field to also see the FullText and
// HybridRrf demos; those sections are skipped when the variable is unset since this sample cannot provision the
// index itself. HybridRrf additionally requires a MongoDB 8.0+ deployment ($rankFusion support).
string uri = Environment.GetEnvironmentVariable("MONGODB_URI")
?? throw new InvalidOperationException("Set MONGODB_URI.");
string databaseName = Environment.GetEnvironmentVariable("MONGODB_DATABASE")
?? throw new InvalidOperationException("Set MONGODB_DATABASE.");
string collectionName = Environment.GetEnvironmentVariable("MONGODB_RAG_COLLECTION")
?? "agent_framework_rag_chunks";
string vectorIndexName = Environment.GetEnvironmentVariable("MONGODB_RAG_VECTOR_INDEX")
?? "agent_framework_rag_vector";
string? searchIndexName = Environment.GetEnvironmentVariable("MONGODB_RAG_SEARCH_INDEX");
using var client = new MongoClient(uri);
IMongoCollection<BsonDocument> collection = client
.GetDatabase(databaseName)
.GetCollection<BsonDocument>(collectionName);
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator = new SampleEmbeddingGenerator();
await SeedKnowledgeAsync(collection);
var options = new MongoDBRAGProviderOptions
{
SearchMode = MongoDBSearchMode.VectorAnn,
VectorIndexName = vectorIndexName,
TopK = 3,
MandatoryFilter = MongoDBRAGFilter.Equal("tenant_id", "quickstart"),
};
await using var ragProvider = new MongoDBRAGProvider(
client,
databaseName,
collectionName,
embeddingGenerator,
vectorDimensions: 3,
options);
Console.WriteLine("Direct SearchAsync results:");
IReadOnlyList<MongoDBRAGResult> results = await ragProvider.SearchAsync("What color do widgets ship in?");
foreach (MongoDBRAGResult result in results)
{
Console.WriteLine($" [{result.Score:F3}] {result.Text} (source: {result.SourceName ?? "n/a"})");
}
Console.WriteLine();
Console.WriteLine("MongoDBRAGContextProvider before-invoke context:");
var contextProvider = new MongoDBRAGContextProvider(ragProvider);
AIContext context = await contextProvider.InvokingAsync(
new AIContextProvider.InvokingContext(
new SampleAgent(),
null,
new AIContext
{
Messages = [new ChatMessage(ChatRole.User, "What color do widgets ship in?")],
}),
default);
Console.WriteLine($" Instructions: {context.Instructions}");
foreach (ChatMessage message in context.Messages ?? [])
{
if (message.AdditionalProperties?.ContainsKey("_rag_id") is true)
{
Console.WriteLine($" [{message.Role}] {message.Text}");
}
}
if (searchIndexName is not null)
{
Console.WriteLine();
Console.WriteLine("FullText SearchAsync results (no embedding generator invoked):");
var fullTextOptions = new MongoDBRAGProviderOptions
{
SearchMode = MongoDBSearchMode.FullText,
SearchIndexName = searchIndexName,
SearchTextFieldNames = ["text"],
TopK = 3,
MandatoryFilter = MongoDBRAGFilter.Equal("tenant_id", "quickstart"),
};
await using var fullTextProvider = new MongoDBRAGProvider(
client,
databaseName,
collectionName,
fullTextOptions);
// Atlas Search indexes newly (re-)seeded documents asynchronously, so an immediate query can race the
// index and miss "quickstart-chunk-1" even though SeedKnowledgeAsync already completed. Poll boundedly
// until it is searchable so this sample's output is deterministic; production SearchAsync never polls.
IReadOnlyList<MongoDBRAGResult> fullTextResults;
try
{
fullTextResults = await PollUntilSearchableAsync(
fullTextProvider,
"What color do widgets ship in?",
"quickstart-chunk-1",
timeout: TimeSpan.FromSeconds(30),
pollInterval: TimeSpan.FromSeconds(1));
}
catch (TimeoutException ex)
{
Console.WriteLine($" {ex.Message}");
fullTextResults = [];
}
foreach (MongoDBRAGResult result in fullTextResults)
{
Console.WriteLine($" [{result.Score:F3}] {result.Text} (source: {result.SourceName ?? "n/a"})");
}
Console.WriteLine();
Console.WriteLine("HybridRrf SearchAsync results (native $rankFusion over both indexes):");
var hybridOptions = new MongoDBRAGProviderOptions
{
SearchMode = MongoDBSearchMode.HybridRrf,
VectorIndexName = vectorIndexName,
SearchIndexName = searchIndexName,
SearchTextFieldNames = ["text"],
TopK = 3,
MandatoryFilter = MongoDBRAGFilter.Equal("tenant_id", "quickstart"),
};
await using var hybridProvider = new MongoDBRAGProvider(
client,
databaseName,
collectionName,
embeddingGenerator,
vectorDimensions: 3,
hybridOptions);
// Same rationale as the FullText demo above: poll boundedly so newly (re-)seeded documents are guaranteed
// searchable through both of Hybrid's input branches before this sample prints its output.
IReadOnlyList<MongoDBRAGResult> hybridResults;
try
{
hybridResults = await PollUntilSearchableAsync(
hybridProvider,
"What color do widgets ship in?",
"quickstart-chunk-1",
timeout: TimeSpan.FromSeconds(30),
pollInterval: TimeSpan.FromSeconds(1));
}
catch (TimeoutException ex)
{
Console.WriteLine($" {ex.Message}");
hybridResults = [];
}
foreach (MongoDBRAGResult result in hybridResults)
{
Console.WriteLine($" [{result.Score:F3}] {result.Text} (source: {result.SourceName ?? "n/a"})");
}
}
else
{
Console.WriteLine();
Console.WriteLine("Skipping FullText and HybridRrf demos: set MONGODB_RAG_SEARCH_INDEX to a Search index " +
"over the \"text\" field to see them.");
}
/// <summary>
/// Bounded polling that repeatedly invokes <see cref="MongoDBRAGProvider.SearchAsync(string, CancellationToken)"/>
/// until <paramref name="expectedId"/> appears in its results or <paramref name="timeout"/> elapses. This exists
/// only to make this sample's FullText output deterministic across an Atlas Search index's asynchronous indexing
/// lag; it is not part of the production <see cref="MongoDBRAGProvider"/> contract, which never polls on a
/// caller's behalf. Cancellation always propagates as a clear <see cref="TimeoutException"/> rather than a bare
/// <see cref="OperationCanceledException"/>.
/// </summary>
static async Task<IReadOnlyList<MongoDBRAGResult>> PollUntilSearchableAsync(
MongoDBRAGProvider provider,
string query,
string expectedId,
TimeSpan timeout,
TimeSpan pollInterval)
{
using var cts = new CancellationTokenSource(timeout);
try
{
while (true)
{
IReadOnlyList<MongoDBRAGResult> results = await provider.SearchAsync(query, cts.Token);
if (results.Any(result => result.Id == expectedId))
{
return results;
}
await Task.Delay(pollInterval, cts.Token);
}
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
throw new TimeoutException(
$"Timed out after {timeout} waiting for document '{expectedId}' to become searchable for query " +
$"'{query}'. This indicates Atlas Search indexing lag exceeded the bounded poll window, not a " +
"MongoDBRAGProvider defect.");
}
}
static async Task SeedKnowledgeAsync(IMongoCollection<BsonDocument> collection)
{
var documents = new[]
{
new BsonDocument
{
{ "_id", "quickstart-chunk-1" },
{ "text", "Widgets ship in blue by default." },
{ "embedding", new BsonArray([1.0, 0.0, 0.0]) },
{ "tenant_id", "quickstart" },
{ "source", new BsonDocument { { "name", "Catalog" }, { "url", "https://example.test/catalog" } } },
},
new BsonDocument
{
{ "_id", "quickstart-chunk-2" },
{ "text", "Gadgets ship in red by default." },
{ "embedding", new BsonArray([0.0, 1.0, 0.0]) },
{ "tenant_id", "quickstart" },
{ "source", new BsonDocument { { "name", "Catalog" }, { "url", "https://example.test/catalog" } } },
},
};
foreach (BsonDocument document in documents)
{
await collection.ReplaceOneAsync(
Builders<BsonDocument>.Filter.Eq("_id", document["_id"]),
document,
new ReplaceOptions { IsUpsert = true });
}
}
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>(
// Correlate on the subject the query and the seeded documents actually share ("widget" vs.
// "gadget"), not an incidental detail like a color mentioned in the answer but not the question --
// otherwise a query like "What color do widgets ship in?" would embed to the same vector as the
// unrelated gadget document and retrieve the wrong chunk.
value.Contains("widget", StringComparison.OrdinalIgnoreCase)
? new float[] { 1, 0, 0 }
: new float[] { 0, 1, 0 }))));
}
public object? GetService(Type serviceType, object? serviceKey = null) => null;
public void Dispose()
{
}
}
sealed class SampleAgent : AIAgent
{
protected override ValueTask<AgentSession> CreateSessionCoreAsync(
CancellationToken cancellationToken) =>
throw new NotSupportedException();
protected override ValueTask<JsonElement> SerializeSessionCoreAsync(
AgentSession session,
JsonSerializerOptions? jsonSerializerOptions,
CancellationToken cancellationToken) =>
throw new NotSupportedException();
protected override ValueTask<AgentSession> DeserializeSessionCoreAsync(
JsonElement serializedSession,
JsonSerializerOptions? jsonSerializerOptions,
CancellationToken cancellationToken) =>
throw new NotSupportedException();
protected override Task<AgentResponse> RunCoreAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session,
AgentRunOptions? options,
CancellationToken cancellationToken) =>
throw new NotSupportedException();
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session,
AgentRunOptions? options,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
await Task.CompletedTask;
yield break;
}
}