diff --git a/Constants/XAiApiConstants.cs b/Constants/XAiApiConstants.cs
index ad5a38e..163fd49 100644
--- a/Constants/XAiApiConstants.cs
+++ b/Constants/XAiApiConstants.cs
@@ -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";
}
}
\ No newline at end of file
diff --git a/Constants/XAiKnowledgeScope.cs b/Constants/XAiKnowledgeScope.cs
deleted file mode 100644
index ff584d0..0000000
--- a/Constants/XAiKnowledgeScope.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-namespace xAiApi.Constants
-{
- ///
- /// Knowledge Base Scope (Where Ingested Vectors are Visible) ...
- ///
- public enum XAiKnowledgeScope
- {
- Conversation = 0,
- Project = 1,
- Global = 2,
- }
-}
diff --git a/Controllers/ChatWithDocumentsController.cs b/Controllers/ChatWithDocumentsController.cs
index a1f3fb7..6063c11 100644
--- a/Controllers/ChatWithDocumentsController.cs
+++ b/Controllers/ChatWithDocumentsController.cs
@@ -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();
- 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;
}
- ///
- /// Safe Metadata Reader ...
- ///
- private string GetMetadata(
- IDictionary metadata,
- string key
- )
- {
- //
- if (metadata.IsNullOrDefault() || !metadata.TryGetValue(key, out var value))
- {
- return null;
- }
-
- //
- return value;
- }
-
///
/// Write a SSE Event ...
///
- 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
}
diff --git a/Controllers/KnowledgeController.cs b/Controllers/KnowledgeController.cs
index b7af596..e49e490 100644
--- a/Controllers/KnowledgeController.cs
+++ b/Controllers/KnowledgeController.cs
@@ -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 ...
///
- /// Ingest Files into Current User's Knowledge Base:
+ /// Ingest Files into a Knowledge Scope:
/// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
///
///
+ /// Target Scope: User (default) / Project / Conversation / Global (Admin)
+ /// ProjectId or ConversationId (Required for Project / Conversation)
+ /// Optional Knowledge Type / Domain
/// Replace Previously Stored Vectors of Same File (default true)
///
///
@@ -56,6 +61,8 @@ namespace xAiApi.Controllers
[Consumes("multipart/form-data")]
public async Task> 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();
- 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 ...
///
- /// List Ingested Documents of Current User ...
+ /// List Ingested Documents of a Knowledge Scope ...
///
+ /// User (default) / Project / Conversation / Global
+ /// ProjectId or ConversationId (Required for Project / Conversation)
+ /// Optional Knowledge Type Filter
///
///
[HttpGet("Documents")]
public async Task>> 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
}
///
- /// Remove All Vectors of a Document ...
+ /// Remove All Vectors of a Document in a Knowledge Scope ...
///
///
+ /// User (default) / Project / Conversation / Global (Admin)
+ /// ProjectId or ConversationId (Required for Project / Conversation)
///
/// Count of Removed Vectors
[HttpDelete("Documents")]
public async Task> 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 ...
+ ///
+ /// Build Scope Descriptor from Request Params ...
+ ///
+ private XAiKnowledgeScopeDescriptor BuildScope(
+ XAiKnowledgeScope scope,
+ Guid? scopeId,
+ string knowledgeType
+ )
+ {
+ //
+ var result = new XAiKnowledgeScopeDescriptor
+ {
+ Scope = scope,
+ ScopeId = scopeId,
+ Type = knowledgeType,
+ };
+
+ //
+ return result;
+ }
+
///
/// Write a SSE Event ...
///
- 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
}
diff --git a/Controllers/ProxyController.cs b/Controllers/ProxyController.cs
deleted file mode 100644
index 3fdac4e..0000000
--- a/Controllers/ProxyController.cs
+++ /dev/null
@@ -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 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;
- }
- }
-}
\ No newline at end of file
diff --git a/Controllers/StartupController.cs b/Controllers/StartupController.cs
index 3717c43..db92745 100644
--- a/Controllers/StartupController.cs
+++ b/Controllers/StartupController.cs
@@ -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);
}
+
+ ///
+ /// Global Exception Handler Endpoint (Production) ...
+ /// Returns a Generic Error without Leaking Exception Details ...
+ ///
+ ///
+ [AllowAnonymous]
+ [Route("error")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public virtual ActionResult Error()
+ {
+ //
+ var error = XException.ActionFailed.ToXError();
+ return StatusCode(StatusCodes.Status500InternalServerError, error);
+ }
}
}
\ No newline at end of file
diff --git a/Controllers/XAiServiceControllerBase.cs b/Controllers/XAiServiceControllerBase.cs
index 11e1433..7cde219 100644
--- a/Controllers/XAiServiceControllerBase.cs
+++ b/Controllers/XAiServiceControllerBase.cs
@@ -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
///
///
///
- [AllowAnonymous]
[HttpGet("AskText")]
+ [Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task> AskText(
[FromQuery] string question,
CancellationToken cancellationToken = default
@@ -90,39 +91,27 @@ namespace xAiApi.Controllers
///
///
///
- [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();
- 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: \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);
+ }
+ }
+
+ ///
+ /// Write Validation Error for Streaming Endpoints (before Stream Starts) ...
+ ///
+ ///
+ [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
///
///
[HttpGet("Projects")]
+ [Authorize(Policy = XPolicies.EnabledUser)]
public async Task>> LoadProjects(
[FromQuery] bool includeDefaults = false,
CancellationToken cancellationToken = default
@@ -211,6 +222,7 @@ namespace xAiApi.Controllers
///
///
///
+ [Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Projects/{projectId}/Conversations")]
public async Task>> LoadConversations(
[FromRoute] Guid projectId,
@@ -255,6 +267,7 @@ namespace xAiApi.Controllers
///
///
///
+ [Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Conversations/{conversationId}/Messages")]
public async Task>> LoadMessages(
[FromRoute] Guid conversationId,
@@ -300,6 +313,7 @@ namespace xAiApi.Controllers
///
///
[HttpGet("Projects/Query")]
+ [Authorize(Policy = XPolicies.EnabledUser)]
public async Task>> QueryProjects(
[FromQuery] XQuery query,
CancellationToken cancellationToken = default
@@ -337,6 +351,7 @@ namespace xAiApi.Controllers
///
///
///
+ [Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Projects/{projectId}/Conversations/Query")]
public async Task>> QueryConversations(
[FromRoute] Guid projectId,
@@ -377,6 +392,7 @@ namespace xAiApi.Controllers
///
///
///
+ [Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Conversations/{conversationId}/Messages/Query")]
public async Task>> QueryMessages(
[FromRoute] Guid conversationId,
@@ -420,6 +436,7 @@ namespace xAiApi.Controllers
///
///
[HttpPost("Projects")]
+ [Authorize(Policy = XPolicies.EnabledUser)]
public async Task> CreateProject(
[FromBody] XAiProjectDto item,
CancellationToken cancellationToken = default
@@ -473,6 +490,7 @@ namespace xAiApi.Controllers
///
///
///
+ [Authorize(Policy = XPolicies.EnabledUser)]
[HttpPost("Projects/{projectId}/Conversations")]
public async Task> CreateConversation(
[FromRoute] Guid projectId,
@@ -535,9 +553,10 @@ namespace xAiApi.Controllers
///
[HttpPost("ExtractContent")]
[Consumes("multipart/form-data")]
+ [Authorize(Policy = XPolicies.EnabledUser)]
public async Task> ExtractContent(
[FromForm] IFormFileCollection files,
- [FromForm] string extractors = null,
+ [FromForm] string extractors = "*",
CancellationToken cancellationToken = default
) {
//
@@ -588,6 +607,7 @@ namespace xAiApi.Controllers
///
///
[HttpPost("Ask")]
+ [Authorize(Policy = XPolicies.EnabledUser)]
public async Task> Ask(
[FromBody] XAiResponseRequest request,
CancellationToken cancellationToken = default
@@ -637,37 +657,30 @@ namespace xAiApi.Controllers
///
///
[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();
- 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
///
[HttpPost("AskWithFiles")]
[Consumes("multipart/form-data")]
+ [Authorize(Policy = XPolicies.EnabledUser)]
public async Task> AskWithFiles(
[FromForm] XAiResponseRequest request,
[FromForm] IFormFileCollection files,
diff --git a/Database/XAiApiDbContext.cs b/Database/XAiApiDbContext.cs
index 1425588..28f5f3e 100644
--- a/Database/XAiApiDbContext.cs
+++ b/Database/XAiApiDbContext.cs
@@ -38,6 +38,7 @@ namespace xAiApi.Database
nameof(XTagEntityRegisterar),
nameof(XFileEntityRegisterar),
nameof(XStringEntityRegisterar),
+ nameof(XAiVectorEntityRegisterar),
nameof(XAiMessageEntityRegisterar),
nameof(XAiProjectEntityRegisterar),
nameof(XAiConversationEntityRegisterar),
diff --git a/Extensions/XModelsExtensions.cs b/Extensions/XModelsExtensions.cs
index d7c1351..b6a2de5 100644
--- a/Extensions/XModelsExtensions.cs
+++ b/Extensions/XModelsExtensions.cs
@@ -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,
diff --git a/Interfaces/IXAiRAGService.cs b/Interfaces/IXAiRAGService.cs
index fd4ce85..afef48c 100644
--- a/Interfaces/IXAiRAGService.cs
+++ b/Interfaces/IXAiRAGService.cs
@@ -11,15 +11,16 @@ namespace xAiApi.Interfaces
///
/// Persistent RAG Service over XAiVector Table:
/// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
+ /// Isolation is Scope Based (Conversation / Project / User / Global) ...
///
public interface IXAiRAGService
{
///
- /// Ingest Files into Owner's Knowledge Base:
+ /// Ingest Files into Specified Knowledge Scope:
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
///
///
- ///
+ /// Target Scope (Null = User Scope)
///
///
///
@@ -27,7 +28,7 @@ namespace xAiApi.Interfaces
///
Task 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
);
///
- /// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ...
+ /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
///
- ///
+ ///
///
- ///
- ///
- /// Optional: Restrict to a Specific File
///
///
Task> 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
);
///
- /// List Ingested Documents of Owner ...
+ /// List Ingested Documents of Specified Scope ...
///
+ /// Target Scope (Null = User Scope)
///
///
///
Task> LoadDocumentsAsync(
+ XAiKnowledgeScopeDescriptor scope = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
///
- /// Remove All Vectors of a Document ...
+ /// Remove All Vectors of a Document in Specified Scope ...
///
///
+ /// Target Scope (Null = User Scope)
///
///
/// Count of Removed Vectors
Task RemoveDocumentAsync(
string fileName,
+ XAiKnowledgeScopeDescriptor scope = null,
+ XUserClaimsInfoDto userInfo = null,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
+ /// Idempotent: Returns 0 when Nothing Left to Migrate ...
+ ///
+ ///
+ ///
+ /// Count of Migrated Vectors
+ Task MigrateLegacyVectorsAsync(
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
@@ -113,4 +124,4 @@ namespace xAiApi.Interfaces
IEnumerable context
);
}
-}
+}
\ No newline at end of file
diff --git a/Models/XAiKnowledgeModels.cs b/Models/XAiKnowledgeModels.cs
index c7ace2f..88ee5e1 100644
--- a/Models/XAiKnowledgeModels.cs
+++ b/Models/XAiKnowledgeModels.cs
@@ -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
///
/// Scope Kind ...
///
- public XAiKnowledgeScope Scope { get; set; }
+ public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User;
///
- /// Scope Identifier (ProjectId / ConversationId) - Null for Global ...
+ /// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ...
///
public Guid? ScopeId { get; set; }
@@ -29,20 +24,60 @@ namespace xAiApi.Models
///
public string Type { get; set; }
- //
- public static XAiKnowledgeScopeDescriptor Global(string type = null) => new()
+ ///
+ /// Create User Scope Knowledge Descriptor ...
+ ///
+ ///
+ ///
+ public static XAiKnowledgeScopeDescriptor User(
+ string type = null
+ ) => new()
+ {
+ Type = type,
+ ScopeId = null,
+ Scope = XAiKnowledgeScope.User,
+ };
+
+ ///
+ /// Create Global Scope Knowledge Descriptor ...
+ ///
+ ///
+ ///
+ 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()
+
+ ///
+ /// Create Project Scope Knowledge Descriptor ...
+ ///
+ ///
+ ///
+ ///
+ 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()
+
+ ///
+ /// Create Conversational Scope Knowledge Descriptor ...
+ ///
+ ///
+ ///
+ ///
+ public static XAiKnowledgeScopeDescriptor Conversation(
+ Guid conversationId,
+ string type = null
+ ) => new()
{
Type = type,
ScopeId = conversationId,
@@ -98,7 +133,7 @@ namespace xAiApi.Models
///
/// 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) ...
///
public class XAiKnowledgeAskRequest
{
@@ -118,6 +153,16 @@ namespace xAiApi.Models
///
public Guid? ProjectId { get; set; }
+ ///
+ /// Include Personal (User) Knowledge Tier (default true) ...
+ ///
+ public bool IncludeUser { get; set; } = true;
+
+ ///
+ /// Include Global Knowledge Tier (default true) ...
+ ///
+ public bool IncludeGlobal { get; set; } = true;
+
///
/// Optional: Restrict Retrieval to a Knowledge Type / Domain ...
///
diff --git a/Providers/Extractors/XCodeFileContentExtractor.cs b/Providers/Extractors/XCodeFileContentExtractor.cs
index 3b2c1a6..e21f740 100644
--- a/Providers/Extractors/XCodeFileContentExtractor.cs
+++ b/Providers/Extractors/XCodeFileContentExtractor.cs
@@ -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;
}
diff --git a/Providers/XAiEmbeddingServiceBase.cs b/Providers/XAiEmbeddingServiceBase.cs
index dd12d20..6eab8e3 100644
--- a/Providers/XAiEmbeddingServiceBase.cs
+++ b/Providers/XAiEmbeddingServiceBase.cs
@@ -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),
diff --git a/Providers/XAiRAGService.cs b/Providers/XAiRAGService.cs
index 03dbd41..ebe9c5e 100644
--- a/Providers/XAiRAGService.cs
+++ b/Providers/XAiRAGService.cs
@@ -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
{
///
/// 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 ...
///
public class XAiRAGService : IXAiRAGService
{
@@ -35,6 +43,11 @@ namespace xAiApi.Providers
private readonly IXDefaultEmbeddingService embeddingService;
private readonly IXFileContentExtractor fileContentExtractor;
+ ///
+ /// Characters which are not Allowed in File Name Part of Identifier ...
+ ///
+ private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#'];
+
public XAiRAGService(
IXTextChunker textChunker,
IXFileProvider fileProvider,
@@ -60,11 +73,11 @@ namespace xAiApi.Providers
//
#region Ingest ...
///
- /// Ingest Files into Owner's Knowledge Base:
+ /// Ingest Files into Specified Knowledge Scope:
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
///
///
- ///
+ ///
///
///
///
@@ -72,7 +85,7 @@ namespace xAiApi.Providers
///
public async Task 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 ...
///
- /// 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 ...
///
- ///
+ ///
///
- ///
- ///
- /// Optional: Restrict to a Specific File
///
///
public async Task> 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();
+ var seen = new HashSet(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 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 ...
///
- /// List Ingested Documents of Owner ...
+ /// List Ingested Documents of Specified Scope ...
///
+ ///
///
///
///
public async Task> 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
}
///
- /// Remove All Vectors of a Document ...
+ /// Remove All Vectors of a Document in Specified Scope ...
///
///
+ ///
///
///
/// Count of Removed Vectors
public async Task 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;
+ }
+
+ ///
+ /// 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 ...
+ ///
+ ///
+ ///
+ /// Count of Migrated Vectors
+ public async Task 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();
+ 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 ...
+ ///
+ /// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ...
+ ///
+ 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;
+ }
+
+ ///
+ /// Ensure Caller has Access to Scope:
+ /// User: Own Data | Global: Read = Everyone, Write = Admin
+ /// Project / Conversation: Caller must be Owner ...
+ ///
+ 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;
+ }
+ }
+
+ ///
+ /// Ensure Caller Owns Project ...
+ ///
+ private async Task 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;
+ }
+
+ ///
+ /// Ensure Caller Owns Conversation ...
+ ///
+ private async Task 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;
+ }
+
+ ///
+ /// Resolve Retrieval Tiers (Ordered): Conversation -> Project -> User -> Global ...
+ ///
+ private async Task> ResolveTiers(
+ XAiKnowledgeAskRequest request,
+ XUserClaimsInfoDto userInfo,
+ CancellationToken cancellationToken
+ )
+ {
+ //
+ var result = new List();
+ 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;
+ }
+
+ ///
+ /// Scope Prefix (Always Ends with Separator so "a" never Matches "ab"):
+ /// "conversation/{id}/" | "project/{id}/" | "user/{ownerId}/" | "global/" ...
+ ///
+ 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;
+ }
+
+ ///
+ /// Document Chunk Prefix: "{scopePrefix}{fileName}#" ...
+ /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
+ ///
+ private string GetDocumentChunkPrefix(string scopePrefix, string fileName)
+ {
+ return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}";
+ }
+
+ ///
+ /// Normalize File Name for Identifier (Strip Client Path, Replace Separators) ...
+ ///
+ 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;
+ }
+
+ ///
+ /// Load Distinct Document Names of a Scope ...
+ ///
+ private async Task> LoadDocumentNames(
+ string scopePrefix,
+ CancellationToken cancellationToken
+ )
+ {
+ //
+ var vectors = await dataProvider.LoadVectorsAsync(
+ includeEmbedding: false,
+ identifierPrefix: scopePrefix,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ var rag = configuration.RAGDescriptor;
+ var result = new HashSet(
+ (vectors ?? [])
+ .Select(v => v.Metadata.GetMetadata(rag.MetadataFileName))
+ .Where(n => !n.IsNullOrEmpty()),
+ StringComparer.Ordinal
+ );
+
+ //
+ return result;
+ }
+
+ ///
+ /// Is Valid User ...
+ ///
+ private static bool IsValidUser(XUserClaimsInfoDto userInfo)
+ {
+ return !userInfo.IsNullOrDefault() && !userInfo.UserId.IsNullOrEmpty();
+ }
+
+ ///
+ /// Is Caller Admin ...
+ ///
+ 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 ...
- ///
- /// Owner Scope Prefix: "{ownerId}/" ...
- ///
- private static string GetOwnerPrefix(string ownerId)
- {
- return $"{ownerId}{XAiApiConstants.XAiKnowledgeOwnerSeparator}";
- }
-
- ///
- /// Document Prefix (Chunker Source): "{ownerId}/{fileName}" ...
- ///
- private static string GetDocumentPrefix(string ownerId, string fileName)
- {
- return $"{GetOwnerPrefix(ownerId)}{fileName}";
- }
-
- ///
- /// Document Chunk Prefix: "{ownerId}/{fileName}#" ...
- /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
- ///
- private string GetDocumentChunkPrefix(string ownerId, string fileName)
- {
- return $"{GetDocumentPrefix(ownerId, fileName)}{configuration.TextChunker.ChunkIdentifierSeparator}";
- }
-
///
/// Extract Plain Text of a File (Text or Audio Transcript) ...
///
@@ -596,9 +1052,10 @@ namespace xAiApi.Providers
}
///
- /// Embed Chunks in Batches and Build Vectors ...
+ /// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ...
///
private async Task> EmbedChunks(
+ XAiKnowledgeScopeDescriptor scope,
IList 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
}
}
-
diff --git a/Startup.cs b/Startup.cs
index d7c70f6..62e1da5 100644
--- a/Startup.cs
+++ b/Startup.cs
@@ -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);