Files
xSaherElmAiApi/Controllers/KnowledgeController.cs
T
saherelm 37d4e622e9 Implement RAG Scopes, Remove ProxyController, Fix Pipeline Order and SSE Format
- RAG: real scopes with identifiers conversation/{id}/, project/{id}/, user/{ownerId}/, global/;
- RAG: ownership checks via GetProject/GetConversation; Global write requires admin role;
- RAG: tiered retrieval Conversation -> Project -> User -> Global (single embedding, dedup, TopK fill);
- RAG: apply Type filter, sanitize file names, enforce MaxFilesPerIngest/MaxFileSizeBytes/MaxDocumentsPerScope;
- RAG: store scope/scopeId/type/ownerId metadata; return it in documents and sources;
- RAG: add MigrateLegacyVectorsAsync + POST /Knowledge/MigrateLegacy ({ownerId}/... -> user/{ownerId}/...);
- Knowledge API: scope/scopeId on Ingest, Documents, DELETE Documents;
- Remove ProxyController (root route "{modelName}/{path}" + AllowAnonymous hijacked all 2-segment paths);
- Startup: ExceptionHandler("/error") + HSTS outside Development; Swagger only in Development;
  static files before routing; CORS before model proxy; add /error endpoint;
- SSE: all stream endpoints use xHttpService XSseExtensions; validate before streaming;
  pre-stream errors return proper HTTP status; remove "Connection: keep-alive";
- Use xAiModels.Constants for XAiKnowledgeScope / Knowledge constants / XOpenAINoKey;
- Register XAiVectorEntityRegisterar in XAiApiDbContext;
- XCodeFileContentExtractor: actually read stream content; drop hard-coded "book.epub".
BREAKING: AskTextStream emits data: {"text":"..."}; AskStream emits data: {json}; both end with event: done.
2026-10-29 19:59:18 +03:30

367 lines
12 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 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>
/// 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
}
}