diff --git a/Constants/XAiApiConstants.cs b/Constants/XAiApiConstants.cs
index 3aae7de..e34afd5 100644
--- a/Constants/XAiApiConstants.cs
+++ b/Constants/XAiApiConstants.cs
@@ -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";
}
}
\ No newline at end of file
diff --git a/Controllers/KnowledgeController.cs b/Controllers/KnowledgeController.cs
new file mode 100644
index 0000000..9488a27
--- /dev/null
+++ b/Controllers/KnowledgeController.cs
@@ -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
+{
+ ///
+ /// Knowledge (Persistent RAG over XAiVector Table) Controller ...
+ /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete
+ ///
+ [Authorize]
+ [Route("[controller]")]
+ public class KnowledgeController : XBaseIdentityApiV1Controller
+ {
+ ///
+ /// Persistent RAG Service ...
+ ///
+ private readonly IXAiRAGService ragService;
+
+ public KnowledgeController(
+ IXAiRAGService ragService,
+ XAppConfiguration appConfiguration,
+ IXIdentityProvider identityProvider,
+ ILogger logger,
+ XValidationProvider validationProvider
+ ) : base(logger, appConfiguration, identityProvider, validationProvider)
+ {
+ //
+ this.ragService = ragService;
+ }
+
+ //
+ #region Ingest ...
+ ///
+ /// Ingest Files into Current User's Knowledge Base:
+ /// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
+ ///
+ ///
+ /// Replace Previously Stored Vectors of Same File (default true)
+ ///
+ ///
+ [HttpPost("Ingest")]
+ [Consumes("multipart/form-data")]
+ public async Task> 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 ...
+ ///
+ /// Ask a Question over Knowledge Base (RAG) ...
+ ///
+ ///
+ ///
+ ///
+ [HttpPost("Ask")]
+ public async Task> 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;
+ }
+ }
+
+ ///
+ /// Ask a Question over Knowledge Base and Stream Response (SSE) ...
+ /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has isFinal = true ...
+ ///
+ ///
+ ///
+ ///
+ [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();
+ 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 ...
+ ///
+ /// List Ingested Documents of Current User ...
+ ///
+ ///
+ ///
+ [HttpGet("Documents")]
+ public async Task>> 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;
+ }
+ }
+
+ ///
+ /// Remove All Vectors of a Document ...
+ ///
+ ///
+ ///
+ /// Count of Removed Vectors
+ [HttpDelete("Documents")]
+ public async Task> 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 ...
+ ///
+ /// Write a SSE Event ...
+ ///
+ 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
+ }
+}
+
diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs
index 9bee46a..32ad347 100644
--- a/DI/XDIHelperExtension.cs
+++ b/DI/XDIHelperExtension.cs
@@ -84,7 +84,11 @@ namespace xAiApi.DI
//
source.AddScoped();
source.AddScoped();
- source.AddScoped();
+ source.AddScoped();
+
+ //
+ // Persistent RAG (Knowledge over XAiVector Table) ...
+ source.AddScoped();
}
///
diff --git a/Interfaces/IXAiRAGService.cs b/Interfaces/IXAiRAGService.cs
new file mode 100644
index 0000000..f47a7ef
--- /dev/null
+++ b/Interfaces/IXAiRAGService.cs
@@ -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
+{
+ ///
+ /// Persistent RAG Service over XAiVector Table:
+ /// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
+ ///
+ public interface IXAiRAGService
+ {
+ ///
+ /// Ingest Files into Owner's Knowledge Base ...
+ ///
+ ///
+ ///
+ /// Remove Previously Stored Vectors of Same File before Store
+ ///
+ ///
+ Task IngestAsync(
+ IFormFileCollection files,
+ string ownerId,
+ bool replaceExisting = true,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ /// Optional: Restrict to a Specific File
+ ///
+ ///
+ Task> RetrieveAsync(
+ string prompt,
+ string ownerId,
+ int? topK = null,
+ float? minScore = null,
+ string fileName = null,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Ask a Question with RAG (Retrieve from DB then Generate) ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task AskWithRAGAsync(
+ XAiKnowledgeAskRequest request,
+ string ownerId,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Ask a Question with RAG and Stream Response ...
+ /// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ IAsyncEnumerable AskWithRAGAsEnumerable(
+ XAiKnowledgeAskRequest request,
+ string ownerId,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// List Ingested Documents of Owner ...
+ ///
+ ///
+ ///
+ ///
+ Task> LoadDocumentsAsync(
+ string ownerId,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Remove All Vectors of a Document ...
+ ///
+ ///
+ ///
+ ///
+ /// Count of Removed Vectors
+ Task RemoveDocumentAsync(
+ string ownerId,
+ string fileName,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Map Search Results to Public Sources ...
+ ///
+ ///
+ ///
+ IList ToSources(
+ IEnumerable context
+ );
+ }
+}
diff --git a/Models/XAiKnowledgeModels.cs b/Models/XAiKnowledgeModels.cs
new file mode 100644
index 0000000..c524b77
--- /dev/null
+++ b/Models/XAiKnowledgeModels.cs
@@ -0,0 +1,88 @@
+using System;
+using System.Collections.Generic;
+
+namespace xAiApi.Models
+{
+ ///
+ /// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ...
+ ///
+ public class XAiKnowledgeIngestResult
+ {
+ ///
+ /// Count of Successfully Ingested Files ...
+ ///
+ public int FilesCount { get; set; }
+
+ ///
+ /// Count of Stored Chunks (Vectors) in this Request ...
+ ///
+ public int ChunksCount { get; set; }
+
+ ///
+ /// Count of Removed Stale Vectors (Re-Ingest) ...
+ ///
+ public int ReplacedCount { get; set; }
+
+ ///
+ /// Skipped Files (Empty, Unsupported or Extraction Failed) ...
+ ///
+ public IList SkippedFiles { get; set; } = new List();
+
+ ///
+ /// Ingested Documents Info ...
+ ///
+ public IList Documents { get; set; } = new List();
+ }
+
+ ///
+ /// Ask Request over Persistent Knowledge Base ...
+ ///
+ public class XAiKnowledgeAskRequest
+ {
+ ///
+ /// Question ...
+ ///
+ public string Prompt { get; set; }
+
+ ///
+ /// Optional: Restrict Retrieval to a Specific File ...
+ ///
+ public string FileName { get; set; }
+
+ ///
+ /// Optional: Max Retrieved Chunks ...
+ ///
+ public int? TopK { get; set; }
+
+ ///
+ /// Optional: Minimum Cosine Similarity Score ...
+ ///
+ public float? MinScore { get; set; }
+ }
+
+ ///
+ /// Ingested Document Info ...
+ ///
+ public class XAiKnowledgeDocumentInfo
+ {
+ ///
+ /// File Name ...
+ ///
+ public string FileName { get; set; }
+
+ ///
+ /// Mime Type ...
+ ///
+ public string MimeType { get; set; }
+
+ ///
+ /// Count of Stored Chunks ...
+ ///
+ public int ChunksCount { get; set; }
+
+ ///
+ /// Ingestion Time (UTC) ...
+ ///
+ public DateTime? IngestedAtUtc { get; set; }
+ }
+}
diff --git a/Providers/XAiRAGService.cs b/Providers/XAiRAGService.cs
new file mode 100644
index 0000000..b21ffb3
--- /dev/null
+++ b/Providers/XAiRAGService.cs
@@ -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
+{
+ ///
+ /// Persistent RAG Service over XAiVector Table ...
+ /// Isolation: Identifier = "{ownerId}/{fileName}#{chunkIndex}" ...
+ ///
+ public class XAiRAGService : IXAiRAGService
+ {
+ private readonly IXTextChunker textChunker;
+ private readonly IXFileProvider fileProvider;
+ private readonly IXDefaultAiService aiService;
+ private readonly IXAiDataProvider dataProvider;
+ private readonly ILogger logger;
+ private readonly XAiApiConfiguration configuration;
+ private readonly IXDefaultEmbeddingService embeddingService;
+ private readonly IXFileContentExtractor fileContentExtractor;
+
+ public XAiRAGService(
+ IXTextChunker textChunker,
+ IXFileProvider fileProvider,
+ IXDefaultAiService aiService,
+ IXAiDataProvider dataProvider,
+ ILogger 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 ...
+ ///
+ /// Ingest Files into Owner's Knowledge Base:
+ /// Extract -> Chunk -> Embed -> Store (XAiVector) ...
+ ///
+ public async Task 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 ...
+ ///
+ /// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ...
+ ///
+ public async Task> 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;
+ }
+
+ ///
+ /// Ask a Question with RAG (Retrieve from DB then Generate) ...
+ ///
+ public async Task 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;
+ }
+
+ ///
+ /// Ask a Question with RAG and Stream Response ...
+ ///
+ public async IAsyncEnumerable 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 ...
+ ///
+ /// List Ingested Documents of Owner (Grouped by File Name) ...
+ ///
+ public async Task> 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;
+ }
+
+ ///
+ /// Remove All Vectors of a Document ...
+ ///
+ public async Task 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;
+ }
+
+ ///
+ /// Map Search Results to Public Sources ...
+ ///
+ public IList ToSources(
+ IEnumerable 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 ...
+ ///
+ /// Owner Scope Prefix: "{ownerId}/" ...
+ ///
+ private static string GetOwnerPrefix(string ownerId)
+ {
+ return $"{ownerId}{XAiApiConstants.XAiKnowledgeOwnerSeparator}";
+ }
+
+ ///
+ /// Document Prefix (Chunker Source): "{ownerId}/{fileName}" ...
+ ///
+ private static string GetDocumentPrefix(string ownerId, string fileName)
+ {
+ return $"{GetOwnerPrefix(ownerId)}{fileName}";
+ }
+
+ ///
+ /// Document Chunk Prefix: "{ownerId}/{fileName}#" ...
+ /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
+ ///
+ private string GetDocumentChunkPrefix(string ownerId, string fileName)
+ {
+ return $"{GetDocumentPrefix(ownerId, fileName)}{configuration.TextChunker.ChunkIdentifierSeparator}";
+ }
+
+ ///
+ /// Extract Plain Text of a File (Text or Audio Transcript) ...
+ ///
+ private async Task 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;
+ }
+ }
+
+ ///
+ /// Embed Chunks in Batches and Build Vectors ...
+ ///
+ private async Task> EmbedChunks(
+ IList 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(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
+ {
+ [rag.MetadataFileName] = fileName,
+ [rag.MetadataMimeType] = mimeType,
+ [rag.MetadataChunkIndex] = chunk.Index.ToString(),
+ [XAiApiConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
+ [XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
+ }
+ });
+ }
+ }
+
+ //
+ return result;
+ }
+
+ ///
+ /// Safe Metadata Reader ...
+ ///
+ private static string GetMetadata(
+ IDictionary metadata,
+ string key
+ )
+ {
+ //
+ if (metadata.IsNullOrDefault() || !metadata.TryGetValue(key, out var value))
+ {
+ return null;
+ }
+
+ //
+ return value;
+ }
+ #endregion
+ }
+}
+