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:
@@ -1,8 +1,9 @@
|
||||
using System;
|
||||
using xModels.Dtos;
|
||||
using System.Text.Json;
|
||||
using xIdentityHelper;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xAiApi.Extensions;
|
||||
using xAiApi.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Extensions;
|
||||
@@ -10,6 +11,7 @@ using xAiModels.Extensions;
|
||||
using xAiModels.Models.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xHttpService.Extensions;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -18,7 +20,6 @@ using xIdentityService.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xIdentityService.Controllers;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using System.Linq;
|
||||
|
||||
namespace xAiApi.Controllers
|
||||
{
|
||||
@@ -53,8 +54,8 @@ namespace xAiApi.Controllers
|
||||
/// <param name="question"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[HttpGet("AskText")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public virtual async Task<ActionResult<string>> AskText(
|
||||
[FromQuery] string question,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -90,39 +91,27 @@ namespace xAiApi.Controllers
|
||||
/// <param name="question"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[HttpGet("AskTextStream")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public virtual async Task AskTextStream(
|
||||
[FromQuery] string question,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||
if (question.IsNullOrEmpty())
|
||||
{
|
||||
await WriteStreamValidationError();
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
ValidationProvider.NotEmpty(question);
|
||||
|
||||
//
|
||||
// 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";
|
||||
|
||||
//
|
||||
// Disable response buffering ...
|
||||
var responseBodyFeature = HttpContext.Features
|
||||
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
|
||||
responseBodyFeature?.DisableBuffering();
|
||||
|
||||
//
|
||||
// Stream Response ...
|
||||
var jsonOptions = new JsonSerializerOptions
|
||||
{
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
// Configure SSE Response ...
|
||||
Response.PrepareSseResponse();
|
||||
|
||||
//
|
||||
var enumerable = aiService.AskTextAsEnumerable(
|
||||
@@ -131,37 +120,58 @@ namespace xAiApi.Controllers
|
||||
);
|
||||
|
||||
//
|
||||
// Format: data: {"text":"..."}\n\n
|
||||
await foreach (var chunk in enumerable)
|
||||
{
|
||||
//
|
||||
// Skip empty chunks ...
|
||||
// Skip Empty Chunks ...
|
||||
if (string.IsNullOrEmpty(chunk))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
// Build SSE message ...
|
||||
// Format: data: <json>\n\n
|
||||
// var payload = JsonSerializer.Serialize(
|
||||
// new { text = chunk },
|
||||
// jsonOptions
|
||||
// );
|
||||
var payload = chunk;
|
||||
|
||||
//
|
||||
// Write SSE Event ...
|
||||
await Response.WriteAsync($"{payload}\n\n", cancellationToken);
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseEventAsync(
|
||||
data: new { text = chunk },
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||
{
|
||||
await Response.Body.FlushAsync();
|
||||
// Client Disconnected ...
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
Logger.LogError(ex, "AskTextStream Failed");
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
await result.ExecuteResultAsync(ControllerContext);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
await Response.WriteSseErrorAsync(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write Validation Error for Streaming Endpoints (before Stream Starts) ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[NonAction]
|
||||
protected async Task WriteStreamValidationError()
|
||||
{
|
||||
//
|
||||
Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
Response.ContentType = "application/json; charset=utf-8";
|
||||
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
|
||||
}
|
||||
#endregion
|
||||
|
||||
@@ -174,6 +184,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("Projects")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<IEnumerable<XAiProjectDto>>> LoadProjects(
|
||||
[FromQuery] bool includeDefaults = false,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -211,6 +222,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="projectId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Projects/{projectId}/Conversations")]
|
||||
public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations(
|
||||
[FromRoute] Guid projectId,
|
||||
@@ -255,6 +267,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="conversationId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Conversations/{conversationId}/Messages")]
|
||||
public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages(
|
||||
[FromRoute] Guid conversationId,
|
||||
@@ -300,6 +313,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("Projects/Query")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XQueryResult<XAiProjectDto>>> QueryProjects(
|
||||
[FromQuery] XQuery query,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -337,6 +351,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="query"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Projects/{projectId}/Conversations/Query")]
|
||||
public async Task<ActionResult<XQueryResult<XAiConversationDto>>> QueryConversations(
|
||||
[FromRoute] Guid projectId,
|
||||
@@ -377,6 +392,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="query"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Conversations/{conversationId}/Messages/Query")]
|
||||
public async Task<ActionResult<XQueryResult<XAiMessageDto>>> QueryMessages(
|
||||
[FromRoute] Guid conversationId,
|
||||
@@ -420,6 +436,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("Projects")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XAiProjectDto>> CreateProject(
|
||||
[FromBody] XAiProjectDto item,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -473,6 +490,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="item"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPost("Projects/{projectId}/Conversations")]
|
||||
public async Task<ActionResult<XAiConversationDto>> CreateConversation(
|
||||
[FromRoute] Guid projectId,
|
||||
@@ -535,9 +553,10 @@ namespace xAiApi.Controllers
|
||||
/// <returns></returns>
|
||||
[HttpPost("ExtractContent")]
|
||||
[Consumes("multipart/form-data")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<string>> ExtractContent(
|
||||
[FromForm] IFormFileCollection files,
|
||||
[FromForm] string extractors = null,
|
||||
[FromForm] string extractors = "*",
|
||||
CancellationToken cancellationToken = default
|
||||
) {
|
||||
//
|
||||
@@ -588,6 +607,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("Ask")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<string>> Ask(
|
||||
[FromBody] XAiResponseRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -637,37 +657,30 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("AskStream")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task AskStream(
|
||||
[FromBody] XAiResponseRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||
if (!request.IsValid())
|
||||
{
|
||||
await WriteStreamValidationError();
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!request.IsValid())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
var connectionId = GetConnectionId();
|
||||
|
||||
//
|
||||
// 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";
|
||||
|
||||
//
|
||||
// Disable response buffering ...
|
||||
var responseBodyFeature = HttpContext.Features
|
||||
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
|
||||
responseBodyFeature?.DisableBuffering();
|
||||
// Configure SSE Response ...
|
||||
Response.PrepareSseResponse();
|
||||
|
||||
//
|
||||
// TODO: Reading Fiels Form Collection and Attach it ...
|
||||
@@ -682,6 +695,7 @@ namespace xAiApi.Controllers
|
||||
);
|
||||
|
||||
//
|
||||
// Format: data: {json}\n\n
|
||||
await foreach (var resp in enumerable)
|
||||
{
|
||||
//
|
||||
@@ -692,20 +706,33 @@ namespace xAiApi.Controllers
|
||||
}
|
||||
|
||||
//
|
||||
var payload = resp.ToJSON(camelCase: true);
|
||||
|
||||
//
|
||||
// Write SSE Event ...
|
||||
await Response.WriteAsync($"{payload}", cancellationToken);
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseEventAsync(
|
||||
data: resp,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||
{
|
||||
await Response.Body.FlushAsync();
|
||||
// Client Disconnected ...
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
Logger.LogError(ex, "AskStream Failed");
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
await result.ExecuteResultAsync(ControllerContext);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
await Response.WriteSseErrorAsync(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,6 +744,7 @@ namespace xAiApi.Controllers
|
||||
/// <returns></returns>
|
||||
[HttpPost("AskWithFiles")]
|
||||
[Consumes("multipart/form-data")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<string>> AskWithFiles(
|
||||
[FromForm] XAiResponseRequest request,
|
||||
[FromForm] IFormFileCollection files,
|
||||
|
||||
Reference in New Issue
Block a user