Integrate RAG into Chat Pipeline and Decouple Embedding Service
- AskAsync: accept Guid? projectId / conversationId; resolve defaults;
- AskAsync: ingest attached files into Conversation scope (replaceExisting)
via IXAiRAGService instead of Upload + Extract + raw content attachment;
- AskAsync: retrieve context (Conversation -> Project -> User -> Global)
and build a single System message: Introduction + ChatWithDocuments prompt
+ Context block (+ Project prompt);
- XAIServiceBase / XDefaultAiService / XDefaultThinkingAiService:
inject IXAiRAGService instead of IXFileProvider;
- Add IXAiEmbeddingService + XAiEmbeddingService; remove
IXDefaultEmbeddingService + XDefaultEmbeddingService;
- XAiEmbeddingServiceBase no longer inherits XAIServiceBase;
IXAiEmbeddingServiceBase / IXAiEmbeddingServiceControllerBase no longer
extend chat interfaces; XAiEmbeddingServiceControllerBase derives from
XBaseIdentityApiV1Controller;
- XAiRAGService: drop IXDefaultAiService dependency (removes circular
dependency); remove AskWithRAGAsync / AskWithRAGAsEnumerable; add file
reference (AddReference) for scoped ingests;
- KnowledgeController: remove POST Ask and POST AskStream;
- DI: add AddXRagService() and call it from Startup before AddXAiServices();
- Add XAiApiRagPromptName = "ChatWithDocuments";
- Knowledge scope factories default Type to XAiDefaultKnowledgeType;
- ChatWithDocuments ask request: TopK and MinScore are now required.
BREAKING: /Knowledge/Ask and /Knowledge/AskStream removed;
IXDefaultEmbeddingService replaced by IXAiEmbeddingService.
This commit is contained in:
+139
-243
@@ -2,10 +2,10 @@ using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using xAiApi.Models;
|
||||
using System.Threading;
|
||||
using xIdentityHelper;
|
||||
using xAiApi.Constants;
|
||||
using System.Threading;
|
||||
using xAiApi.Interfaces;
|
||||
using xAiModels.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xAiModels.Interfaces;
|
||||
using xAiApi.Configurations;
|
||||
@@ -18,8 +18,6 @@ using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xAiApi.Interfaces.Extractors;
|
||||
using System.Runtime.CompilerServices;
|
||||
using xAiModels.Constants;
|
||||
|
||||
namespace xAiApi.Providers
|
||||
{
|
||||
@@ -36,11 +34,10 @@ namespace xAiApi.Providers
|
||||
{
|
||||
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 IXAiEmbeddingService embeddingService;
|
||||
private readonly IXFileContentExtractor fileContentExtractor;
|
||||
|
||||
/// <summary>
|
||||
@@ -51,17 +48,15 @@ namespace xAiApi.Providers
|
||||
public XAiRAGService(
|
||||
IXTextChunker textChunker,
|
||||
IXFileProvider fileProvider,
|
||||
IXDefaultAiService aiService,
|
||||
IXAiDataProvider dataProvider,
|
||||
ILogger<XAiRAGService> logger,
|
||||
XAiApiConfiguration configuration,
|
||||
IXDefaultEmbeddingService embeddingService,
|
||||
IXAiEmbeddingService embeddingService,
|
||||
IXFileContentExtractor fileContentExtractor
|
||||
)
|
||||
{
|
||||
//
|
||||
this.logger = logger;
|
||||
this.aiService = aiService;
|
||||
this.textChunker = textChunker;
|
||||
this.fileProvider = fileProvider;
|
||||
this.dataProvider = dataProvider;
|
||||
@@ -201,13 +196,28 @@ namespace xAiApi.Providers
|
||||
|
||||
//
|
||||
// Handle File Save ...
|
||||
await fileProvider.Upload(
|
||||
var uploadedFile = await fileProvider.Upload(
|
||||
file: file,
|
||||
userInfo: userInfo,
|
||||
connectionId: connectionId,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
// Add Reference File to Prompt Message ...
|
||||
if (scope.ScopeId.HasValue)
|
||||
{
|
||||
//
|
||||
await fileProvider.AddReference(
|
||||
userInfo: userInfo,
|
||||
id: uploadedFile.Id,
|
||||
connectionId: connectionId,
|
||||
cancellationToken: cancellationToken,
|
||||
providedFor: scope.Scope.GetStringValue(),
|
||||
forProvidedId: scope.ScopeId.Value.ToString()
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// Embed in Batches ...
|
||||
var vectors = await EmbedChunks(
|
||||
@@ -360,123 +370,6 @@ namespace xAiApi.Providers
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ask a Question with RAG (Retrieve from DB then Generate) ...
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<XAiDocumentAnswer> AskWithRAGAsync(
|
||||
XAiKnowledgeAskRequest request,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Retrieve (Validates Request) ...
|
||||
var context = await RetrieveAsync(
|
||||
request: request,
|
||||
userInfo: userInfo,
|
||||
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 ...
|
||||
/// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ...
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async IAsyncEnumerable<XAiDocumentAnswerChunk> AskWithRAGAsEnumerable(
|
||||
XAiKnowledgeAskRequest request,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
[EnumeratorCancellation]
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Retrieve (Validates Request) ...
|
||||
var context = await RetrieveAsync(
|
||||
request: request,
|
||||
userInfo: userInfo,
|
||||
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
|
||||
|
||||
//
|
||||
@@ -701,12 +594,125 @@ namespace xAiApi.Providers
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
/// <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 (with Scope Metadata) ...
|
||||
/// </summary>
|
||||
private async Task<IList<XAiVectorDto>> EmbedChunks(
|
||||
XAiKnowledgeScopeDescriptor scope,
|
||||
IList<XTextChunk> chunks,
|
||||
string type,
|
||||
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
|
||||
{
|
||||
//
|
||||
Type = type,
|
||||
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(),
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataType] = type,
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(),
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty,
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
#region Scope ...
|
||||
/// <summary>
|
||||
/// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ...
|
||||
/// </summary>
|
||||
private static XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope)
|
||||
private XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope)
|
||||
{
|
||||
//
|
||||
var result = scope ?? XAiKnowledgeScopeDescriptor.User();
|
||||
@@ -916,7 +922,10 @@ namespace xAiApi.Providers
|
||||
/// Document Chunk Prefix: "{scopePrefix}{fileName}#" ...
|
||||
/// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
|
||||
/// </summary>
|
||||
private string GetDocumentChunkPrefix(string scopePrefix, string fileName)
|
||||
private string GetDocumentChunkPrefix(
|
||||
string scopePrefix,
|
||||
string fileName
|
||||
)
|
||||
{
|
||||
return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}";
|
||||
}
|
||||
@@ -1005,120 +1014,7 @@ namespace xAiApi.Providers
|
||||
//
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
/// <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 (with Scope Metadata) ...
|
||||
/// </summary>
|
||||
private async Task<IList<XAiVectorDto>> EmbedChunks(
|
||||
XAiKnowledgeScopeDescriptor scope,
|
||||
IList<XTextChunk> chunks,
|
||||
string type,
|
||||
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
|
||||
{
|
||||
//
|
||||
Type = type,
|
||||
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(),
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataType] = type,
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(),
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty,
|
||||
[XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user