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.
This commit is contained in:
2026-10-29 19:59:18 +03:30
parent d3ecc8feea
commit 37d4e622e9
15 changed files with 940 additions and 610 deletions
+88 -45
View File
@@ -3,9 +3,11 @@ 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;
@@ -45,10 +47,13 @@ namespace xAiApi.Controllers
//
#region Ingest ...
/// <summary>
/// Ingest Files into Current User's Knowledge Base:
/// 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>
@@ -56,6 +61,8 @@ namespace xAiApi.Controllers
[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
@@ -80,9 +87,9 @@ namespace xAiApi.Controllers
files: files,
userInfo: userInfo,
connectionId: connectionId,
knowledgeType: knowledgeType,
replaceExisting: replaceExisting,
cancellationToken: cancellationToken
cancellationToken: cancellationToken,
scope: BuildScope(scope, scopeId, knowledgeType)
);
//
@@ -155,56 +162,58 @@ namespace xAiApi.Controllers
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
{
//
// Validate ...
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
//
// Configure SSE Response Headers ...
Response.Headers["X-Accel-Buffering"] = "no";
Response.Headers["Connection"] = "keep-alive";
Response.Headers["Content-Type"] = "text/event-stream";
Response.Headers["Cache-Control"] = "no-cache, no-store";
await using var enumerator = ragService
.AskWithRAGAsEnumerable(
request: request,
userInfo: userInfo,
cancellationToken: cancellationToken
)
.GetAsyncEnumerator(cancellationToken);
//
// Disable Response Buffering ...
var responseBodyFeature = HttpContext.Features
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
responseBodyFeature?.DisableBuffering();
// Pull First Item before Starting Stream, so Scope / Ownership /
// Retrieval Errors are Returned as Regular Http Errors ...
var hasItem = await enumerator.MoveNextAsync();
//
var enumerable = ragService.AskWithRAGAsEnumerable(
request: request,
userInfo: userInfo,
cancellationToken: cancellationToken
);
// Configure SSE Response ...
Response.PrepareSseResponse();
//
await foreach (var chunk in enumerable)
while (hasItem)
{
//
if (chunk.IsNullOrDefault())
var chunk = enumerator.Current;
if (!chunk.IsNullOrDefault())
{
continue;
await WriteChunk(chunk, cancellationToken);
}
//
await WriteChunk(chunk, cancellationToken);
hasItem = await enumerator.MoveNextAsync();
}
//
await Response.Body.FlushAsync(cancellationToken);
await Response.WriteSseDoneAsync(cancellationToken);
}
catch (OperationCanceledException)
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
{
// Client Disconnected ...
}
@@ -212,16 +221,16 @@ namespace xAiApi.Controllers
{
//
Logger.LogError(ex, "Knowledge: AskStream Failed");
try
if (!Response.HasStarted)
{
//
if (!Response.HasStarted)
{
Response.StatusCode = StatusCodes.Status500InternalServerError;
}
await Response.Body.FlushAsync(CancellationToken.None);
var result = GetExceptionActionResult(ex);
await result.ExecuteResultAsync(ControllerContext);
return;
}
catch { /* ignore */ }
//
await Response.WriteSseErrorAsync(ex.Message);
}
}
#endregion
@@ -229,12 +238,18 @@ namespace xAiApi.Controllers
//
#region Documents ...
/// <summary>
/// List Ingested Documents of Current User ...
/// 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
)
{
@@ -247,7 +262,8 @@ namespace xAiApi.Controllers
//
var result = await ragService.LoadDocumentsAsync(
userInfo: userInfo,
cancellationToken: cancellationToken
cancellationToken: cancellationToken,
scope: BuildScope(scope, scopeId, knowledgeType)
);
//
@@ -262,14 +278,18 @@ namespace xAiApi.Controllers
}
/// <summary>
/// Remove All Vectors of a Document ...
/// 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
)
{
@@ -287,7 +307,8 @@ namespace xAiApi.Controllers
var result = await ragService.RemoveDocumentAsync(
fileName: fileName,
userInfo: userInfo,
cancellationToken: cancellationToken
cancellationToken: cancellationToken,
scope: BuildScope(scope, scopeId, null)
);
//
@@ -304,18 +325,40 @@ namespace xAiApi.Controllers
//
#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 async Task WriteChunk(
private Task WriteChunk(
XAiDocumentAnswerChunk chunk,
CancellationToken cancellationToken
)
{
//
var payload = chunk.ToJSON(camelCase: true);
await Response.WriteAsync($"data: {payload}\n\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
return Response.WriteSseEventAsync(
data: chunk,
cancellationToken: cancellationToken
);
}
#endregion
}