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:
+128
-184
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user