Add Persistent Knowledge RAG Service and API
- Add IXAiRAGService and XAiRAGService for Extract -> Chunk -> Embed -> Store;
- Add synchronous and streaming RAG answers with sources;
- Add Knowledge models and KnowledgeController endpoints;
- Register IXAiRAGService as scoped;
- Keep current identifier: {ownerId}/{fileName}#{chunkIndex}.
This commit is contained in:
@@ -0,0 +1,626 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xAiApi.Models;
|
||||
using System.Threading;
|
||||
using xAiApi.Constants;
|
||||
using xAiApi.Interfaces;
|
||||
using xCommons.Extensions;
|
||||
using xAiModels.Interfaces;
|
||||
using xAiApi.Configurations;
|
||||
using xExceptions.Constants;
|
||||
using xAiModels.Models.Dtos;
|
||||
using System.Threading.Tasks;
|
||||
using xFileService.Interfaces;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xAiApi.Interfaces.Extractors;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace xAiApi.Providers
|
||||
{
|
||||
/// <summary>
|
||||
/// Persistent RAG Service over XAiVector Table ...
|
||||
/// Isolation: Identifier = "{ownerId}/{fileName}#{chunkIndex}" ...
|
||||
/// </summary>
|
||||
public class XAiRAGService : IXAiRAGService
|
||||
{
|
||||
private readonly IXTextChunker textChunker;
|
||||
private readonly IXFileProvider fileProvider;
|
||||
private readonly IXDefaultAiService aiService;
|
||||
private readonly IXAiDataProvider dataProvider;
|
||||
private readonly ILogger<XAiRAGService> logger;
|
||||
private readonly XAiApiConfiguration configuration;
|
||||
private readonly IXDefaultEmbeddingService embeddingService;
|
||||
private readonly IXFileContentExtractor fileContentExtractor;
|
||||
|
||||
public XAiRAGService(
|
||||
IXTextChunker textChunker,
|
||||
IXFileProvider fileProvider,
|
||||
IXDefaultAiService aiService,
|
||||
IXAiDataProvider dataProvider,
|
||||
ILogger<XAiRAGService> logger,
|
||||
XAiApiConfiguration configuration,
|
||||
IXDefaultEmbeddingService embeddingService,
|
||||
IXFileContentExtractor fileContentExtractor
|
||||
)
|
||||
{
|
||||
//
|
||||
this.logger = logger;
|
||||
this.aiService = aiService;
|
||||
this.textChunker = textChunker;
|
||||
this.fileProvider = fileProvider;
|
||||
this.dataProvider = dataProvider;
|
||||
this.configuration = configuration;
|
||||
this.embeddingService = embeddingService;
|
||||
this.fileContentExtractor = fileContentExtractor;
|
||||
}
|
||||
|
||||
//
|
||||
#region Ingest ...
|
||||
/// <summary>
|
||||
/// Ingest Files into Owner's Knowledge Base:
|
||||
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
|
||||
/// </summary>
|
||||
public async Task<XAiKnowledgeIngestResult> IngestAsync(
|
||||
IFormFileCollection files,
|
||||
string ownerId,
|
||||
bool replaceExisting = true,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!files.HasChild() || ownerId.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = new XAiKnowledgeIngestResult();
|
||||
var ingestedAtUtc = DateTime.UtcNow.ToString("O");
|
||||
|
||||
//
|
||||
foreach (var file in files)
|
||||
{
|
||||
//
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
//
|
||||
if (file.IsNull() || file.Length == 0)
|
||||
{
|
||||
result.SkippedFiles.Add(file?.FileName ?? "(null)");
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
|
||||
if (!fileContentExtractor.CanExtract(mimeType))
|
||||
{
|
||||
result.SkippedFiles.Add(file.FileName);
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
var text = await ExtractText(file, mimeType, cancellationToken);
|
||||
if (text.IsNullOrEmpty())
|
||||
{
|
||||
result.SkippedFiles.Add(file.FileName);
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
// Chunk with Owner Scoped Source => Identifier = "{ownerId}/{fileName}#{index}" ...
|
||||
var documentPrefix = GetDocumentPrefix(ownerId, file.FileName);
|
||||
var chunks = textChunker.Chunk(text, documentPrefix);
|
||||
if (!chunks.HasChild())
|
||||
{
|
||||
result.SkippedFiles.Add(file.FileName);
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
// TODO: Implement File Save ...
|
||||
|
||||
//
|
||||
// Embed in Batches ...
|
||||
var vectors = await EmbedChunks(
|
||||
chunks: chunks,
|
||||
ownerId: ownerId,
|
||||
mimeType: mimeType,
|
||||
fileName: file.FileName,
|
||||
ingestedAtUtc: ingestedAtUtc,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
// Remove Stale Vectors of Same Document ...
|
||||
if (replaceExisting)
|
||||
{
|
||||
//
|
||||
result.ReplacedCount += await dataProvider.RemoveVectorsAsync(
|
||||
identifierPrefix: GetDocumentChunkPrefix(ownerId, file.FileName),
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// Store ...
|
||||
var storedCount = await dataProvider.UpsertVectorsAsync(
|
||||
items: vectors,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
result.FilesCount++;
|
||||
result.ChunksCount += storedCount;
|
||||
result.Documents.Add(new XAiKnowledgeDocumentInfo
|
||||
{
|
||||
MimeType = mimeType,
|
||||
FileName = file.FileName,
|
||||
ChunksCount = storedCount,
|
||||
IngestedAtUtc = DateTime.Parse(ingestedAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind)
|
||||
});
|
||||
|
||||
//
|
||||
logger.LogInformation(
|
||||
"Knowledge: Ingested {FileName} for {OwnerId} with {Chunks} Chunks",
|
||||
file.FileName, ownerId, storedCount
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
//
|
||||
#region Ask ...
|
||||
/// <summary>
|
||||
/// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ...
|
||||
/// </summary>
|
||||
public async Task<IList<XAiVectorSearchResult>> RetrieveAsync(
|
||||
string prompt,
|
||||
string ownerId,
|
||||
int? topK = null,
|
||||
float? minScore = null,
|
||||
string fileName = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (prompt.IsNullOrEmpty() || ownerId.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var rag = configuration.RAGDescriptor;
|
||||
var effectiveTopK = Math.Clamp(topK ?? rag.DefaultTopK, 1, rag.MaxTopK);
|
||||
var effectiveMinScore = minScore ?? rag.DefaultMinScore;
|
||||
|
||||
//
|
||||
// Embed Question ...
|
||||
var queryEmbedding = await embeddingService.Embedding(
|
||||
content: prompt,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
|
||||
{
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Search in DB (Scoped to Owner or Owner + File) ...
|
||||
var prefix = fileName.IsNullOrEmpty()
|
||||
? GetOwnerPrefix(ownerId)
|
||||
: GetDocumentChunkPrefix(ownerId, fileName);
|
||||
var searchResult = await dataProvider.SearchVectorsAsync(
|
||||
topK: effectiveTopK,
|
||||
identifierPrefix: prefix,
|
||||
minScore: effectiveMinScore,
|
||||
queryEmbedding: queryEmbedding,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
var result = searchResult?.ToList() ?? [];
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ask a Question with RAG (Retrieve from DB then Generate) ...
|
||||
/// </summary>
|
||||
public async Task<XAiDocumentAnswer> AskWithRAGAsync(
|
||||
XAiKnowledgeAskRequest request,
|
||||
string ownerId,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Retrieve ...
|
||||
var context = await RetrieveAsync(
|
||||
ownerId: ownerId,
|
||||
topK: request.TopK,
|
||||
prompt: request.Prompt,
|
||||
minScore: request.MinScore,
|
||||
fileName: request.FileName,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
var result = new XAiDocumentAnswer
|
||||
{
|
||||
Sources = ToSources(context)
|
||||
};
|
||||
if (!context.HasChild())
|
||||
{
|
||||
//
|
||||
result.NoContextFound = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
// Generate ...
|
||||
result.Answer = await aiService.AskWithContextAsync(
|
||||
context: context,
|
||||
prompt: request.Prompt,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ask a Question with RAG and Stream Response ...
|
||||
/// </summary>
|
||||
public async IAsyncEnumerable<XAiDocumentAnswerChunk> AskWithRAGAsEnumerable(
|
||||
XAiKnowledgeAskRequest request,
|
||||
string ownerId,
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Retrieve ...
|
||||
var context = await RetrieveAsync(
|
||||
ownerId: ownerId,
|
||||
topK: request.TopK,
|
||||
prompt: request.Prompt,
|
||||
minScore: request.MinScore,
|
||||
fileName: request.FileName,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
// First Item: Sources ...
|
||||
var hasContext = context.HasChild();
|
||||
yield return new XAiDocumentAnswerChunk
|
||||
{
|
||||
Text = string.Empty,
|
||||
IsFinal = !hasContext,
|
||||
NoContextFound = !hasContext,
|
||||
Sources = ToSources(context)
|
||||
};
|
||||
if (!hasContext)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
//
|
||||
// Stream Deltas ...
|
||||
var enumerable = aiService.AskWithContextAsEnumerable(
|
||||
context: context,
|
||||
prompt: request.Prompt,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
await foreach (var delta in enumerable)
|
||||
{
|
||||
//
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
//
|
||||
if (delta.IsNullOrEmpty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
yield return new XAiDocumentAnswerChunk { Text = delta };
|
||||
}
|
||||
|
||||
//
|
||||
// Final Item ...
|
||||
yield return new XAiDocumentAnswerChunk
|
||||
{
|
||||
Text = string.Empty,
|
||||
IsFinal = true
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Documents ...
|
||||
/// <summary>
|
||||
/// List Ingested Documents of Owner (Grouped by File Name) ...
|
||||
/// </summary>
|
||||
public async Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
|
||||
string ownerId,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (ownerId.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var vectors = await dataProvider.LoadVectorsAsync(
|
||||
includeEmbedding: false,
|
||||
cancellationToken: cancellationToken,
|
||||
identifierPrefix: GetOwnerPrefix(ownerId)
|
||||
);
|
||||
|
||||
//
|
||||
var rag = configuration.RAGDescriptor;
|
||||
var result = (vectors ?? [])
|
||||
.GroupBy(v => GetMetadata(v.Metadata, rag.MetadataFileName) ?? v.Identifier)
|
||||
.Select(g =>
|
||||
{
|
||||
//
|
||||
var first = g.First();
|
||||
var ingestedText = GetMetadata(first.Metadata, XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc);
|
||||
|
||||
//
|
||||
return new XAiKnowledgeDocumentInfo
|
||||
{
|
||||
FileName = g.Key,
|
||||
ChunksCount = g.Count(),
|
||||
MimeType = GetMetadata(first.Metadata, rag.MetadataMimeType),
|
||||
IngestedAtUtc = DateTime.TryParse(
|
||||
ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt
|
||||
) ? dt : null
|
||||
};
|
||||
})
|
||||
.OrderBy(d => d.FileName)
|
||||
.ToList();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove All Vectors of a Document ...
|
||||
/// </summary>
|
||||
public async Task<int> RemoveDocumentAsync(
|
||||
string ownerId,
|
||||
string fileName,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (ownerId.IsNullOrEmpty() || fileName.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = await dataProvider.RemoveVectorsAsync(
|
||||
cancellationToken: cancellationToken,
|
||||
identifierPrefix: GetDocumentChunkPrefix(ownerId, fileName)
|
||||
);
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Map Search Results to Public Sources ...
|
||||
/// </summary>
|
||||
public IList<XAiDocumentSource> ToSources(
|
||||
IEnumerable<XAiVectorSearchResult> context
|
||||
)
|
||||
{
|
||||
//
|
||||
var rag = configuration.RAGDescriptor;
|
||||
var result = (context ?? [])
|
||||
.Select(c =>
|
||||
{
|
||||
//
|
||||
var text = c.Text ?? string.Empty;
|
||||
var chunkIndexText = GetMetadata(c.Metadata, rag.MetadataChunkIndex);
|
||||
var snippetLength = Math.Min(text.Length, rag.SourceSnippetLength);
|
||||
|
||||
//
|
||||
return new XAiDocumentSource
|
||||
{
|
||||
Score = c.Score,
|
||||
Identifier = c.Identifier,
|
||||
Snippet = text.Substring(0, snippetLength),
|
||||
FileName = GetMetadata(c.Metadata, rag.MetadataFileName),
|
||||
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null
|
||||
};
|
||||
})
|
||||
.ToList();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
/// <summary>
|
||||
/// Owner Scope Prefix: "{ownerId}/" ...
|
||||
/// </summary>
|
||||
private static string GetOwnerPrefix(string ownerId)
|
||||
{
|
||||
return $"{ownerId}{XAiApiConstants.XAiKnowledgeOwnerSeparator}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Document Prefix (Chunker Source): "{ownerId}/{fileName}" ...
|
||||
/// </summary>
|
||||
private static string GetDocumentPrefix(string ownerId, string fileName)
|
||||
{
|
||||
return $"{GetOwnerPrefix(ownerId)}{fileName}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Document Chunk Prefix: "{ownerId}/{fileName}#" ...
|
||||
/// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
|
||||
/// </summary>
|
||||
private string GetDocumentChunkPrefix(string ownerId, string fileName)
|
||||
{
|
||||
return $"{GetDocumentPrefix(ownerId, fileName)}{configuration.TextChunker.ChunkIdentifierSeparator}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract Plain Text of a File (Text or Audio Transcript) ...
|
||||
/// </summary>
|
||||
private async Task<string> ExtractText(
|
||||
IFormFile file,
|
||||
string mimeType,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
using var stream = file.OpenReadStream();
|
||||
var extraction = await fileContentExtractor.ExtractRichAsync(
|
||||
fileStream: stream,
|
||||
mimeType: mimeType,
|
||||
fileName: file.FileName,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
var result = extraction?.Text;
|
||||
if (string.IsNullOrWhiteSpace(result))
|
||||
{
|
||||
result = extraction?.AudioTranscript;
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Embed Chunks in Batches and Build Vectors ...
|
||||
/// </summary>
|
||||
private async Task<IList<XAiVectorDto>> EmbedChunks(
|
||||
IList<XTextChunk> chunks,
|
||||
string ownerId,
|
||||
string fileName,
|
||||
string mimeType,
|
||||
string ingestedAtUtc,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
//
|
||||
var rag = configuration.RAGDescriptor;
|
||||
var batchSize = Math.Max(1, rag.EmbeddingBatchSize);
|
||||
var result = new List<XAiVectorDto>(chunks.Count);
|
||||
|
||||
//
|
||||
for (var offset = 0; offset < chunks.Count; offset += batchSize)
|
||||
{
|
||||
//
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
//
|
||||
var batch = chunks.Skip(offset).Take(batchSize).ToList();
|
||||
var embeddings = await embeddingService.Embeddings(
|
||||
batch: batch.Select(c => c.Text).ToArray(),
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count)
|
||||
{
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
for (var i = 0; i < batch.Count; i++)
|
||||
{
|
||||
//
|
||||
var chunk = batch[i];
|
||||
result.Add(new XAiVectorDto
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Text = chunk.Text,
|
||||
Embedding = embeddings[i],
|
||||
Identifier = chunk.Identifier,
|
||||
Metadata = new Dictionary<string, string>
|
||||
{
|
||||
[rag.MetadataFileName] = fileName,
|
||||
[rag.MetadataMimeType] = mimeType,
|
||||
[rag.MetadataChunkIndex] = chunk.Index.ToString(),
|
||||
[XAiApiConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
|
||||
[XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Safe Metadata Reader ...
|
||||
/// </summary>
|
||||
private static string GetMetadata(
|
||||
IDictionary<string, string> metadata,
|
||||
string key
|
||||
)
|
||||
{
|
||||
//
|
||||
if (metadata.IsNullOrDefault() || !metadata.TryGetValue(key, out var value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
return value;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user