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
-21
View File
@@ -20,26 +20,5 @@ namespace xAiApi.Constants
public const string XAiDefaultVisionModelName = "Qwen";
public const string XAiDefaultThinkingModelName = "Qwen";
public const string XAiEmbeddingPromptName = "Embedding";
//
public const string XOpenAINoKey = "no-key-required";
//
// Knowledge (Persistent RAG) ...
public const string XAiDefaultKnowledgeType = "XAiKnowledge";
public const string XAiKnowledgeSeparator = "/";
public const string XAiKnowledgeOwnerSeparator = "/";
public const string XAiKnowledgeChunkSeparator = "#";
public const string XAiKnowledgeGlobalPrefix = "global";
public const string XAiKnowledgeProjectPrefix = "project";
public const string XAiKnowledgeConversationPrefix = "conversation";
//
// Knowledge Metadata Keys ...
public const string XAiKnowledgeMetadataType = "type";
public const string XAiKnowledgeMetadataScope = "scope";
public const string XAiKnowledgeMetadataScopeId = "scopeId";
public const string XAiKnowledgeMetadataOwnerId = "ownerId";
public const string XAiKnowledgeMetadataIngestedAtUtc = "ingestedAtUtc";
}
}
-12
View File
@@ -1,12 +0,0 @@
namespace xAiApi.Constants
{
/// <summary>
/// Knowledge Base Scope (Where Ingested Vectors are Visible) ...
/// </summary>
public enum XAiKnowledgeScope
{
Conversation = 0,
Project = 1,
Global = 2,
}
}
+37 -48
View File
@@ -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
}
+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
}
-248
View File
@@ -1,248 +0,0 @@
using System;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading;
using xAiApi.Extensions;
using xCommons.Providers;
using xExceptions.Models;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using xIdentityService.Controllers;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
[AllowAnonymous]
public class ProxyController : XBaseIdentityApiController
{
private readonly IServiceProvider serviceProvider;
private readonly XAiApiConfiguration apiConfiguration;
private readonly IHttpClientFactory httpClientFactory;
public ProxyController(
ILogger<ProxyController> logger,
IServiceProvider serviceProvider,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XAiApiConfiguration apiConfiguration,
IHttpClientFactory httpClientFactory,
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{
this.serviceProvider = serviceProvider;
this.apiConfiguration = apiConfiguration;
this.httpClientFactory = httpClientFactory;
}
[AcceptVerbs("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD")]
[Route("{modelName}/{path}")]
public async Task Proxy(
[FromRoute] string modelName,
[FromRoute] string path = null,
object body = null,
CancellationToken cancellationToken = default
)
{
//
var descriptor = apiConfiguration.GetModel(modelName);
if (!descriptor.IsValid())
{
//
var error = XException.NotFound.ToXError();
error.Message = $"{error.Message}: {modelName}' is not configured.";
await WriteJsonError(
StatusCodes.Status502BadGateway,
error.ToJSON()
);
//
return;
}
//
var targetUrl = BuildTargetUrl(
remainingPath: path,
modelName: modelName,
query: Request.QueryString
);
var method = new HttpMethod(Request.Method);
using var upstreamRequest = new HttpRequestMessage(method, targetUrl);
//
// Attach Body ...
if (!body.IsNull())
{
//
var json = body.ToJSON();
upstreamRequest.Content = new StringContent(
json,
Encoding.UTF8,
"application/json"
);
}
//
Request.CopyHeaders(
exceptions: null,
dest: upstreamRequest
);
//
var client = httpClientFactory.CreateClient("XAiModelProxy");
client.Timeout = Timeout.InfiniteTimeSpan;
HttpResponseMessage upstreamResponse;
try
{
//
upstreamResponse = await client.SendAsync(
upstreamRequest,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken
);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
//
Logger.LogError(ex, "Proxy failed for model {Model}", modelName);
var error = XException.ActionFailed.ToXError();
error.Message = $"{error.Message}: Upstream model is unavailable.";
await WriteJsonError(
StatusCodes.Status502BadGateway,
error.ToJSON()
);
return;
}
//
using (upstreamResponse)
{
//
if (!upstreamResponse.IsSuccessStatusCode)
{
//
var statusCode = (int)upstreamResponse.StatusCode;
//
XError error;
string errorBody;
try
{
//
errorBody = await upstreamResponse.Content
.ReadAsStringAsync();
//
error = errorBody.IsXError()
? errorBody.ToXError()
: XException.BadRequest.ToXError();
}
catch
{
error = XException.BadRequest.ToXError();
}
//
await WriteJsonError(
statusCode: statusCode,
message: error.ToJSON()
);
//
return;
}
//
upstreamResponse.CopyHeaders(
exceptions: null,
response: Response
);
Response.StatusCode = (int)upstreamResponse.StatusCode;
//
using var responseStream = await upstreamResponse.Content.ReadAsStreamAsync();
await responseStream.CopyToAsync(Response.Body, cancellationToken);
}
}
// ============================================================
// Helpers
// ============================================================
private async Task WriteJsonError(
int statusCode,
string message
)
{
//
Response.StatusCode = statusCode;
Response.ContentType = "application/json; charset=utf-8";
//
await Response.WriteAsync(message);
}
private Uri BuildTargetUrl(
string modelName,
string remainingPath = null,
QueryString query = default
)
{
//
// Validate ...
var isValid =
!modelName.IsNullOrEmpty() &&
!apiConfiguration.IsNull() &&
!apiConfiguration.ProxyConfiguration.IsNull() &&
!apiConfiguration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty();
if (!isValid)
{
XException.InvalidArgs.Throw();
}
//
var baseUrls = serviceProvider.GetApplicationUrls().ToArray();
if (!baseUrls.HasChild())
{
XException.InvalidData.Throw();
}
//
var baseUrl = baseUrls[0];
//
var path = $"{baseUrl}/{apiConfiguration.ProxyConfiguration.RoutePrefix.TrimStart('/')}/{modelName}";
if (!remainingPath.IsNullOrEmpty())
{
path += "/" + remainingPath.TrimStart('/');
}
//
var builder = new UriBuilder(path)
{
Query = query.HasValue
? query.Value.TrimStart('?')
: string.Empty
};
//
var result = builder.Uri;
//
return result;
}
}
}
+23 -5
View File
@@ -1,9 +1,12 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using xCommons.Configurations;
using xCommons.Controllers;
using xCommons.Providers;
using xCommons.Extensions;
using xCommons.Controllers;
using xExceptions.Constants;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
@@ -41,5 +44,20 @@ namespace xAiApi.Controllers
//
return Ok(message);
}
/// <summary>
/// Global Exception Handler Endpoint (Production) ...
/// Returns a Generic Error without Leaking Exception Details ...
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[Route("error")]
[ApiExplorerSettings(IgnoreApi = true)]
public virtual ActionResult Error()
{
//
var error = XException.ActionFailed.ToXError();
return StatusCode(StatusCodes.Status500InternalServerError, error);
}
}
}
+98 -70
View File
@@ -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,
+1
View File
@@ -38,6 +38,7 @@ namespace xAiApi.Database
nameof(XTagEntityRegisterar),
nameof(XFileEntityRegisterar),
nameof(XStringEntityRegisterar),
nameof(XAiVectorEntityRegisterar),
nameof(XAiMessageEntityRegisterar),
nameof(XAiProjectEntityRegisterar),
nameof(XAiConversationEntityRegisterar),
+1 -1
View File
@@ -288,7 +288,7 @@ namespace xAiApi.Extensions
//
// Instance Ollama Client using Custom HttpCLient ...
var openAiClient = new OpenAIClient(
new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiApiConstants.XOpenAINoKey : apiKey),
new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : apiKey),
new OpenAIClientOptions
{
Endpoint = url,
+26 -15
View File
@@ -11,15 +11,16 @@ namespace xAiApi.Interfaces
/// <summary>
/// Persistent RAG Service over XAiVector Table:
/// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
/// Isolation is Scope Based (Conversation / Project / User / Global) ...
/// </summary>
public interface IXAiRAGService
{
/// <summary>
/// Ingest Files into Owner's Knowledge Base:
/// Ingest Files into Specified Knowledge Scope:
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
/// </summary>
/// <param name="files"></param>
/// <param name="knowledgeType"></param>
/// <param name="scope">Target Scope (Null = User Scope)</param>
/// <param name="userInfo"></param>
/// <param name="connectionId"></param>
/// <param name="replaceExisting"></param>
@@ -27,7 +28,7 @@ namespace xAiApi.Interfaces
/// <returns></returns>
Task<XAiKnowledgeIngestResult> IngestAsync(
IFormFileCollection files,
string knowledgeType = null,
XAiKnowledgeScopeDescriptor scope = null,
XUserClaimsInfoDto userInfo = null,
string connectionId = null,
bool replaceExisting = true,
@@ -35,21 +36,15 @@ namespace xAiApi.Interfaces
);
/// <summary>
/// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ...
/// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="request"></param>
/// <param name="userInfo"></param>
/// <param name="topK"></param>
/// <param name="minScore"></param>
/// <param name="fileName">Optional: Restrict to a Specific File</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<XAiVectorSearchResult>> RetrieveAsync(
string prompt,
XAiKnowledgeAskRequest request,
XUserClaimsInfoDto userInfo = null,
int? topK = null,
float? minScore = null,
string fileName = null,
CancellationToken cancellationToken = default
);
@@ -81,25 +76,41 @@ namespace xAiApi.Interfaces
);
/// <summary>
/// List Ingested Documents of Owner ...
/// List Ingested Documents of Specified Scope ...
/// </summary>
/// <param name="scope">Target Scope (Null = User Scope)</param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
XAiKnowledgeScopeDescriptor scope = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// Remove All Vectors of a Document ...
/// Remove All Vectors of a Document in Specified Scope ...
/// </summary>
/// <param name="fileName"></param>
/// <param name="scope">Target Scope (Null = User Scope)</param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Removed Vectors</returns>
Task<int> RemoveDocumentAsync(
string fileName,
XAiKnowledgeScopeDescriptor scope = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
/// Idempotent: Returns 0 when Nothing Left to Migrate ...
/// </summary>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Migrated Vectors</returns>
Task<int> MigrateLegacyVectorsAsync(
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
@@ -113,4 +124,4 @@ namespace xAiApi.Interfaces
IEnumerable<XAiVectorSearchResult> context
);
}
}
}
+58 -13
View File
@@ -1,10 +1,5 @@
using xAiApi.Constants;
using xAiApi.Constants;
using System;
using xAiApi.Constants;
using xAiModels.Constants;
using System.Collections.Generic;
namespace xAiApi.Models
@@ -17,10 +12,10 @@ namespace xAiApi.Models
/// <summary>
/// Scope Kind ...
/// </summary>
public XAiKnowledgeScope Scope { get; set; }
public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User;
/// <summary>
/// Scope Identifier (ProjectId / ConversationId) - Null for Global ...
/// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ...
/// </summary>
public Guid? ScopeId { get; set; }
@@ -29,20 +24,60 @@ namespace xAiApi.Models
/// </summary>
public string Type { get; set; }
//
public static XAiKnowledgeScopeDescriptor Global(string type = null) => new()
/// <summary>
/// Create User Scope Knowledge Descriptor ...
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static XAiKnowledgeScopeDescriptor User(
string type = null
) => new()
{
Type = type,
ScopeId = null,
Scope = XAiKnowledgeScope.User,
};
/// <summary>
/// Create Global Scope Knowledge Descriptor ...
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static XAiKnowledgeScopeDescriptor Global(
string type = null
) => new()
{
Type = type,
ScopeId = null,
Scope = XAiKnowledgeScope.Global,
};
public static XAiKnowledgeScopeDescriptor Project(Guid projectId, string type = null) => new()
/// <summary>
/// Create Project Scope Knowledge Descriptor ...
/// </summary>
/// <param name="projectId"></param>
/// <param name="type"></param>
/// <returns></returns>
public static XAiKnowledgeScopeDescriptor Project(
Guid projectId,
string type = null
) => new()
{
Type = type,
ScopeId = projectId,
Scope = XAiKnowledgeScope.Project,
};
public static XAiKnowledgeScopeDescriptor Conversation(Guid conversationId, string type = null) => new()
/// <summary>
/// Create Conversational Scope Knowledge Descriptor ...
/// </summary>
/// <param name="conversationId"></param>
/// <param name="type"></param>
/// <returns></returns>
public static XAiKnowledgeScopeDescriptor Conversation(
Guid conversationId,
string type = null
) => new()
{
Type = type,
ScopeId = conversationId,
@@ -98,7 +133,7 @@ namespace xAiApi.Models
/// <summary>
/// Ask Request over Persistent Knowledge Base ...
/// Retrieval is Tiered: Conversation -> Project -> Global (Each Tier Fills Remaining TopK) ...
/// Retrieval is Tiered: Conversation -> Project -> User -> Global (Each Tier Fills Remaining TopK) ...
/// </summary>
public class XAiKnowledgeAskRequest
{
@@ -118,6 +153,16 @@ namespace xAiApi.Models
/// </summary>
public Guid? ProjectId { get; set; }
/// <summary>
/// Include Personal (User) Knowledge Tier (default true) ...
/// </summary>
public bool IncludeUser { get; set; } = true;
/// <summary>
/// Include Global Knowledge Tier (default true) ...
/// </summary>
public bool IncludeGlobal { get; set; } = true;
/// <summary>
/// Optional: Restrict Retrieval to a Knowledge Type / Domain ...
/// </summary>
@@ -72,7 +72,7 @@ namespace xAiApi.Providers.Extractors
//
var result = await ExtractRichAsync(
fileStream,
"book.epub",
string.Empty,
mimeType,
cancellationToken
);
@@ -112,12 +112,18 @@ namespace xAiApi.Providers.Extractors
detectEncodingFromByteOrderMarks: true
);
//
var content = await reader.ReadToEndAsync();
//
// Normalize line endings for consistent downstream processing ...
result.Text = result.Text?
content = content?
.Replace("\r\n", "\n")
.Replace("\r", "\n");
//
result.Text = content;
//
return result;
}
+1 -1
View File
@@ -195,7 +195,7 @@ namespace xAiApi.Providers
case XAiModelProviderType.OpenAI:
//
var openAiClient = new OpenAIClient(
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiApiConstants.XOpenAINoKey : descriptor.ApiKey),
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : descriptor.ApiKey),
new OpenAIClientOptions
{
Endpoint = new Uri(descriptor.Url),
+573 -114
View File
@@ -1,7 +1,9 @@
using System;
using System.IO;
using System.Linq;
using xAiApi.Models;
using System.Threading;
using xIdentityHelper;
using xAiApi.Constants;
using xAiApi.Interfaces;
using xCommons.Extensions;
@@ -17,12 +19,18 @@ using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using System.Runtime.CompilerServices;
using xAiModels.Constants;
namespace xAiApi.Providers
{
/// <summary>
/// Persistent RAG Service over XAiVector Table ...
/// Isolation: Identifier = "{ownerId}/{fileName}#{chunkIndex}" ...
/// Isolation (Identifier Layout):
/// Conversation: "conversation/{conversationId}/{fileName}#{i}"
/// Project : "project/{projectId}/{fileName}#{i}"
/// User : "user/{ownerId}/{fileName}#{i}"
/// Global : "global/{fileName}#{i}"
/// Retrieval is Tiered: Conversation -> Project -> User -> Global ...
/// </summary>
public class XAiRAGService : IXAiRAGService
{
@@ -35,6 +43,11 @@ namespace xAiApi.Providers
private readonly IXDefaultEmbeddingService embeddingService;
private readonly IXFileContentExtractor fileContentExtractor;
/// <summary>
/// Characters which are not Allowed in File Name Part of Identifier ...
/// </summary>
private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#'];
public XAiRAGService(
IXTextChunker textChunker,
IXFileProvider fileProvider,
@@ -60,11 +73,11 @@ namespace xAiApi.Providers
//
#region Ingest ...
/// <summary>
/// Ingest Files into Owner's Knowledge Base:
/// Ingest Files into Specified Knowledge Scope:
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
/// </summary>
/// <param name="files"></param>
/// <param name="knowledgeType"></param>
/// <param name="scope"></param>
/// <param name="userInfo"></param>
/// <param name="connectionId"></param>
/// <param name="replaceExisting"></param>
@@ -72,7 +85,7 @@ namespace xAiApi.Providers
/// <returns></returns>
public async Task<XAiKnowledgeIngestResult> IngestAsync(
IFormFileCollection files,
string knowledgeType = null,
XAiKnowledgeScopeDescriptor scope = null,
XUserClaimsInfoDto userInfo = null,
string connectionId = null,
bool replaceExisting = true,
@@ -81,21 +94,42 @@ namespace xAiApi.Providers
{
//
// Validate ...
if (!files.HasChild() || userInfo.IsNullOrDefault())
if (!files.HasChild() || !IsValidUser(userInfo))
{
XException.InvalidArgs.Throw();
}
//
// Normalize ...
if (knowledgeType.IsNullOrEmpty())
var rag = configuration.RAGDescriptor;
if (rag.MaxFilesPerIngest > 0 && files.Count > rag.MaxFilesPerIngest)
{
knowledgeType = XAiApiConstants.XAiDefaultKnowledgeType;
XException.InvalidArgs.Throw();
}
//
var result = new XAiKnowledgeIngestResult();
var ingestedAtUtc = DateTime.UtcNow.ToString("O");
//
// Resolve & Authorize Scope (Write) ...
scope = NormalizeScope(scope);
await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);
//
var knowledgeType = scope.Type.IsNullOrEmpty()
? XAiModelsConstants.XAiDefaultKnowledgeType
: scope.Type;
var scopePrefix = GetScopePrefix(scope, userInfo);
//
var result = new XAiKnowledgeIngestResult
{
Type = knowledgeType,
Scope = scope.Scope,
ScopeId = scope.ScopeId,
};
var ingestedAt = DateTime.UtcNow;
var ingestedAtUtc = ingestedAt.ToString("O");
//
// Existing Documents (for MaxDocumentsPerScope Limit) ...
var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken);
//
foreach (var file in files)
@@ -110,6 +144,36 @@ namespace xAiApi.Providers
continue;
}
//
// Size Limit ...
if (rag.MaxFileSizeBytes > 0 && file.Length > rag.MaxFileSizeBytes)
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
var fileName = NormalizeFileName(file.FileName);
if (fileName.IsNullOrEmpty())
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
// Documents per Scope Limit (Global Unlimited; Re-Ingest of Existing Doc Allowed) ...
var isNewDocument = !existingDocuments.Contains(fileName);
if (
isNewDocument &&
scope.Scope != XAiKnowledgeScope.Global &&
rag.MaxDocumentsPerScope > 0 &&
existingDocuments.Count >= rag.MaxDocumentsPerScope
)
{
result.SkippedFiles.Add(file.FileName);
continue;
}
//
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
if (!fileContentExtractor.CanExtract(mimeType))
@@ -127,9 +191,8 @@ namespace xAiApi.Providers
}
//
// Chunk with Owner Scoped Source => Identifier = "{ownerId}/{fileName}#{index}" ...
var documentPrefix = GetDocumentPrefix(userInfo.UserId, file.FileName);
var chunks = textChunker.Chunk(text, documentPrefix);
// Chunk with Scoped Source => Identifier = "{scopePrefix}{fileName}#{index}" ...
var chunks = textChunker.Chunk(text, $"{scopePrefix}{fileName}");
if (!chunks.HasChild())
{
result.SkippedFiles.Add(file.FileName);
@@ -148,10 +211,11 @@ namespace xAiApi.Providers
//
// Embed in Batches ...
var vectors = await EmbedChunks(
scope: scope,
chunks: chunks,
fileName: fileName,
mimeType: mimeType,
type: knowledgeType,
fileName: file.FileName,
ownerId: userInfo.UserId,
ingestedAtUtc: ingestedAtUtc,
cancellationToken: cancellationToken
@@ -164,7 +228,7 @@ namespace xAiApi.Providers
//
result.ReplacedCount += await dataProvider.RemoveVectorsAsync(
cancellationToken: cancellationToken,
identifierPrefix: GetDocumentChunkPrefix(userInfo.UserId, file.FileName)
identifierPrefix: GetDocumentChunkPrefix(scopePrefix, fileName)
);
}
@@ -176,20 +240,25 @@ namespace xAiApi.Providers
);
//
existingDocuments.Add(fileName);
result.FilesCount++;
result.ChunksCount += storedCount;
result.Documents.Add(new XAiKnowledgeDocumentInfo
{
FileName = fileName,
MimeType = mimeType,
FileName = file.FileName,
Type = knowledgeType,
Scope = scope.Scope,
ScopeId = scope.ScopeId,
ChunksCount = storedCount,
IngestedAtUtc = DateTime.Parse(ingestedAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind)
OwnerId = userInfo.UserId,
IngestedAtUtc = ingestedAt,
});
//
logger.LogInformation(
"Knowledge: Ingested {FileName} for {OwnerId} with {Chunks} Chunks",
file.FileName, userInfo.UserId, storedCount
"Knowledge: Ingested {FileName} into {Scope}:{ScopeId} by {OwnerId} with {Chunks} Chunks",
fileName, scope.Scope, scope.ScopeId, userInfo.UserId, storedCount
);
}
@@ -198,44 +267,50 @@ namespace xAiApi.Providers
}
#endregion
//
#region Ask ...
/// <summary>
/// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ...
/// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
/// Each Tier Fills Remaining TopK; Duplicates are Removed ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="request"></param>
/// <param name="userInfo"></param>
/// <param name="topK"></param>
/// <param name="minScore"></param>
/// <param name="fileName">Optional: Restrict to a Specific File</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IList<XAiVectorSearchResult>> RetrieveAsync(
string prompt,
XAiKnowledgeAskRequest request,
XUserClaimsInfoDto userInfo = null,
int? topK = null,
float? minScore = null,
string fileName = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (prompt.IsNullOrEmpty() || userInfo.IsNullOrDefault())
if (
request.IsNullOrDefault() ||
request.Prompt.IsNullOrEmpty() ||
!IsValidUser(userInfo)
)
{
XException.InvalidArgs.Throw();
}
//
var rag = configuration.RAGDescriptor;
var effectiveTopK = Math.Clamp(topK ?? rag.DefaultTopK, 1, rag.MaxTopK);
var effectiveMinScore = minScore ?? rag.DefaultMinScore;
var effectiveTopK = Math.Clamp(request.TopK ?? rag.DefaultTopK, 1, rag.MaxTopK);
var effectiveMinScore = request.MinScore ?? rag.DefaultMinScore;
//
// Embed Question ...
// Resolve Tiers (with Ownership Checks) before Embedding ...
var tiers = await ResolveTiers(request, userInfo, cancellationToken);
if (!tiers.HasChild())
{
return [];
}
//
// Embed Question (Once) ...
var queryEmbedding = await embeddingService.Embedding(
content: prompt,
content: request.Prompt,
cancellationToken: cancellationToken
);
if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
@@ -244,21 +319,45 @@ namespace xAiApi.Providers
}
//
// Search in DB (Scoped to Owner or Owner + File) ...
var prefix = fileName.IsNullOrEmpty()
? GetOwnerPrefix(userInfo.UserId)
: GetDocumentChunkPrefix(userInfo.UserId, fileName);
var searchResult = await dataProvider.SearchVectorsAsync(
type: null,
topK: effectiveTopK,
identifierPrefix: prefix,
minScore: effectiveMinScore,
queryEmbedding: queryEmbedding,
cancellationToken: cancellationToken
);
var fileName = NormalizeFileName(request.FileName);
var result = new List<XAiVectorSearchResult>();
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var tier in tiers)
{
//
var remaining = effectiveTopK - result.Count;
if (remaining <= 0)
{
break;
}
//
var scopePrefix = GetScopePrefix(tier, userInfo);
var prefix = fileName.IsNullOrEmpty()
? scopePrefix
: GetDocumentChunkPrefix(scopePrefix, fileName);
//
var searchResult = await dataProvider.SearchVectorsAsync(
topK: remaining,
type: request.Type,
identifierPrefix: prefix,
minScore: effectiveMinScore,
queryEmbedding: queryEmbedding,
cancellationToken: cancellationToken
);
//
foreach (var item in searchResult ?? [])
{
if (seen.Add(item.Identifier ?? item.Id.ToString()))
{
result.Add(item);
}
}
}
//
var result = searchResult?.ToList() ?? [];
return result;
}
@@ -276,20 +375,10 @@ namespace xAiApi.Providers
)
{
//
// Validate ...
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Retrieve ...
// Retrieve (Validates Request) ...
var context = await RetrieveAsync(
request: request,
userInfo: userInfo,
topK: request.TopK,
prompt: request.Prompt,
minScore: request.MinScore,
fileName: request.FileName,
cancellationToken: cancellationToken
);
@@ -328,25 +417,15 @@ namespace xAiApi.Providers
public async IAsyncEnumerable<XAiDocumentAnswerChunk> AskWithRAGAsEnumerable(
XAiKnowledgeAskRequest request,
XUserClaimsInfoDto userInfo = null,
[EnumeratorCancellation]
[EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Retrieve ...
// Retrieve (Validates Request) ...
var context = await RetrieveAsync(
request: request,
userInfo: userInfo,
topK: request.TopK,
prompt: request.Prompt,
minScore: request.MinScore,
fileName: request.FileName,
cancellationToken: cancellationToken
);
@@ -403,46 +482,60 @@ namespace xAiApi.Providers
//
#region Documents ...
/// <summary>
/// List Ingested Documents of Owner ...
/// List Ingested Documents of Specified Scope ...
/// </summary>
/// <param name="scope"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
XAiKnowledgeScopeDescriptor scope = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (userInfo.IsNullOrDefault())
if (!IsValidUser(userInfo))
{
XException.InvalidArgs.Throw();
}
//
// Resolve & Authorize Scope (Read) ...
scope = NormalizeScope(scope);
await EnsureAccess(scope, userInfo, isWrite: false, cancellationToken);
//
var vectors = await dataProvider.LoadVectorsAsync(
type: scope.Type,
includeEmbedding: false,
cancellationToken: cancellationToken,
identifierPrefix: GetOwnerPrefix(userInfo.UserId)
identifierPrefix: GetScopePrefix(scope, userInfo)
);
//
var rag = configuration.RAGDescriptor;
var result = (vectors ?? [])
.GroupBy(v => v.Metadata.GetMetadata(rag.MetadataFileName) ?? v.Identifier)
.GroupBy(v => v.Metadata.GetMetadata(rag.MetadataFileName).IsNullOrEmpty()
? v.Identifier
: v.Metadata.GetMetadata(rag.MetadataFileName))
.Select(g =>
{
//
var first = g.First();
var ingestedText = first.Metadata.GetMetadata(XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc);
var ingestedText = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc);
//
return new XAiKnowledgeDocumentInfo
{
FileName = g.Key,
Type = first.Type,
Scope = scope.Scope,
ChunksCount = g.Count(),
ScopeId = scope.ScopeId,
MimeType = first.Metadata.GetMetadata(rag.MetadataMimeType),
OwnerId = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataOwnerId),
IngestedAtUtc = DateTime.TryParse(
ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt
) ? dt : null
@@ -456,33 +549,114 @@ namespace xAiApi.Providers
}
/// <summary>
/// Remove All Vectors of a Document ...
/// Remove All Vectors of a Document in Specified Scope ...
/// </summary>
/// <param name="fileName"></param>
/// <param name="scope"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Removed Vectors</returns>
public async Task<int> RemoveDocumentAsync(
string fileName,
XAiKnowledgeScopeDescriptor scope = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (
fileName.IsNullOrEmpty() ||
userInfo.IsNullOrDefault() ||
userInfo.UserId.IsNullOrEmpty()
)
var normalizedFileName = NormalizeFileName(fileName);
if (normalizedFileName.IsNullOrEmpty() || !IsValidUser(userInfo))
{
XException.InvalidArgs.Throw();
}
//
// Resolve & Authorize Scope (Write) ...
scope = NormalizeScope(scope);
await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);
//
var result = await dataProvider.RemoveVectorsAsync(
cancellationToken: cancellationToken,
identifierPrefix: GetDocumentChunkPrefix(userInfo.UserId, fileName)
identifierPrefix: GetDocumentChunkPrefix(GetScopePrefix(scope, userInfo), normalizedFileName)
);
//
return result;
}
/// <summary>
/// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
/// Store First then Remove Legacy (no Data Loss on Failure); Idempotent ...
/// </summary>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns>Count of Migrated Vectors</returns>
public async Task<int> MigrateLegacyVectorsAsync(
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!IsValidUser(userInfo))
{
XException.InvalidArgs.Throw();
}
//
var legacyPrefix = $"{userInfo.UserId}{XAiModelsConstants.XAiKnowledgeOwnerSeparator}";
var legacyVectors = await dataProvider.LoadVectorsAsync(
includeEmbedding: true,
identifierPrefix: legacyPrefix,
cancellationToken: cancellationToken
);
if (!legacyVectors.HasChild())
{
return 0;
}
//
var scope = XAiKnowledgeScopeDescriptor.User();
var scopePrefix = GetScopePrefix(scope, userInfo);
var migrated = legacyVectors
.Select(v =>
{
//
var type = v.Type.IsNullOrEmpty() ? XAiModelsConstants.XAiDefaultKnowledgeType : v.Type;
var metadata = v.Metadata ?? new Dictionary<string, string>();
metadata[XAiModelsConstants.XAiKnowledgeMetadataType] = type;
metadata[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = string.Empty;
metadata[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString();
metadata[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = userInfo.UserId;
//
return new XAiVectorDto
{
Type = type,
Text = v.Text,
Metadata = metadata,
Embedding = v.Embedding,
Identifier = $"{scopePrefix}{v.Identifier.Substring(legacyPrefix.Length)}",
};
})
.ToList();
//
var result = await dataProvider.UpsertVectorsAsync(
items: migrated,
cancellationToken: cancellationToken
);
await dataProvider.RemoveVectorsAsync(
identifierPrefix: legacyPrefix,
cancellationToken: cancellationToken
);
//
logger.LogInformation(
"Knowledge: Migrated {Count} Legacy Vectors of {OwnerId} into User Scope",
result, userInfo.UserId
);
//
@@ -511,10 +685,12 @@ namespace xAiApi.Providers
//
return new XAiDocumentSource
{
Type = c.Type,
Score = c.Score,
Identifier = c.Identifier,
Snippet = text.Substring(0, snippetLength),
FileName = c.Metadata.GetMetadata(rag.MetadataFileName),
Scope = c.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataScope),
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null
};
})
@@ -525,34 +701,314 @@ namespace xAiApi.Providers
}
#endregion
//
#region Scope ...
/// <summary>
/// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ...
/// </summary>
private static XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope)
{
//
var result = scope ?? XAiKnowledgeScopeDescriptor.User();
switch (result.Scope)
{
case XAiKnowledgeScope.User:
case XAiKnowledgeScope.Global:
result.ScopeId = null;
break;
case XAiKnowledgeScope.Project:
case XAiKnowledgeScope.Conversation:
if (!result.ScopeId.HasValue || result.ScopeId.Value == Guid.Empty)
{
XException.InvalidArgs.Throw();
}
break;
default:
XException.InvalidArgs.Throw();
break;
}
//
return result;
}
/// <summary>
/// Ensure Caller has Access to Scope:
/// User: Own Data | Global: Read = Everyone, Write = Admin
/// Project / Conversation: Caller must be Owner ...
/// </summary>
private async Task EnsureAccess(
XAiKnowledgeScopeDescriptor scope,
XUserClaimsInfoDto userInfo,
bool isWrite,
CancellationToken cancellationToken
)
{
//
switch (scope.Scope)
{
case XAiKnowledgeScope.Global:
if (isWrite && !IsAdmin(userInfo))
{
XException.NotAuthorized.Throw();
}
break;
case XAiKnowledgeScope.Project:
await EnsureProjectOwner(scope.ScopeId.Value, userInfo, cancellationToken);
break;
case XAiKnowledgeScope.Conversation:
await EnsureConversationOwner(scope.ScopeId.Value, userInfo, cancellationToken);
break;
}
}
/// <summary>
/// Ensure Caller Owns Project ...
/// </summary>
private async Task<XAiProjectDto> EnsureProjectOwner(
Guid projectId,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken
)
{
//
var result = await dataProvider.GetProject(
id: projectId,
cancellationToken: cancellationToken
);
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal))
{
XException.NotAuthorized.Throw();
}
//
return result;
}
/// <summary>
/// Ensure Caller Owns Conversation ...
/// </summary>
private async Task<XAiConversationDto> EnsureConversationOwner(
Guid conversationId,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken
)
{
//
var result = await dataProvider.GetConversation(
id: conversationId,
cancellationToken: cancellationToken
);
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal))
{
XException.NotAuthorized.Throw();
}
//
return result;
}
/// <summary>
/// Resolve Retrieval Tiers (Ordered): Conversation -> Project -> User -> Global ...
/// </summary>
private async Task<IList<XAiKnowledgeScopeDescriptor>> ResolveTiers(
XAiKnowledgeAskRequest request,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken
)
{
//
var result = new List<XAiKnowledgeScopeDescriptor>();
Guid? projectId = request.ProjectId.HasValue && request.ProjectId.Value != Guid.Empty
? request.ProjectId
: null;
//
// Conversation Tier (+ Implicit Project) ...
if (request.ConversationId.HasValue && request.ConversationId.Value != Guid.Empty)
{
//
var conversation = await EnsureConversationOwner(
request.ConversationId.Value, userInfo, cancellationToken
);
result.Add(XAiKnowledgeScopeDescriptor.Conversation(request.ConversationId.Value));
//
// Conversation must Belong to Requested Project ...
if (
projectId.HasValue &&
conversation.ProjectId != Guid.Empty &&
projectId.Value != conversation.ProjectId
)
{
XException.InvalidArgs.Throw();
}
if (conversation.ProjectId != Guid.Empty)
{
projectId = conversation.ProjectId;
}
}
//
// Project Tier ...
if (projectId.HasValue)
{
await EnsureProjectOwner(projectId.Value, userInfo, cancellationToken);
result.Add(XAiKnowledgeScopeDescriptor.Project(projectId.Value));
}
//
// User / Global Tiers ...
if (request.IncludeUser)
{
result.Add(XAiKnowledgeScopeDescriptor.User());
}
if (request.IncludeGlobal)
{
result.Add(XAiKnowledgeScopeDescriptor.Global());
}
//
return result;
}
/// <summary>
/// Scope Prefix (Always Ends with Separator so "a" never Matches "ab"):
/// "conversation/{id}/" | "project/{id}/" | "user/{ownerId}/" | "global/" ...
/// </summary>
private static string GetScopePrefix(
XAiKnowledgeScopeDescriptor scope,
XUserClaimsInfoDto userInfo
)
{
//
var separator = XAiModelsConstants.XAiKnowledgeSeparator;
var result = scope.Scope switch
{
XAiKnowledgeScope.Global => $"{XAiModelsConstants.XAiKnowledgeGlobalPrefix}{separator}",
XAiKnowledgeScope.User => $"{XAiModelsConstants.XAiKnowledgeUserPrefix}{separator}{userInfo.UserId}{separator}",
XAiKnowledgeScope.Project => $"{XAiModelsConstants.XAiKnowledgeProjectPrefix}{separator}{scope.ScopeId:D}{separator}",
XAiKnowledgeScope.Conversation => $"{XAiModelsConstants.XAiKnowledgeConversationPrefix}{separator}{scope.ScopeId:D}{separator}",
_ => null
};
if (result.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
return result;
}
/// <summary>
/// Document Chunk Prefix: "{scopePrefix}{fileName}#" ...
/// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
/// </summary>
private string GetDocumentChunkPrefix(string scopePrefix, string fileName)
{
return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}";
}
/// <summary>
/// Normalize File Name for Identifier (Strip Client Path, Replace Separators) ...
/// </summary>
private string NormalizeFileName(string fileName)
{
//
if (string.IsNullOrWhiteSpace(fileName))
{
return null;
}
//
// Strip Client Side Path (Both Separators) ...
var name = Path.GetFileName(fileName.Replace('\\', '/'))?.Trim();
if (name.IsNullOrEmpty())
{
return null;
}
//
foreach (var c in UnsafeFileNameChars)
{
name = name.Replace(c, '_');
}
var chunkSeparator = configuration.TextChunker.ChunkIdentifierSeparator;
if (!chunkSeparator.IsNullOrEmpty())
{
name = name.Replace(chunkSeparator, "_");
}
//
return name;
}
/// <summary>
/// Load Distinct Document Names of a Scope ...
/// </summary>
private async Task<HashSet<string>> LoadDocumentNames(
string scopePrefix,
CancellationToken cancellationToken
)
{
//
var vectors = await dataProvider.LoadVectorsAsync(
includeEmbedding: false,
identifierPrefix: scopePrefix,
cancellationToken: cancellationToken
);
//
var rag = configuration.RAGDescriptor;
var result = new HashSet<string>(
(vectors ?? [])
.Select(v => v.Metadata.GetMetadata(rag.MetadataFileName))
.Where(n => !n.IsNullOrEmpty()),
StringComparer.Ordinal
);
//
return result;
}
/// <summary>
/// Is Valid User ...
/// </summary>
private static bool IsValidUser(XUserClaimsInfoDto userInfo)
{
return !userInfo.IsNullOrDefault() && !userInfo.UserId.IsNullOrEmpty();
}
/// <summary>
/// Is Caller Admin ...
/// </summary>
private static bool IsAdmin(XUserClaimsInfoDto userInfo)
{
//
var result =
!userInfo.IsNullOrDefault() &&
!userInfo.Roles.IsNullOrDefault() &&
userInfo.Roles.Any(r => string.Equals(r, XUserRoles.ADMIN, StringComparison.OrdinalIgnoreCase));
//
return result;
}
#endregion
//
#region Private ...
/// <summary>
/// Owner Scope Prefix: "{ownerId}/" ...
/// </summary>
private static string GetOwnerPrefix(string ownerId)
{
return $"{ownerId}{XAiApiConstants.XAiKnowledgeOwnerSeparator}";
}
/// <summary>
/// Document Prefix (Chunker Source): "{ownerId}/{fileName}" ...
/// </summary>
private static string GetDocumentPrefix(string ownerId, string fileName)
{
return $"{GetOwnerPrefix(ownerId)}{fileName}";
}
/// <summary>
/// Document Chunk Prefix: "{ownerId}/{fileName}#" ...
/// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
/// </summary>
private string GetDocumentChunkPrefix(string ownerId, string fileName)
{
return $"{GetDocumentPrefix(ownerId, fileName)}{configuration.TextChunker.ChunkIdentifierSeparator}";
}
/// <summary>
/// Extract Plain Text of a File (Text or Audio Transcript) ...
/// </summary>
@@ -596,9 +1052,10 @@ namespace xAiApi.Providers
}
/// <summary>
/// Embed Chunks in Batches and Build Vectors ...
/// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ...
/// </summary>
private async Task<IList<XAiVectorDto>> EmbedChunks(
XAiKnowledgeScopeDescriptor scope,
IList<XTextChunk> chunks,
string type,
string ownerId,
@@ -649,8 +1106,11 @@ namespace xAiApi.Providers
[rag.MetadataFileName] = fileName,
[rag.MetadataMimeType] = mimeType,
[rag.MetadataChunkIndex] = chunk.Index.ToString(),
[XAiApiConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
[XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
[XAiModelsConstants.XAiKnowledgeMetadataType] = type,
[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(),
[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty,
[XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
}
});
}
@@ -662,4 +1122,3 @@ namespace xAiApi.Providers
#endregion
}
}
+26 -15
View File
@@ -18,6 +18,7 @@ using xStorageService.DI;
using xIdentityService.DI;
using xDataService.Models;
using xCommons.Extensions;
using xAiModels.Constants;
using xPushService.Helpers;
using xCommons.Configurations;
using System.Collections.Generic;
@@ -204,27 +205,41 @@ namespace xAiApi
{
//
// Configure the HTTP request pipeline.
var isDevelopmentEnvironment = false;
if (env.IsDevelopment())
// Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors
// -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ...
var isDevelopmentEnvironment = env.IsDevelopment();
if (isDevelopmentEnvironment)
{
isDevelopmentEnvironment = true;
app.UseDeveloperExceptionPage();
}
//
// Use Swagger Middleware ...
app.UseXSwagger();
else
{
app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute);
app.UseHsts();
}
//
// Force Https Redirection ...
app.UseHttpsRedirection();
//
// Using Cors ...
// Use Storage Service (Prepare Folders + Static Files) ...
// Must be before Routing so Static Files Short Circuit Pipeline ...
app.UseXStorageService();
//
// Use Swagger Middleware (Only in Development) ...
if (isDevelopmentEnvironment)
{
app.UseXSwagger();
}
//
// Using Cors (before Proxy so Browser Requests get CORS Headers) ...
app.UseXCors();
//
// Enable Model Proxy ...
// Enable Model Proxy (Handles its own Authentication) ...
app.UseXAiModelProxy();
//
@@ -232,7 +247,7 @@ namespace xAiApi
app.UseRouting();
//
// Use xIdentityService ...
// Use xIdentityService (Authentication) ...
app.UseXIdentityService();
//
@@ -246,11 +261,7 @@ namespace xAiApi
});
//
// Use Storage Service ...
app.UseXStorageService();
//
// Use PushService ...
// Use PushService (Legacy UseSignalR -> Registers its own Router) ...
var pushHelper = new XPushServiceHelper();
app.UseXPushService(pushHelper);