Skip to content

Commit baa2d9e

Browse files
committed
cleanup: dotnet format to fix whitespace issues
1 parent 3cb8be0 commit baa2d9e

File tree

10 files changed

+154
-152
lines changed

10 files changed

+154
-152
lines changed

samples/AspireDemo/AspireHost/Program.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,18 @@
1111
options.AddFilter("Aspire.Hosting.ApplicationModel", LogLevel.Information);
1212
options.AddFilter("Aspire.Hosting", LogLevel.Information);
1313
options.AddFilter("Aspire", LogLevel.Warning);
14-
14+
1515
// Reduce OpenTelemetry noise
1616
options.AddFilter("OpenTelemetry", LogLevel.Warning);
17-
17+
1818
// Keep basic hosting messages
1919
options.AddFilter("Microsoft.Extensions.Hosting.Internal.Host", LogLevel.Information);
2020
options.AddFilter("Microsoft.Extensions.Hosting", LogLevel.Warning);
21-
21+
2222
// Reduce ASP.NET Core noise but keep startup messages
2323
options.AddFilter("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Information);
2424
options.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
25-
25+
2626
// Reduce DI and HTTP noise
2727
options.AddFilter("Microsoft.Extensions.DependencyInjection", LogLevel.Warning);
2828
options.AddFilter("System.Net.Http", LogLevel.Warning);

samples/AspireDemo/NLWebNet.AspireApp/Program.cs

Lines changed: 59 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,9 @@
5959
.WithName("GetHealth")
6060
.WithOpenApi();
6161

62-
app.MapGet("/api/health", () => Results.Ok(new {
63-
Status = "Healthy",
62+
app.MapGet("/api/health", () => Results.Ok(new
63+
{
64+
Status = "Healthy",
6465
Timestamp = DateTimeOffset.UtcNow,
6566
Service = "NLWebNet AspireApp API"
6667
}))
@@ -88,7 +89,7 @@
8889
{
8990
// Extract GitHub token from headers if provided for consistent embedding
9091
var githubToken = context.Request.Headers["X-GitHub-Token"].FirstOrDefault();
91-
92+
9293
var count = await ingestionService.IngestDemoFeedsAsync(githubToken);
9394
return Results.Ok(new { Message = $"Successfully ingested {count} documents from demo feeds", Count = count });
9495
}
@@ -106,10 +107,11 @@
106107
{
107108
new { Name = "Microsoft .NET Blog", Url = "https://devblogs.microsoft.com/dotnet/feed/", Note = "Latest 25 articles" }
108109
};
109-
110-
return Results.Ok(new {
110+
111+
return Results.Ok(new
112+
{
111113
Message = "Demo RSS feed used for focused ingestion (latest 25 articles from .NET blog)",
112-
Feeds = demoFeeds
114+
Feeds = demoFeeds
113115
});
114116
})
115117
.WithName("GetDemoFeeds")
@@ -137,12 +139,12 @@
137139
{
138140
using var activity = System.Diagnostics.Activity.Current?.Source.StartActivity("VectorSearch.SearchDocuments");
139141
var correlationId = Guid.NewGuid().ToString("N")[..8];
140-
142+
141143
activity?.SetTag("search.correlation_id", correlationId);
142144
activity?.SetTag("search.query", query);
143145
activity?.SetTag("search.limit", limit);
144146
activity?.SetTag("search.threshold", threshold);
145-
147+
146148
try
147149
{
148150
if (string.IsNullOrWhiteSpace(query))
@@ -153,56 +155,56 @@
153155
}
154156

155157
var searchLimit = limit ?? 10;
156-
158+
157159
// Extract GitHub token from headers if provided
158160
var githubToken = context.Request.Headers["X-GitHub-Token"].FirstOrDefault();
159161
var hasToken = !string.IsNullOrEmpty(githubToken);
160-
162+
161163
// Adjust threshold based on embedding type
162164
var searchThreshold = threshold ?? (hasToken && IsValidGitHubToken(githubToken) ? 0.1f : 0.03f);
163-
165+
164166
logger.LogInformation("=== SEARCH REQUEST START [{CorrelationId}] ===", correlationId);
165-
logger.LogInformation("[{CorrelationId}] Search parameters - Query: '{Query}', Limit: {Limit}, Threshold: {Threshold}, HasToken: {HasToken}, TokenLength: {TokenLength}",
167+
logger.LogInformation("[{CorrelationId}] Search parameters - Query: '{Query}', Limit: {Limit}, Threshold: {Threshold}, HasToken: {HasToken}, TokenLength: {TokenLength}",
166168
correlationId, query, searchLimit, searchThreshold, hasToken, githubToken?.Length ?? 0);
167-
169+
168170
activity?.SetTag("auth.has_token", hasToken);
169171
activity?.SetTag("auth.token_length", githubToken?.Length ?? 0);
170172
activity?.SetTag("search.processed_limit", searchLimit);
171173
activity?.SetTag("search.processed_threshold", searchThreshold);
172-
174+
173175
// Generate embedding for the search query
174176
logger.LogInformation("[{CorrelationId}] Generating query embedding...", correlationId);
175177
var embeddingStopwatch = System.Diagnostics.Stopwatch.StartNew();
176-
178+
177179
var queryEmbedding = await embeddingService.GenerateEmbeddingAsync(query, githubToken);
178-
180+
179181
embeddingStopwatch.Stop();
180-
logger.LogInformation("[{CorrelationId}] Query embedding generated - Duration: {Duration}ms, Dimensions: {Dimensions}, EmbeddingType: {EmbeddingType}",
182+
logger.LogInformation("[{CorrelationId}] Query embedding generated - Duration: {Duration}ms, Dimensions: {Dimensions}, EmbeddingType: {EmbeddingType}",
181183
correlationId, embeddingStopwatch.ElapsedMilliseconds, queryEmbedding.Length, hasToken ? "GitHub Models" : "Simple Hash");
182-
184+
183185
activity?.SetTag("embedding.duration_ms", embeddingStopwatch.ElapsedMilliseconds);
184186
activity?.SetTag("embedding.dimensions", queryEmbedding.Length);
185187
activity?.SetTag("embedding.type", hasToken ? "github_models" : "simple_hash");
186-
188+
187189
// Search for similar documents
188190
logger.LogInformation("[{CorrelationId}] Performing vector similarity search...", correlationId);
189191
var searchStopwatch = System.Diagnostics.Stopwatch.StartNew();
190-
192+
191193
var results = await vectorStorage.SearchSimilarAsync(queryEmbedding, searchLimit, searchThreshold);
192-
194+
193195
searchStopwatch.Stop();
194196
var rawResultCount = results.Count();
195-
196-
logger.LogInformation("[{CorrelationId}] Vector search completed - Duration: {Duration}ms, RawResults: {RawResultCount}",
197+
198+
logger.LogInformation("[{CorrelationId}] Vector search completed - Duration: {Duration}ms, RawResults: {RawResultCount}",
197199
correlationId, searchStopwatch.ElapsedMilliseconds, rawResultCount);
198-
200+
199201
activity?.SetTag("vector_search.duration_ms", searchStopwatch.ElapsedMilliseconds);
200202
activity?.SetTag("vector_search.raw_result_count", rawResultCount);
201-
203+
202204
// Process and format results
203205
logger.LogInformation("[{CorrelationId}] Processing search results...", correlationId);
204206
var processingStopwatch = System.Diagnostics.Stopwatch.StartNew();
205-
207+
206208
var searchResults = results.Select(r => new
207209
{
208210
Id = r.Document.Id,
@@ -212,53 +214,53 @@
212214
PublishedDate = r.Document.IngestedAt,
213215
Similarity = Math.Max(0.0, Math.Min(1.0, r.Score))
214216
}).ToList();
215-
217+
216218
processingStopwatch.Stop();
217-
219+
218220
// Log result statistics
219221
if (searchResults.Any())
220222
{
221223
var avgSimilarity = searchResults.Average(r => r.Similarity);
222224
var maxSimilarity = searchResults.Max(r => r.Similarity);
223225
var minSimilarity = searchResults.Min(r => r.Similarity);
224-
225-
logger.LogInformation("[{CorrelationId}] Result statistics - Count: {Count}, AvgSimilarity: {AvgSimilarity:F3}, MaxSimilarity: {MaxSimilarity:F3}, MinSimilarity: {MinSimilarity:F3}",
226+
227+
logger.LogInformation("[{CorrelationId}] Result statistics - Count: {Count}, AvgSimilarity: {AvgSimilarity:F3}, MaxSimilarity: {MaxSimilarity:F3}, MinSimilarity: {MinSimilarity:F3}",
226228
correlationId, searchResults.Count, avgSimilarity, maxSimilarity, minSimilarity);
227-
228-
logger.LogInformation("[{CorrelationId}] Top result - Title: '{Title}', Similarity: {Similarity:F3}",
229+
230+
logger.LogInformation("[{CorrelationId}] Top result - Title: '{Title}', Similarity: {Similarity:F3}",
229231
correlationId, searchResults[0].Title, searchResults[0].Similarity);
230-
232+
231233
activity?.SetTag("results.count", searchResults.Count);
232234
activity?.SetTag("results.avg_similarity", avgSimilarity);
233235
activity?.SetTag("results.max_similarity", maxSimilarity);
234236
activity?.SetTag("results.min_similarity", minSimilarity);
235237
}
236238
else
237239
{
238-
logger.LogWarning("[{CorrelationId}] No results found for query '{Query}' with threshold {Threshold}",
240+
logger.LogWarning("[{CorrelationId}] No results found for query '{Query}' with threshold {Threshold}",
239241
correlationId, query, searchThreshold);
240242
activity?.SetTag("results.count", 0);
241243
}
242244

243245
var totalDuration = embeddingStopwatch.ElapsedMilliseconds + searchStopwatch.ElapsedMilliseconds + processingStopwatch.ElapsedMilliseconds;
244-
245-
logger.LogInformation("=== SEARCH REQUEST SUCCESS [{CorrelationId}] === Total duration: {TotalDuration}ms, Results: {ResultCount}, EmbeddingType: {EmbeddingType}",
246+
247+
logger.LogInformation("=== SEARCH REQUEST SUCCESS [{CorrelationId}] === Total duration: {TotalDuration}ms, Results: {ResultCount}, EmbeddingType: {EmbeddingType}",
246248
correlationId, totalDuration, searchResults.Count, hasToken ? "GitHub Models" : "Simple Hash");
247-
249+
248250
activity?.SetTag("search.success", true);
249251
activity?.SetTag("search.total_duration_ms", totalDuration);
250-
252+
251253
return Results.Ok(searchResults);
252254
}
253255
catch (Exception ex)
254256
{
255257
logger.LogError(ex, "=== SEARCH REQUEST FAILED [{CorrelationId}] === Query: '{Query}', Error: {Message}", correlationId, query, ex.Message);
256-
258+
257259
activity?.SetTag("search.success", false);
258260
activity?.SetTag("error.type", ex.GetType().Name);
259261
activity?.SetTag("error.message", ex.Message);
260262
activity?.SetTag("error.stack_trace", ex.StackTrace);
261-
263+
262264
return Results.BadRequest(new { Error = ex.Message });
263265
}
264266
})
@@ -272,11 +274,11 @@
272274
{
273275
var githubToken = context.Request.Headers["X-GitHub-Token"].FirstOrDefault();
274276
var hasToken = !string.IsNullOrEmpty(githubToken) && IsValidGitHubToken(githubToken);
275-
277+
276278
logger.LogInformation("Generating embedding for diagnostic - Text: '{Text}', HasToken: {HasToken}", text, hasToken);
277-
279+
278280
var embedding = await embeddingService.GenerateEmbeddingAsync(text, githubToken);
279-
281+
280282
var stats = new
281283
{
282284
Text = text,
@@ -294,7 +296,7 @@
294296
NonZeroCount = embedding.Span.ToArray().Count(x => Math.Abs(x) > 0.001f)
295297
}
296298
};
297-
299+
298300
return Results.Ok(stats);
299301
}
300302
catch (Exception ex)
@@ -314,16 +316,16 @@
314316
var searchLimit = limit ?? 10;
315317
var githubToken = context.Request.Headers["X-GitHub-Token"].FirstOrDefault();
316318
var hasToken = !string.IsNullOrEmpty(githubToken) && IsValidGitHubToken(githubToken);
317-
319+
318320
logger.LogInformation("=== DIAGNOSTIC SEARCH ===");
319321
logger.LogInformation("Query: '{Query}', HasToken: {HasToken}", query, hasToken);
320-
322+
321323
// Generate query embedding
322324
var queryEmbedding = await embeddingService.GenerateEmbeddingAsync(query, githubToken);
323-
325+
324326
// Get raw search results with very low threshold
325327
var results = await vectorStorage.SearchSimilarAsync(queryEmbedding, searchLimit, 0.0f);
326-
328+
327329
var diagnosticResults = results.Select((r, index) => new
328330
{
329331
Rank = index + 1,
@@ -337,7 +339,7 @@
337339
TitleMatch = r.Document.Title?.Contains(query, StringComparison.OrdinalIgnoreCase) == true,
338340
DescriptionMatch = r.Document.Description?.Contains(query, StringComparison.OrdinalIgnoreCase) == true
339341
}).ToList();
340-
342+
341343
var analysis = new
342344
{
343345
Query = query,
@@ -355,10 +357,10 @@
355357
LowestSimilarity = diagnosticResults.LastOrDefault()?.Similarity ?? 0,
356358
Results = diagnosticResults
357359
};
358-
359-
logger.LogInformation("Diagnostic complete - {ResultCount} results, {TextMatches} contain query term",
360+
361+
logger.LogInformation("Diagnostic complete - {ResultCount} results, {TextMatches} contain query term",
360362
diagnosticResults.Count, diagnosticResults.Count(r => r.ContainsQueryTerm));
361-
363+
362364
return Results.Ok(analysis);
363365
}
364366
catch (Exception ex)
@@ -377,7 +379,7 @@
377379
{
378380
var searchLimit = limit ?? 50;
379381
var documents = await vectorStorage.GetAllDocumentsAsync(searchLimit);
380-
382+
381383
var results = documents.Select(doc => new
382384
{
383385
Id = doc.Id,
@@ -388,13 +390,13 @@
388390
TitleMatch = !string.IsNullOrEmpty(search) && doc.Title.Contains(search, StringComparison.OrdinalIgnoreCase),
389391
DescriptionMatch = !string.IsNullOrEmpty(search) && !string.IsNullOrEmpty(doc.Description) && doc.Description.Contains(search, StringComparison.OrdinalIgnoreCase)
390392
}).ToList();
391-
393+
392394
if (!string.IsNullOrEmpty(search))
393395
{
394396
// Filter to only documents that contain the search term
395397
results = results.Where(r => r.TitleMatch || r.DescriptionMatch).ToList();
396398
}
397-
399+
398400
return Results.Ok(new
399401
{
400402
TotalDocuments = documents.Count(),
@@ -438,7 +440,7 @@
438440
// Try with the actual token from headers
439441
var githubToken = context.Request.Headers["X-GitHub-Token"].FirstOrDefault();
440442
ReadOnlyMemory<float>? realGithubEmbedding = null;
441-
443+
442444
if (!string.IsNullOrEmpty(githubToken))
443445
{
444446
try
@@ -489,7 +491,7 @@
489491
// Helper method for GitHub token validation
490492
static bool IsValidGitHubToken(string? token)
491493
{
492-
return !string.IsNullOrWhiteSpace(token) &&
494+
return !string.IsNullOrWhiteSpace(token) &&
493495
(token.StartsWith("gho_") || token.StartsWith("ghp_") || token.StartsWith("github_pat_")) &&
494496
token.Length > 20;
495497
}

samples/AspireDemo/NLWebNet.AspireApp/Services/CompositeEmbeddingService.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public CompositeEmbeddingService(
1818
{
1919
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
2020
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
21-
21+
2222
// Always create simple embedding service as fallback
2323
var simpleLogger = _serviceProvider.GetRequiredService<ILogger<SimpleEmbeddingService>>();
2424
_simpleEmbeddingService = new SimpleEmbeddingService(simpleLogger);
@@ -37,10 +37,10 @@ public async Task<ReadOnlyMemory<float>> GenerateEmbeddingAsync(string text, str
3737
try
3838
{
3939
_logger.LogDebug("Attempting to use GitHub Models embedding service with provided token");
40-
40+
4141
var githubService = CreateGitHubModelsService(githubToken);
4242
var result = await githubService.GenerateEmbeddingAsync(text, githubToken, cancellationToken);
43-
43+
4444
_logger.LogDebug("Successfully generated embedding using GitHub Models");
4545
return result;
4646
}
@@ -63,14 +63,14 @@ private GitHubModelsEmbeddingService CreateGitHubModelsService(string githubToke
6363
{
6464
var httpClientFactory = _serviceProvider.GetRequiredService<IHttpClientFactory>();
6565
var httpClient = httpClientFactory.CreateClient("GitHubModels");
66-
66+
6767
// Configure the HttpClient for this request
6868
httpClient.BaseAddress = new Uri("https://models.inference.ai.azure.com/");
69-
httpClient.DefaultRequestHeaders.Authorization =
69+
httpClient.DefaultRequestHeaders.Authorization =
7070
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", githubToken);
7171
httpClient.DefaultRequestHeaders.Add("User-Agent", "NLWebNet-AspireDemo");
7272
httpClient.Timeout = TimeSpan.FromSeconds(30);
73-
73+
7474
var logger = _serviceProvider.GetRequiredService<ILogger<GitHubModelsEmbeddingService>>();
7575
return new GitHubModelsEmbeddingService(httpClient, "text-embedding-3-small", logger);
7676
}
@@ -79,7 +79,7 @@ private static bool IsValidGitHubToken(string token)
7979
{
8080
// Basic validation for GitHub token format
8181
// Real tokens start with 'gho_', 'ghp_', or 'github_pat_'
82-
return !string.IsNullOrWhiteSpace(token) &&
82+
return !string.IsNullOrWhiteSpace(token) &&
8383
(token.StartsWith("gho_") || token.StartsWith("ghp_") || token.StartsWith("github_pat_")) &&
8484
token.Length > 20; // GitHub tokens are typically much longer
8585
}

0 commit comments

Comments
 (0)