-
Notifications
You must be signed in to change notification settings - Fork 8
feat: Update embedding logic to bulk #1037
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BenjaminMichaelis
wants to merge
3
commits into
main
Choose a base branch
from
bmichaelis/EmbeddingUpdates
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
142 changes: 122 additions & 20 deletions
142
EssentialCSharp.Chat.Shared/Services/EmbeddingService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,51 +1,153 @@ | ||
| using System.Text.RegularExpressions; | ||
| using EssentialCSharp.Chat.Common.Models; | ||
| using Microsoft.Extensions.AI; | ||
| using Microsoft.Extensions.VectorData; | ||
| using Npgsql; | ||
|
|
||
| namespace EssentialCSharp.Chat.Common.Services; | ||
|
|
||
| /// <summary> | ||
| /// Service for generating embeddings for markdown chunks using Azure OpenAI | ||
| /// Service for generating embeddings for markdown chunks using Azure OpenAI and uploading | ||
| /// them to a PostgreSQL vector store via a staging-then-swap pattern to avoid downtime. | ||
| /// </summary> | ||
| public class EmbeddingService(VectorStore vectorStore, IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator) | ||
| public class EmbeddingService( | ||
| VectorStore vectorStore, | ||
| IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator, | ||
| NpgsqlDataSource dataSource) | ||
| { | ||
| public static string CollectionName { get; } = "markdown_chunks"; | ||
|
|
||
| /// <summary> | ||
| /// Maximum number of inputs per Azure OpenAI embedding batch call. | ||
| /// </summary> | ||
| private const int EmbeddingBatchSize = 2048; | ||
|
|
||
| // Only allow simple identifiers: letters, digits, and underscores, starting with a letter or underscore. | ||
| private static readonly Regex _safeIdentifierRegex = new(@"^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled); | ||
|
|
||
| /// <summary> | ||
| /// Generate an embedding for the given text. | ||
| /// </summary> | ||
| /// <param name="text">The text to generate an embedding for.</param> | ||
| /// <param name="cancellationToken">The cancellation token.</param> | ||
| /// <returns>A search vector as ReadOnlyMemory<float>.</returns> | ||
| public async Task<ReadOnlyMemory<float>> GenerateEmbeddingAsync(string text, CancellationToken cancellationToken = default) | ||
| { | ||
| var embedding = await embeddingGenerator.GenerateAsync(text, cancellationToken: cancellationToken); | ||
| return embedding.Vector; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Generate an embedding for each text paragraph and upload it to the specified collection. | ||
| /// Generate embeddings for all chunks in batches and upload them to the vector store | ||
| /// using a staging-then-atomic-swap pattern so the live collection stays queryable | ||
| /// throughout the rebuild. | ||
| /// | ||
| /// Steps: | ||
| /// 1. Create a staging collection ({collectionName}_staging). | ||
| /// 2. Embed all chunks in batches of <see cref="EmbeddingBatchSize"/> (Azure OpenAI limit). | ||
| /// 3. Batch-upsert all chunks into staging. | ||
| /// 4. Atomically swap tables in a single transaction using two SQL RENAME operations | ||
| /// (live → old, staging → live). PostgreSQL ALTER TABLE acquires | ||
| /// AccessExclusiveLock automatically; no explicit LOCK TABLE is needed. The | ||
| /// transaction ensures no reader sees an intermediate state. | ||
| /// 5. Drop the old live backup table with DROP TABLE. | ||
| /// | ||
| /// If an error occurs before the swap, only the staging table is affected — the live | ||
| /// collection is untouched. | ||
| /// </summary> | ||
| /// <param name="collectionName">The name of the collection to upload the text paragraphs to.</param> | ||
| /// <returns>An async task.</returns> | ||
| public async Task GenerateBookContentEmbeddingsAndUploadToVectorStore(IEnumerable<BookContentChunk> bookContents, CancellationToken cancellationToken, string? collectionName = null) | ||
| public async Task GenerateBookContentEmbeddingsAndUploadToVectorStore( | ||
| IEnumerable<BookContentChunk> bookContents, | ||
| CancellationToken cancellationToken, | ||
| string? collectionName = null) | ||
| { | ||
| collectionName ??= CollectionName; | ||
|
|
||
| var collection = vectorStore.GetCollection<string, BookContentChunk>(collectionName); | ||
| await collection.EnsureCollectionDeletedAsync(cancellationToken); | ||
| await collection.EnsureCollectionExistsAsync(cancellationToken); | ||
| if (!_safeIdentifierRegex.IsMatch(collectionName)) | ||
| throw new ArgumentException( | ||
| $"Collection name '{collectionName}' contains unsafe characters. Use only letters, digits, and underscores.", | ||
| nameof(collectionName)); | ||
|
|
||
| string stagingName = $"{collectionName}_staging"; | ||
| string oldName = $"{collectionName}_old"; | ||
|
|
||
| // ── Step 1: Prepare staging collection ──────────────────────────────────────── | ||
| var staging = vectorStore.GetCollection<string, BookContentChunk>(stagingName); | ||
| await staging.EnsureCollectionDeletedAsync(cancellationToken); | ||
| await staging.EnsureCollectionExistsAsync(cancellationToken); | ||
|
|
||
| // ── Step 2: Batch-embed all chunks ──────────────────────────────────────────── | ||
| // Azure OpenAI supports at most EmbeddingBatchSize inputs per GenerateAsync call. | ||
| var chunkList = bookContents.ToList(); | ||
| var texts = chunkList.Select(c => c.ChunkText).ToList(); | ||
|
|
||
| int uploadedCount = 0; | ||
| var allEmbeddings = new List<Embedding<float>>(chunkList.Count); | ||
| foreach (var batch in texts.Chunk(EmbeddingBatchSize)) | ||
| { | ||
| var batchEmbeddings = await embeddingGenerator.GenerateAsync(batch, cancellationToken: cancellationToken); | ||
| allEmbeddings.AddRange(batchEmbeddings); | ||
| } | ||
|
|
||
| foreach (var chunk in bookContents) | ||
| if (allEmbeddings.Count != chunkList.Count) | ||
| throw new InvalidOperationException( | ||
| $"Embedding count mismatch: expected {chunkList.Count}, got {allEmbeddings.Count}."); | ||
|
|
||
| for (int i = 0; i < chunkList.Count; i++) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| chunk.TextEmbedding = await GenerateEmbeddingAsync(chunk.ChunkText, cancellationToken); | ||
| await collection.UpsertAsync(chunk, cancellationToken); | ||
| Console.WriteLine($"Uploaded chunk '{chunk.Id}' to collection '{collectionName}' for file '{chunk.FileName}' with heading '{chunk.Heading}'."); | ||
| uploadedCount++; | ||
| chunkList[i].TextEmbedding = allEmbeddings[i].Vector; | ||
| } | ||
| Console.WriteLine($"Successfully generated embeddings and uploaded {uploadedCount} chunks to collection '{collectionName}'."); | ||
|
|
||
| // ── Step 3: Batch-upsert all chunks into staging ────────────────────────────── | ||
| try | ||
| { | ||
| await staging.UpsertAsync(chunkList, cancellationToken); | ||
| Console.WriteLine($"Uploaded {chunkList.Count} chunks to staging collection '{stagingName}'."); | ||
| } | ||
| catch | ||
| { | ||
| // Best-effort cleanup: drop the partially-populated staging table so the | ||
| // next run starts clean. Do not let this secondary failure mask the original. | ||
| try | ||
| { | ||
| await staging.EnsureCollectionDeletedAsync(cancellationToken); | ||
| } | ||
| catch (Exception cleanupEx) when (cleanupEx is not OperationCanceledException) | ||
| { | ||
| Console.Error.WriteLine($"Warning: failed to clean up staging collection '{stagingName}' after upsert failure: {cleanupEx.Message}"); | ||
| } | ||
| throw; | ||
| } | ||
|
|
||
| // ── Step 4: Atomic swap — staging → live ────────────────────────────────────── | ||
| // Two ALTER TABLE RENAME operations in one transaction (live → old, staging → live). | ||
| // Each RENAME auto-acquires AccessExclusiveLock on its table; the transaction | ||
| // guarantees both renames are visible atomically to other sessions. | ||
| await using var conn = await dataSource.OpenConnectionAsync(cancellationToken); | ||
| await using var tx = await conn.BeginTransactionAsync(cancellationToken); | ||
|
|
||
| await using (var cmd = conn.CreateCommand()) | ||
| { | ||
| cmd.Transaction = tx; | ||
|
|
||
| // Drop any leftover backup from a previous run | ||
| cmd.CommandText = $"DROP TABLE IF EXISTS \"{oldName}\""; | ||
| await cmd.ExecuteNonQueryAsync(cancellationToken); | ||
|
|
||
| // Rename live → old. IF EXISTS is a no-op on first run when no live table exists. | ||
| cmd.CommandText = $"ALTER TABLE IF EXISTS \"{collectionName}\" RENAME TO \"{oldName}\""; | ||
| await cmd.ExecuteNonQueryAsync(cancellationToken); | ||
|
|
||
| // Rename staging → live | ||
| cmd.CommandText = $"ALTER TABLE \"{stagingName}\" RENAME TO \"{collectionName}\""; | ||
| await cmd.ExecuteNonQueryAsync(cancellationToken); | ||
| } | ||
|
|
||
| await tx.CommitAsync(cancellationToken); | ||
| Console.WriteLine($"Swapped '{stagingName}' → '{collectionName}' atomically."); | ||
|
|
||
| // ── Step 5: Drop the old backup ─────────────────────────────────────────────── | ||
| await using (var cmd = conn.CreateCommand()) | ||
| { | ||
| cmd.CommandText = $"DROP TABLE IF EXISTS \"{oldName}\""; | ||
| await cmd.ExecuteNonQueryAsync(cancellationToken); | ||
| } | ||
|
|
||
| Console.WriteLine($"Successfully generated embeddings and uploaded {chunkList.Count} chunks to collection '{collectionName}'."); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These SQL statements interpolate
collectionName/derived names directly into identifier-quoted SQL. IfcollectionNamecan be influenced outside trusted code, this becomes identifier-injection (quotes can be escaped/broken). Consider restrictingcollectionNameto a safe identifier regex (e.g., letters/digits/underscore) before composing SQL, and use Npgsql's identifier-quoting helper to build the final identifiers consistently.