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:
2026-10-30 19:46:20 +03:30
parent 37d4e622e9
commit ad8ea9c1dd
22 changed files with 343 additions and 655 deletions
+1
View File
@@ -11,6 +11,7 @@ namespace xAiApi.Constants
public const string XDILogTag = "XAiApi";
//
public const string XAiApiRagPromptName = "ChatWithDocuments";
public const string XAiApiIntroductionPromptName = "Introduction";
public const string XAiApiContentExtractionPromptName = "ContentExtraction";
+2 -2
View File
@@ -54,7 +54,7 @@ namespace xAiApi.Controllers
/// <summary>
/// Embedding Service ...
/// </summary>
private readonly IXDefaultEmbeddingService embeddingService;
private readonly IXAiEmbeddingService embeddingService;
/// <summary>
/// File Context Extractor Service ...
@@ -68,8 +68,8 @@ namespace xAiApi.Controllers
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XAiApiConfiguration apiConfiguration,
IXAiEmbeddingService embeddingService,
XValidationProvider validationProvider,
IXDefaultEmbeddingService embeddingService,
ILogger<ChatWithDocumentsController> logger,
IXFileContentExtractor fileContentExtractor
) : base(logger, appConfiguration, identityProvider, validationProvider)
+7 -7
View File
@@ -10,20 +10,20 @@ namespace xAiApi.Controllers
{
[Authorize]
[Route("[controller]")]
public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase<IXDefaultEmbeddingService>
public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase<IXAiEmbeddingService>
{
public DefaultEmbeddingController(
ILogger<DefaultEmbeddingController> logger,
IXDefaultEmbeddingService aiService,
IXAiEmbeddingService embeddingService,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger,
aiService,
appConfiguration,
identityProvider,
validationProvider
logger: logger,
appConfiguration: appConfiguration,
identityProvider: identityProvider,
embeddingService: embeddingService,
validationProvider: validationProvider
)
{ }
}
-132
View File
@@ -40,7 +40,6 @@ namespace xAiApi.Controllers
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{
//
this.ragService = ragService;
}
@@ -104,137 +103,6 @@ namespace xAiApi.Controllers
}
#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,
userInfo: userInfo,
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
)
{
//
// Validate (before Stream Starts -> Proper Http Error) ...
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
{
Response.StatusCode = StatusCodes.Status400BadRequest;
Response.ContentType = "application/json; charset=utf-8";
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
return;
}
//
try
{
//
var userInfo = await GetUserInfo();
//
await using var enumerator = ragService
.AskWithRAGAsEnumerable(
request: request,
userInfo: userInfo,
cancellationToken: cancellationToken
)
.GetAsyncEnumerator(cancellationToken);
//
// Pull First Item before Starting Stream, so Scope / Ownership /
// Retrieval Errors are Returned as Regular Http Errors ...
var hasItem = await enumerator.MoveNextAsync();
//
// Configure SSE Response ...
Response.PrepareSseResponse();
//
while (hasItem)
{
//
var chunk = enumerator.Current;
if (!chunk.IsNullOrDefault())
{
await WriteChunk(chunk, cancellationToken);
}
//
hasItem = await enumerator.MoveNextAsync();
}
//
await Response.WriteSseDoneAsync(cancellationToken);
}
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
{
// Client Disconnected ...
}
catch (Exception ex)
{
//
Logger.LogError(ex, "Knowledge: AskStream Failed");
if (!Response.HasStarted)
{
//
var result = GetExceptionActionResult(ex);
await result.ExecuteResultAsync(ControllerContext);
return;
}
//
await Response.WriteSseErrorAsync(ex.Message);
}
}
#endregion
//
#region Documents ...
/// <summary>
@@ -8,32 +8,32 @@ using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using xIdentityService.Controllers;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
[Authorize]
[Route("[controller]")]
public abstract class XAiEmbeddingServiceControllerBase<TAiService> : XAiServiceControllerBase<TAiService>, IXAiEmbeddingServiceControllerBase
where TAiService : IXAiEmbeddingServiceBase
public abstract class XAiEmbeddingServiceControllerBase<TEmbeddingService> : XBaseIdentityApiV1Controller, IXAiEmbeddingServiceControllerBase
where TEmbeddingService : IXAiEmbeddingServiceBase
{
private readonly TAiService aiService;
private readonly TEmbeddingService embeddingService;
protected XAiEmbeddingServiceControllerBase(
ILogger logger,
TAiService aiService,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
XValidationProvider validationProvider,
TEmbeddingService embeddingService
) : base(
logger,
aiService,
appConfiguration,
identityProvider,
validationProvider
)
{
this.aiService = aiService;
this.embeddingService = embeddingService;
}
/// <summary>
@@ -57,7 +57,7 @@ namespace xAiApi.Controllers
ValidationProvider.NotEmpty(content);
//
var result = await aiService.Embedding(
var result = await embeddingService.Embedding(
content: content,
cancellationToken: cancellationToken
);
@@ -94,7 +94,7 @@ namespace xAiApi.Controllers
ValidationProvider.NotZeroChilds(batch);
//
var result = await aiService.Embeddings(
var result = await embeddingService.Embeddings(
batch: batch,
cancellationToken: cancellationToken
);
+2 -2
View File
@@ -689,9 +689,9 @@ namespace xAiApi.Controllers
prompt: request.Prompt,
ownerId: userInfo.UserId,
connectionId: connectionId,
projectId: request.ProjectId,
projectId: request.ProjectId.Value,
cancellationToken: cancellationToken,
conversationId: request.ConversationId
conversationId: request.ConversationId.Value
);
//
+14 -5
View File
@@ -73,6 +73,20 @@ namespace xAiApi.DI
source.AddSingleton(configuration);
}
/// <summary>
/// Register Rag Service ...
/// </summary>
/// <param name="source"></param>
public static void AddXRagService(
this IServiceCollection source
)
{
//
// Persistent RAG (Knowledge over XAiVector Table) ...
source.AddScoped<IXAiEmbeddingService, XAiEmbeddingService>();
source.AddScoped<IXAiRAGService, XAiRAGService>();
}
/// <summary>
/// Register Ai Services ...
/// </summary>
@@ -83,12 +97,7 @@ namespace xAiApi.DI
{
//
source.AddScoped<IXDefaultAiService, XDefaultAiService>();
source.AddScoped<IXDefaultEmbeddingService, XDefaultEmbeddingService>();
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
//
// Persistent RAG (Knowledge over XAiVector Table) ...
source.AddScoped<IXAiRAGService, XAiRAGService>();
}
/// <summary>
+2 -2
View File
@@ -74,8 +74,8 @@ namespace xAiApi.Extensions
!source.IsNullOrDefault() &&
!source.Prompt.IsNullOrEmpty() &&
!source.SessionId.IsDefaultGuid() &&
(!source.TopK.HasValue || source.TopK.Value > 0) &&
(!source.MinScore.HasValue || (source.MinScore.Value >= -1f && source.MinScore.Value <= 1f));
source.TopK.HasValue && source.TopK.Value > 0 &&
source.MinScore.HasValue && source.MinScore.Value >= -1f && source.MinScore.Value <= 1f;
//
return result;
+5
View File
@@ -0,0 +1,5 @@
namespace xAiApi.Interfaces
{
public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase
{ }
}
+2 -3
View File
@@ -1,15 +1,14 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using OllamaSharp;
using System.Collections.Generic;
namespace xAiApi.Interfaces
{
/// <summary>
/// Base Embedding Provider Service ...
/// </summary>
public interface IXAiEmbeddingServiceBase : IXAiServiceBase
public interface IXAiEmbeddingServiceBase // : IXAiServiceBase
{
/// <summary>
/// Embedding Specified String ...
@@ -1,11 +1,11 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace xAiApi.Interfaces
{
public interface IXAiEmbeddingServiceControllerBase : IXAiServiceControllerBase
public interface IXAiEmbeddingServiceControllerBase
{
/// <summary>
/// Request For Embedding Specified String ...
-27
View File
@@ -48,33 +48,6 @@ namespace xAiApi.Interfaces
CancellationToken cancellationToken = default
);
/// <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>
Task<XAiDocumentAnswer> AskWithRAGAsync(
XAiKnowledgeAskRequest request,
XUserClaimsInfoDto userInfo = null,
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="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IAsyncEnumerable<XAiDocumentAnswerChunk> AskWithRAGAsEnumerable(
XAiKnowledgeAskRequest request,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// List Ingested Documents of Specified Scope ...
/// </summary>
+2 -2
View File
@@ -258,8 +258,8 @@ namespace xAiApi.Interfaces
Task<XAiMessageDto> AskAsync(
string prompt,
string ownerId,
Guid projectId,
Guid conversationId,
Guid? projectId,
Guid? conversationId,
string connectionId = null,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
-5
View File
@@ -1,5 +0,0 @@
namespace xAiApi.Interfaces
{
public interface IXDefaultEmbeddingService : IXAiEmbeddingServiceBase
{ }
}
+5 -4
View File
@@ -33,7 +33,8 @@ namespace xAiApi.Models
string type = null
) => new()
{
Type = type,
//
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
ScopeId = null,
Scope = XAiKnowledgeScope.User,
};
@@ -47,7 +48,7 @@ namespace xAiApi.Models
string type = null
) => new()
{
Type = type,
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
ScopeId = null,
Scope = XAiKnowledgeScope.Global,
};
@@ -63,7 +64,7 @@ namespace xAiApi.Models
string type = null
) => new()
{
Type = type,
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
ScopeId = projectId,
Scope = XAiKnowledgeScope.Project,
};
@@ -79,7 +80,7 @@ namespace xAiApi.Models
string type = null
) => new()
{
Type = type,
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
ScopeId = conversationId,
Scope = XAiKnowledgeScope.Conversation,
};
+128 -184
View File
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using xModels.Dtos;
using xAiApi.Models;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
@@ -11,14 +12,12 @@ using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Interfaces;
using xAiModels.Extensions;
using xAiService.Constants;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using xAiService.Extensions;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xFileService.Interfaces;
using Microsoft.Extensions.AI;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
@@ -43,7 +42,7 @@ namespace xAiApi.Providers
/// </summary>
public XAiModelDescriptor Descriptor { get; }
private readonly IXFileProvider fileProvider;
private readonly IXAiRAGService ragProvider;
private readonly IXAiDataProvider dataProvider;
private readonly ILogger<XAIServiceBase> logger;
private readonly XAiApiConfiguration configuration;
@@ -51,7 +50,7 @@ namespace xAiApi.Providers
private readonly IXFileContentExtractor fileContentExtractor;
protected XAIServiceBase(
IXFileProvider fileProvider,
IXAiRAGService ragProvider,
IXAiDataProvider dataProvider,
ILogger<XAIServiceBase> logger,
XAiApiConfiguration configuration,
@@ -62,7 +61,7 @@ namespace xAiApi.Providers
{
//
this.logger = logger;
this.fileProvider = fileProvider;
this.ragProvider = ragProvider;
this.dataProvider = dataProvider;
this.configuration = configuration;
this.validationProvider = validationProvider;
@@ -377,56 +376,6 @@ namespace xAiApi.Providers
//
return result;
}
/// <summary>
/// Convert Context Chunks to a Numbered Text Block ...
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
protected virtual string BuildContextBlock(
IEnumerable<XAiVectorSearchResult> context
)
{
//
var result = "(no context)";
//
var items = context?
.Where(c =>
!c.IsNullOrDefault() &&
!c.Text.IsNullOrEmpty()
)
.ToList() ?? [];
if (!items.HasChild())
{
return result;
}
//
var index = 1;
var builder = new System.Text.StringBuilder();
foreach (var item in items)
{
//
var identifier = item.Identifier.IsNullOrEmpty()
? item.Id.ToString()
: item.Identifier;
//
builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})");
builder.AppendLine(item.Text.Trim());
builder.AppendLine("----");
//
index++;
}
//
result = builder.ToString();
//
return result;
}
#endregion
//
@@ -874,8 +823,8 @@ namespace xAiApi.Providers
public virtual async Task<XAiMessageDto> AskAsync(
string prompt,
string ownerId,
Guid projectId,
Guid conversationId,
Guid? projectId,
Guid? conversationId,
string connectionId = null,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
@@ -893,7 +842,7 @@ namespace xAiApi.Providers
//
// Check Project ...
XAiProjectDto project = null;
if (projectId.IsDefaultGuid())
if (!projectId.HasValue || projectId.Value.IsDefaultGuid())
{
//
project = await dataProvider.GetDefaultProject(
@@ -909,7 +858,7 @@ namespace xAiApi.Providers
{
//
project = await dataProvider.GetProject(
id: projectId,
id: projectId.Value,
fillConversations: false,
fillConversationMessages: false,
cancellationToken: cancellationToken
@@ -923,12 +872,12 @@ namespace xAiApi.Providers
//
// Check Conversation ...
XAiConversationDto conversation = null;
if (conversationId.IsDefaultGuid())
if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid())
{
//
conversation = await dataProvider.GetDefaultConversation(
ownerId: ownerId,
projectId: projectId,
projectId: projectId.Value,
connectionId: connectionId,
cancellationToken: cancellationToken
);
@@ -940,8 +889,8 @@ namespace xAiApi.Providers
{
//
conversation = await dataProvider.GetConversation(
id: conversationId,
fillMessages: false,
id: conversationId.Value,
cancellationToken: cancellationToken
);
}
@@ -951,38 +900,58 @@ namespace xAiApi.Providers
}
//
// Reading Messages ...
var messages = await dataProvider.LoadMessages(
conversationId: conversationId,
// Ingest Files based on Conversation ...
XAiKnowledgeIngestResult ingestResult;
if (files.HasChild())
{
//
try
{
//
ingestResult = await ragProvider
.IngestAsync(
files: files,
userInfo: userInfo,
replaceExisting: true,
connectionId: connectionId,
cancellationToken: cancellationToken,
scope: XAiKnowledgeScopeDescriptor.Conversation(
type: null,
conversationId: conversationId.Value
)
);
}
catch { }
}
//
// Prepare Knowledge Request ...
var knowledgeRequest = new XAiKnowledgeAskRequest
{
Prompt = prompt,
IncludeUser = true,
IncludeGlobal = true,
ProjectId = projectId,
ConversationId = conversationId
};
var context = await ragProvider.RetrieveAsync(
userInfo: userInfo,
request: knowledgeRequest,
cancellationToken: cancellationToken
);
//
// Upload Files ...
IEnumerable<xFileService.Models.Dtos.XFileDto> uploadedFiles = null;
if (files.HasChild())
{
//
// Validate User Info ...
if (userInfo.IsNullOrDefault())
{
XException.InvalidArgs.Throw();
}
//
// Upload Files ...
uploadedFiles = await fileProvider.Upload(
files: files,
userInfo: userInfo,
connectionId: connectionId,
cancellationToken: cancellationToken
);
}
// Reading Messages ...
var messages = await dataProvider.LoadMessages(
conversationId: conversationId.Value,
cancellationToken: cancellationToken
);
//
// Handle Memory ...
IList<ChatMessage> history = await PrepareMemory(
project: project,
context: context,
messages: messages,
cancellationToken: cancellationToken
);
@@ -995,102 +964,23 @@ namespace xAiApi.Providers
OwnerId = ownerId,
Role = XAiChatRole.User,
CreatedOn = DateTime.UtcNow,
ConversationId = conversationId,
ConversationId = conversationId.Value,
ConversationTitle = conversation.Title
};
//
// Attached Uploaded File Id's as Meta Data ...
if (uploadedFiles.HasChild())
{
//
var fileIds = uploadedFiles.Select(f => f.Id).ToList();
promptMessage.MetaDatas = new Dictionary<string, object>
{
{ XAiServiceConstants.XMetaDataFileIdsIdentifier, fileIds }
}.ToJSON();
}
//
// Save Prompt Message ...
promptMessage = await dataProvider.AddMessage(
item: promptMessage,
connectionId: connectionId,
conversationId: conversationId,
conversationId: conversationId.Value,
cancellationToken: cancellationToken
);
//
// Since Prompt Message Has Id now, we can Attach Uploaded Files to it ...
IList<AIContent> fileContents = [];
if (uploadedFiles.HasChild())
{
//
foreach (var uf in uploadedFiles)
{
//
try
{
//
// Add Reference File to Prompt Message ...
await fileProvider.AddReference(
id: uf.Id,
userInfo: userInfo,
connectionId: connectionId,
forProvidedId: promptMessage.Id,
cancellationToken: cancellationToken,
providedFor: XAiServiceConstants.XAiMessageFilesIdentifier
);
//
// Handle File Content Extraction and Attach to Prompt Message ...
var fileDescriptor = await fileProvider.GetFileDescriptor(
id: uf.Id,
cancellationToken: cancellationToken
);
if (fileDescriptor == null || fileDescriptor.Stream == null)
{
continue;
}
//
var extractionResult = await fileContentExtractor.ExtractRichAsync(
fileStream: fileDescriptor.Stream,
fileName: uf.FileName ?? uf.Name,
mimeType: fileDescriptor.MIMEType,
cancellationToken: cancellationToken
);
if (extractionResult.IsValid())
{
//
var contents = extractionResult.ToAIContents();
fileContents = [.. fileContents, .. contents];
//
// ذخیره Metadata برای ردیابی
logger.LogInformation(
"File {FileName} extracted successfully. Text: {HasText}, Images: {ImageCount}, Fallback: {UsedFallback}",
uf.FileName,
!string.IsNullOrEmpty(extractionResult.Text),
extractionResult.Images.Count,
extractionResult.UsedImageFallback
);
}
//
fileDescriptor.Stream.Dispose();
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to extract content from file: {FileName}", uf.FileName);
}
}
}
//
// Converts to ChatMessage ...
var promptChatMessage = promptMessage
.ToChatMessages(fileContents);
.ToChatMessages(additionalContents: []);
//
// Ask Questions From LLM ...
@@ -1108,13 +998,13 @@ namespace xAiApi.Providers
OwnerId = ownerId,
CreatedOn = DateTime.UtcNow,
Role = XAiChatRole.Assistant,
ConversationId = conversationId,
ConversationId = conversationId.Value,
ConversationTitle = conversation.Title
};
result = await dataProvider.AddMessage(
item: result,
connectionId: connectionId,
conversationId: conversationId,
conversationId: conversationId.Value,
cancellationToken: cancellationToken
);
@@ -1330,11 +1220,13 @@ namespace xAiApi.Providers
/// </summary>
/// <param name="project"></param>
/// <param name="messages"></param>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<IList<ChatMessage>> PrepareMemory(
XAiProjectDto project,
IEnumerable<XAiMessageDto> messages,
IEnumerable<XAiVectorSearchResult> context = null,
CancellationToken cancellationToken = default
)
{
@@ -1343,35 +1235,37 @@ namespace xAiApi.Providers
//
// Retrieve Introduction Prompt ...
var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName);
if (introductionPrompt.IsNullOrEmpty())
if (ragPrompt.IsNullOrEmpty() ||
introductionPrompt.IsNullOrEmpty()
)
{
XException.InvalidData.Throw();
}
//
var introductionMessage = new ChatMessage(
role: ChatRole.System,
content: introductionPrompt
);
//
result.Add(introductionMessage);
var contextBlock = BuildContextBlock(context);
var systemText =
$"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" +
$"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
$"Context:{Environment.NewLine}{contextBlock}";
//
// Apply Project Prompt as System Text ...
if (!project.IsNullOrDefault() &&
!project.Prompt.IsNullOrEmpty())
{
//
// TODO: Handle Project Files Here ...
var projectMessage = new ChatMessage(
role: ChatRole.System,
contents: [new TextContent(project.Prompt)]
);
result.Add(projectMessage);
systemText += $"Project:{Environment.NewLine}{project.Prompt}";
}
//
// Add System Message ...
result
.Add(new ChatMessage(ChatRole.System, systemText));
//
// Attach Message ...
if (messages.HasChild())
{
//
@@ -1386,6 +1280,56 @@ namespace xAiApi.Providers
return result;
}
/// <summary>
/// Convert Context Chunks to a Numbered Text Block ...
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private string BuildContextBlock(
IEnumerable<XAiVectorSearchResult> context
)
{
//
var result = "(no context)";
//
var items = context?
.Where(c =>
!c.IsNullOrDefault() &&
!c.Text.IsNullOrEmpty()
)
.ToList() ?? [];
if (!items.HasChild())
{
return result;
}
//
var index = 1;
var builder = new System.Text.StringBuilder();
foreach (var item in items)
{
//
var identifier = item.Identifier.IsNullOrEmpty()
? item.Id.ToString()
: item.Identifier;
//
builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})");
builder.AppendLine(item.Text.Trim());
builder.AppendLine("----");
//
index++;
}
//
result = builder.ToString();
//
return result;
}
/// <summary>
/// Ask Quetion from LLM ...
/// </summary>
@@ -1,25 +1,22 @@
using xAiApi.Constants;
using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using xFileService.Interfaces;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using xCommons.Providers;
namespace xAiApi.Providers
{
public class XDefaultEmbeddingService : XAiEmbeddingServiceBase, IXDefaultEmbeddingService
public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService
{
public XDefaultEmbeddingService(
IXFileProvider fileProvider,
public XAiEmbeddingService(
IXAiDataProvider dataProvider,
XAiApiConfiguration configuration,
ILogger<XAiEmbeddingService> logger,
XValidationProvider validationProvider,
ILogger<XDefaultEmbeddingService> logger,
IXFileContentExtractor fileContentExtractor
) : base(
fileProvider,
dataProvider,
configuration,
validationProvider,
+11 -13
View File
@@ -17,7 +17,6 @@ using xAiModels.Interfaces;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using xFileService.Interfaces;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
@@ -29,28 +28,23 @@ namespace xAiApi.Providers
/// <summary>
/// Base Embedding Provider Service ...
/// </summary>
public abstract class XAiEmbeddingServiceBase : XAIServiceBase, IXAiEmbeddingServiceBase
public abstract class XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase
{
private readonly IXFileProvider fileProvider;
private readonly string embeddingModelName;
private readonly XAiModelDescriptor descriptor;
private readonly IXAiDataProvider dataProvider;
private readonly XAiApiConfiguration configuration;
private readonly XValidationProvider validationProvider;
private readonly ILogger<XAiEmbeddingServiceBase> logger;
private readonly IXFileContentExtractor fileContentExtractor;
protected XAiEmbeddingServiceBase(
IXFileProvider fileProvider,
IXAiDataProvider dataProvider,
XAiApiConfiguration configuration,
XValidationProvider validationProvider,
ILogger<XAiEmbeddingServiceBase> logger,
IXFileContentExtractor fileContentExtractor,
string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
) : base(
fileProvider,
dataProvider,
logger,
configuration,
validationProvider,
fileContentExtractor,
null
)
{
//
@@ -61,10 +55,14 @@ namespace xAiApi.Providers
XException.InvalidConfiguration.Throw();
}
this.fileProvider = fileProvider;
this.dataProvider = dataProvider;
this.configuration = configuration;
this.validationProvider = validationProvider;
//
this.logger = logger;
this.fileContentExtractor = fileContentExtractor;
this.embeddingModelName = embeddingModelName;
}
/// <summary>
+139 -243
View File
@@ -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
}
}
+2 -3
View File
@@ -3,7 +3,6 @@ using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using xFileService.Interfaces;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
@@ -12,14 +11,14 @@ namespace xAiApi.Providers
public class XDefaultAiService : XAIServiceBase, IXDefaultAiService
{
public XDefaultAiService(
IXFileProvider fileProvider,
IXAiRAGService ragProvider,
IXAiDataProvider dataProvider,
ILogger<XDefaultAiService> logger,
XAiApiConfiguration configuration,
XValidationProvider validationProvider,
IXFileContentExtractor fileContentExtractor
) : base(
fileProvider,
ragProvider,
dataProvider,
logger,
configuration,
+2 -3
View File
@@ -4,7 +4,6 @@ using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using Microsoft.Extensions.AI;
using xFileService.Interfaces;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
@@ -13,7 +12,7 @@ namespace xAiApi.Providers
public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService
{
public XDefaultThinkingAiService(
IXFileProvider fileProvider,
IXAiRAGService ragProvider,
IXAiDataProvider dataProvider,
ILogger<XAIServiceBase> logger,
XAiApiConfiguration configuration,
@@ -22,7 +21,7 @@ namespace xAiApi.Providers
ReasoningEffort effort = ReasoningEffort.Medium,
ReasoningOutput output = ReasoningOutput.Full
) : base(
fileProvider,
ragProvider,
dataProvider,
logger,
configuration,
+4
View File
@@ -196,6 +196,10 @@ namespace xAiApi
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
services.AddXAiChatWithDocuments();
//
// Persistent RAG (Knowledge over XAiVector Table) ...
services.AddXRagService();
//
// Register Default AI Services ...
services.AddXAiServices();