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:
2026-10-26 17:51:39 +03:30
parent fef38cad1b
commit 9e82e05bfe
6 changed files with 1154 additions and 1 deletions
+6
View File
@@ -23,5 +23,11 @@ namespace xAiApi.Constants
//
public const string XOpenAINoKey = "no-key-required";
//
// Knowledge (Persistent RAG) ...
public const string XAiKnowledgeOwnerSeparator = "/";
public const string XAiKnowledgeMetadataOwnerId = "ownerId";
public const string XAiKnowledgeMetadataIngestedAtUtc = "ingestedAtUtc";
}
}
+319
View File
@@ -0,0 +1,319 @@
using System;
using xAiApi.Models;
using System.Threading;
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Controllers;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
/// <summary>
/// Knowledge (Persistent RAG over XAiVector Table) Controller ...
/// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete
/// </summary>
[Authorize]
[Route("[controller]")]
public class KnowledgeController : XBaseIdentityApiV1Controller
{
/// <summary>
/// Persistent RAG Service ...
/// </summary>
private readonly IXAiRAGService ragService;
public KnowledgeController(
IXAiRAGService ragService,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
ILogger<KnowledgeController> logger,
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{
//
this.ragService = ragService;
}
//
#region Ingest ...
/// <summary>
/// Ingest Files into Current User's Knowledge Base:
/// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
/// </summary>
/// <param name="files"></param>
/// <param name="replaceExisting">Replace Previously Stored Vectors of Same File (default true)</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Ingest")]
[Consumes("multipart/form-data")]
public async Task<ActionResult<XAiKnowledgeIngestResult>> Ingest(
[FromForm] IFormFileCollection files,
[FromForm] bool replaceExisting = true,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (!files.HasChild())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
//
var result = await ragService.IngestAsync(
files: files,
ownerId: userInfo.UserId,
replaceExisting: replaceExisting,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Ask ...
/// <summary>
/// Ask a Question over Knowledge Base (RAG) ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Ask")]
public async Task<ActionResult<XAiDocumentAnswer>> Ask(
[FromBody] XAiKnowledgeAskRequest request,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
//
var result = await ragService.AskWithRAGAsync(
request: request,
ownerId: userInfo.UserId,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Ask a Question over Knowledge Base and Stream Response (SSE) ...
/// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has isFinal = true ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AskStream")]
public async Task AskStream(
[FromBody] XAiKnowledgeAskRequest request,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
//
// Configure SSE Response Headers ...
Response.Headers["X-Accel-Buffering"] = "no";
Response.Headers["Connection"] = "keep-alive";
Response.Headers["Content-Type"] = "text/event-stream";
Response.Headers["Cache-Control"] = "no-cache, no-store";
//
// Disable Response Buffering ...
var responseBodyFeature = HttpContext.Features
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
responseBodyFeature?.DisableBuffering();
//
var enumerable = ragService.AskWithRAGAsEnumerable(
request: request,
ownerId: userInfo.UserId,
cancellationToken: cancellationToken
);
//
await foreach (var chunk in enumerable)
{
//
if (chunk.IsNullOrDefault())
{
continue;
}
//
await WriteChunk(chunk, cancellationToken);
}
//
await Response.Body.FlushAsync(cancellationToken);
}
catch (OperationCanceledException)
{
// Client Disconnected ...
}
catch (Exception ex)
{
//
Logger.LogError(ex, "Knowledge: AskStream Failed");
try
{
//
if (!Response.HasStarted)
{
Response.StatusCode = StatusCodes.Status500InternalServerError;
}
await Response.Body.FlushAsync(CancellationToken.None);
}
catch { /* ignore */ }
}
}
#endregion
//
#region Documents ...
/// <summary>
/// List Ingested Documents of Current User ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("Documents")]
public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
CancellationToken cancellationToken = default
)
{
//
try
{
//
var userInfo = await GetUserInfo();
//
var result = await ragService.LoadDocumentsAsync(
ownerId: userInfo.UserId,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Remove All Vectors of a Document ...
/// </summary>
/// <param name="fileName"></param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Removed Vectors</returns>
[HttpDelete("Documents")]
public async Task<ActionResult<int>> DeleteDocument(
[FromQuery] string fileName,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
ValidationProvider.NotEmpty(fileName);
//
var userInfo = await GetUserInfo();
//
var result = await ragService.RemoveDocumentAsync(
fileName: fileName,
ownerId: userInfo.UserId,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Private ...
/// <summary>
/// Write a SSE Event ...
/// </summary>
private async Task WriteChunk(
XAiDocumentAnswerChunk chunk,
CancellationToken cancellationToken
)
{
//
var payload = chunk.ToJSON(camelCase: true);
await Response.WriteAsync($"data: {payload}\n\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
#endregion
}
}
+5 -1
View File
@@ -84,7 +84,11 @@ namespace xAiApi.DI
//
source.AddScoped<IXDefaultAiService, XDefaultAiService>();
source.AddScoped<IXDefaultEmbeddingService, XDefaultEmbeddingService>();
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
//
// Persistent RAG (Knowledge over XAiVector Table) ...
source.AddScoped<IXAiRAGService, XAiRAGService>();
}
/// <summary>
+110
View File
@@ -0,0 +1,110 @@
using xAiApi.Models;
using System.Threading;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
namespace xAiApi.Interfaces
{
/// <summary>
/// Persistent RAG Service over XAiVector Table:
/// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
/// </summary>
public interface IXAiRAGService
{
/// <summary>
/// Ingest Files into Owner's Knowledge Base ...
/// </summary>
/// <param name="files"></param>
/// <param name="ownerId"></param>
/// <param name="replaceExisting">Remove Previously Stored Vectors of Same File before Store</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XAiKnowledgeIngestResult> IngestAsync(
IFormFileCollection files,
string ownerId,
bool replaceExisting = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="ownerId"></param>
/// <param name="topK"></param>
/// <param name="minScore"></param>
/// <param name="fileName">Optional: Restrict to a Specific File</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<XAiVectorSearchResult>> RetrieveAsync(
string prompt,
string ownerId,
int? topK = null,
float? minScore = null,
string fileName = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// Ask a Question with RAG (Retrieve from DB then Generate) ...
/// </summary>
/// <param name="request"></param>
/// <param name="ownerId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XAiDocumentAnswer> AskWithRAGAsync(
XAiKnowledgeAskRequest request,
string ownerId,
CancellationToken cancellationToken = default
);
/// <summary>
/// Ask a Question with RAG and Stream Response ...
/// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ...
/// </summary>
/// <param name="request"></param>
/// <param name="ownerId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IAsyncEnumerable<XAiDocumentAnswerChunk> AskWithRAGAsEnumerable(
XAiKnowledgeAskRequest request,
string ownerId,
CancellationToken cancellationToken = default
);
/// <summary>
/// List Ingested Documents of Owner ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
string ownerId,
CancellationToken cancellationToken = default
);
/// <summary>
/// Remove All Vectors of a Document ...
/// </summary>
/// <param name="ownerId"></param>
/// <param name="fileName"></param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Removed Vectors</returns>
Task<int> RemoveDocumentAsync(
string ownerId,
string fileName,
CancellationToken cancellationToken = default
);
/// <summary>
/// Map Search Results to Public Sources ...
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
IList<XAiDocumentSource> ToSources(
IEnumerable<XAiVectorSearchResult> context
);
}
}
+88
View File
@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
namespace xAiApi.Models
{
/// <summary>
/// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ...
/// </summary>
public class XAiKnowledgeIngestResult
{
/// <summary>
/// Count of Successfully Ingested Files ...
/// </summary>
public int FilesCount { get; set; }
/// <summary>
/// Count of Stored Chunks (Vectors) in this Request ...
/// </summary>
public int ChunksCount { get; set; }
/// <summary>
/// Count of Removed Stale Vectors (Re-Ingest) ...
/// </summary>
public int ReplacedCount { get; set; }
/// <summary>
/// Skipped Files (Empty, Unsupported or Extraction Failed) ...
/// </summary>
public IList<string> SkippedFiles { get; set; } = new List<string>();
/// <summary>
/// Ingested Documents Info ...
/// </summary>
public IList<XAiKnowledgeDocumentInfo> Documents { get; set; } = new List<XAiKnowledgeDocumentInfo>();
}
/// <summary>
/// Ask Request over Persistent Knowledge Base ...
/// </summary>
public class XAiKnowledgeAskRequest
{
/// <summary>
/// Question ...
/// </summary>
public string Prompt { get; set; }
/// <summary>
/// Optional: Restrict Retrieval to a Specific File ...
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Optional: Max Retrieved Chunks ...
/// </summary>
public int? TopK { get; set; }
/// <summary>
/// Optional: Minimum Cosine Similarity Score ...
/// </summary>
public float? MinScore { get; set; }
}
/// <summary>
/// Ingested Document Info ...
/// </summary>
public class XAiKnowledgeDocumentInfo
{
/// <summary>
/// File Name ...
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Mime Type ...
/// </summary>
public string MimeType { get; set; }
/// <summary>
/// Count of Stored Chunks ...
/// </summary>
public int ChunksCount { get; set; }
/// <summary>
/// Ingestion Time (UTC) ...
/// </summary>
public DateTime? IngestedAtUtc { get; set; }
}
}
+626
View File
@@ -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
}
}