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:
@@ -10,10 +10,11 @@ using xAiApi.Configurations;
|
||||
using xExceptions.Constants;
|
||||
using xAiModels.Models.Dtos;
|
||||
using System.Threading.Tasks;
|
||||
using xHttpService.Extensions;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Interfaces;
|
||||
using xIdentityService.Controllers;
|
||||
using xAiApi.Interfaces.Extractors;
|
||||
@@ -314,15 +315,19 @@ namespace xAiApi.Controllers
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||
if (!request.IsValid())
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!request.IsValid())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
Response.ContentType = "application/json; charset=utf-8";
|
||||
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
var ownerId = userInfo.UserId;
|
||||
@@ -339,17 +344,8 @@ namespace xAiApi.Controllers
|
||||
var context = await Retrieve(request, ownerId, cancellationToken);
|
||||
|
||||
//
|
||||
// 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();
|
||||
|
||||
//
|
||||
// First Event: Sources ...
|
||||
@@ -365,6 +361,7 @@ namespace xAiApi.Controllers
|
||||
//
|
||||
if (!hasContext)
|
||||
{
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -397,6 +394,11 @@ namespace xAiApi.Controllers
|
||||
Text = string.Empty,
|
||||
IsFinal = true
|
||||
}, cancellationToken);
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||
{
|
||||
// Client Disconnected ...
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -404,9 +406,14 @@ namespace xAiApi.Controllers
|
||||
Logger.LogError(ex, "ChatWithDocuments: AskStream Failed");
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
await result.ExecuteResultAsync(ControllerContext);
|
||||
return;
|
||||
}
|
||||
await Response.Body.FlushAsync();
|
||||
|
||||
//
|
||||
await Response.WriteSseErrorAsync(ex.Message);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
@@ -447,11 +454,10 @@ namespace xAiApi.Controllers
|
||||
CreatedAtUtc = session.CreatedAtUtc,
|
||||
LastAccessAtUtc = session.LastAccessAtUtc,
|
||||
ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl),
|
||||
Files = vectors
|
||||
.Select(v => GetMetadata(v.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName))
|
||||
Files = [.. vectors
|
||||
.Select(v => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName))
|
||||
.Where(f => !f.IsNullOrEmpty())
|
||||
.Distinct()
|
||||
.ToList()
|
||||
.Distinct()]
|
||||
};
|
||||
|
||||
//
|
||||
@@ -647,7 +653,7 @@ namespace xAiApi.Controllers
|
||||
.Select(c =>
|
||||
{
|
||||
//
|
||||
var chunkIndexText = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataChunkIndex);
|
||||
var chunkIndexText = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataChunkIndex);
|
||||
var text = c.Text ?? string.Empty;
|
||||
var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength);
|
||||
|
||||
@@ -658,7 +664,7 @@ namespace xAiApi.Controllers
|
||||
Identifier = c.Identifier,
|
||||
Snippet = text.Substring(0, snippetLength),
|
||||
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null,
|
||||
FileName = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName)
|
||||
FileName = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)
|
||||
};
|
||||
})
|
||||
.ToList();
|
||||
@@ -667,36 +673,19 @@ namespace xAiApi.Controllers
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Safe Metadata Reader ...
|
||||
/// </summary>
|
||||
private string GetMetadata(
|
||||
IDictionary<string, string> metadata,
|
||||
string key
|
||||
)
|
||||
{
|
||||
//
|
||||
if (metadata.IsNullOrDefault() || !metadata.TryGetValue(key, out var value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user