Files
xSaherElmAiApi/Controllers/KnowledgeController.cs
T
saherelm ad8ea9c1dd 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.
2026-10-30 19:46:20 +03:30

235 lines
7.6 KiB
C#

using System;
using xAiApi.Models;
using System.Threading;
using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Constants;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using xHttpService.Extensions;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Controllers;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
/// <summary>
/// Knowledge (Persistent RAG over XAiVector Table) Controller ...
/// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete
/// </summary>
[Authorize]
[Route("[controller]")]
public class KnowledgeController : XBaseIdentityApiV1Controller
{
/// <summary>
/// Persistent RAG Service ...
/// </summary>
private readonly IXAiRAGService ragService;
public KnowledgeController(
IXAiRAGService ragService,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
ILogger<KnowledgeController> logger,
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{
this.ragService = ragService;
}
//
#region Ingest ...
/// <summary>
/// Ingest Files into a Knowledge Scope:
/// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
/// </summary>
/// <param name="files"></param>
/// <param name="scope">Target Scope: User (default) / Project / Conversation / Global (Admin)</param>
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
/// <param name="knowledgeType">Optional Knowledge Type / Domain</param>
/// <param name="replaceExisting">Replace Previously Stored Vectors of Same File (default true)</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Ingest")]
[Consumes("multipart/form-data")]
public async Task<ActionResult<XAiKnowledgeIngestResult>> Ingest(
[FromForm] IFormFileCollection files,
[FromForm] XAiKnowledgeScope scope = XAiKnowledgeScope.Global,
[FromForm] Guid? scopeId = null,
[FromForm] string knowledgeType = null,
[FromForm] bool replaceExisting = true,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (!files.HasChild())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
var result = await ragService.IngestAsync(
files: files,
userInfo: userInfo,
connectionId: connectionId,
replaceExisting: replaceExisting,
cancellationToken: cancellationToken,
scope: BuildScope(scope, scopeId, knowledgeType)
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Documents ...
/// <summary>
/// List Ingested Documents of a Knowledge Scope ...
/// </summary>
/// <param name="scope">User (default) / Project / Conversation / Global</param>
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
/// <param name="knowledgeType">Optional Knowledge Type Filter</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("Documents")]
public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
[FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User,
[FromQuery] Guid? scopeId = null,
[FromQuery] string knowledgeType = null,
CancellationToken cancellationToken = default
)
{
//
try
{
//
var userInfo = await GetUserInfo();
//
var result = await ragService.LoadDocumentsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken,
scope: BuildScope(scope, scopeId, knowledgeType)
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Remove All Vectors of a Document in a Knowledge Scope ...
/// </summary>
/// <param name="fileName"></param>
/// <param name="scope">User (default) / Project / Conversation / Global (Admin)</param>
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Removed Vectors</returns>
[HttpDelete("Documents")]
public async Task<ActionResult<int>> DeleteDocument(
[FromQuery] string fileName,
[FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User,
[FromQuery] Guid? scopeId = null,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
ValidationProvider.NotEmpty(fileName);
//
var userInfo = await GetUserInfo();
//
var result = await ragService.RemoveDocumentAsync(
fileName: fileName,
userInfo: userInfo,
cancellationToken: cancellationToken,
scope: BuildScope(scope, scopeId, null)
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Private ...
/// <summary>
/// Build Scope Descriptor from Request Params ...
/// </summary>
private XAiKnowledgeScopeDescriptor BuildScope(
XAiKnowledgeScope scope,
Guid? scopeId,
string knowledgeType
)
{
//
var result = new XAiKnowledgeScopeDescriptor
{
Scope = scope,
ScopeId = scopeId,
Type = knowledgeType,
};
//
return result;
}
/// <summary>
/// Write a SSE Event ...
/// </summary>
private Task WriteChunk(
XAiDocumentAnswerChunk chunk,
CancellationToken cancellationToken
)
{
//
return Response.WriteSseEventAsync(
data: chunk,
cancellationToken: cancellationToken
);
}
#endregion
}
}