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:
@@ -20,26 +20,5 @@ namespace xAiApi.Constants
|
|||||||
public const string XAiDefaultVisionModelName = "Qwen";
|
public const string XAiDefaultVisionModelName = "Qwen";
|
||||||
public const string XAiDefaultThinkingModelName = "Qwen";
|
public const string XAiDefaultThinkingModelName = "Qwen";
|
||||||
public const string XAiEmbeddingPromptName = "Embedding";
|
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";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,10 +10,11 @@ using xAiApi.Configurations;
|
|||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
using xAiModels.Models.Dtos;
|
using xAiModels.Models.Dtos;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using xHttpService.Extensions;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using System.Collections.Generic;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System.Collections.Generic;
|
||||||
using xIdentityService.Interfaces;
|
using xIdentityService.Interfaces;
|
||||||
using xIdentityService.Controllers;
|
using xIdentityService.Controllers;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
@@ -314,15 +315,19 @@ namespace xAiApi.Controllers
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
try
|
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||||
{
|
|
||||||
//
|
|
||||||
// Validate ...
|
|
||||||
if (!request.IsValid())
|
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 userInfo = await GetUserInfo();
|
||||||
var ownerId = userInfo.UserId;
|
var ownerId = userInfo.UserId;
|
||||||
@@ -339,17 +344,8 @@ namespace xAiApi.Controllers
|
|||||||
var context = await Retrieve(request, ownerId, cancellationToken);
|
var context = await Retrieve(request, ownerId, cancellationToken);
|
||||||
|
|
||||||
//
|
//
|
||||||
// Configure SSE Response Headers ...
|
// Configure SSE Response ...
|
||||||
Response.Headers["X-Accel-Buffering"] = "no";
|
Response.PrepareSseResponse();
|
||||||
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();
|
|
||||||
|
|
||||||
//
|
//
|
||||||
// First Event: Sources ...
|
// First Event: Sources ...
|
||||||
@@ -365,6 +361,7 @@ namespace xAiApi.Controllers
|
|||||||
//
|
//
|
||||||
if (!hasContext)
|
if (!hasContext)
|
||||||
{
|
{
|
||||||
|
await Response.WriteSseDoneAsync(cancellationToken);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -397,6 +394,11 @@ namespace xAiApi.Controllers
|
|||||||
Text = string.Empty,
|
Text = string.Empty,
|
||||||
IsFinal = true
|
IsFinal = true
|
||||||
}, cancellationToken);
|
}, cancellationToken);
|
||||||
|
await Response.WriteSseDoneAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||||
|
{
|
||||||
|
// Client Disconnected ...
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -404,9 +406,14 @@ namespace xAiApi.Controllers
|
|||||||
Logger.LogError(ex, "ChatWithDocuments: AskStream Failed");
|
Logger.LogError(ex, "ChatWithDocuments: AskStream Failed");
|
||||||
if (!Response.HasStarted)
|
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
|
#endregion
|
||||||
@@ -447,11 +454,10 @@ namespace xAiApi.Controllers
|
|||||||
CreatedAtUtc = session.CreatedAtUtc,
|
CreatedAtUtc = session.CreatedAtUtc,
|
||||||
LastAccessAtUtc = session.LastAccessAtUtc,
|
LastAccessAtUtc = session.LastAccessAtUtc,
|
||||||
ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl),
|
ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl),
|
||||||
Files = vectors
|
Files = [.. vectors
|
||||||
.Select(v => GetMetadata(v.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName))
|
.Select(v => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName))
|
||||||
.Where(f => !f.IsNullOrEmpty())
|
.Where(f => !f.IsNullOrEmpty())
|
||||||
.Distinct()
|
.Distinct()]
|
||||||
.ToList()
|
|
||||||
};
|
};
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -647,7 +653,7 @@ namespace xAiApi.Controllers
|
|||||||
.Select(c =>
|
.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 text = c.Text ?? string.Empty;
|
||||||
var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength);
|
var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength);
|
||||||
|
|
||||||
@@ -658,7 +664,7 @@ namespace xAiApi.Controllers
|
|||||||
Identifier = c.Identifier,
|
Identifier = c.Identifier,
|
||||||
Snippet = text.Substring(0, snippetLength),
|
Snippet = text.Substring(0, snippetLength),
|
||||||
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null,
|
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null,
|
||||||
FileName = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName)
|
FileName = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
.ToList();
|
.ToList();
|
||||||
@@ -667,36 +673,19 @@ namespace xAiApi.Controllers
|
|||||||
return result;
|
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>
|
/// <summary>
|
||||||
/// Write a SSE Event ...
|
/// Write a SSE Event ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task WriteChunk(
|
private Task WriteChunk(
|
||||||
XAiDocumentAnswerChunk chunk,
|
XAiDocumentAnswerChunk chunk,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
var payload = chunk.ToJSON(camelCase: true);
|
return Response.WriteSseEventAsync(
|
||||||
await Response.WriteAsync($"data: {payload}\n\n", cancellationToken);
|
data: chunk,
|
||||||
await Response.Body.FlushAsync(cancellationToken);
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ using xAiApi.Models;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
|
using xAiModels.Constants;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using xHttpService.Extensions;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
@@ -45,10 +47,13 @@ namespace xAiApi.Controllers
|
|||||||
//
|
//
|
||||||
#region Ingest ...
|
#region Ingest ...
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ingest Files into Current User's Knowledge Base:
|
/// Ingest Files into a Knowledge Scope:
|
||||||
/// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
|
/// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="files"></param>
|
/// <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="replaceExisting">Replace Previously Stored Vectors of Same File (default true)</param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
@@ -56,6 +61,8 @@ namespace xAiApi.Controllers
|
|||||||
[Consumes("multipart/form-data")]
|
[Consumes("multipart/form-data")]
|
||||||
public async Task<ActionResult<XAiKnowledgeIngestResult>> Ingest(
|
public async Task<ActionResult<XAiKnowledgeIngestResult>> Ingest(
|
||||||
[FromForm] IFormFileCollection files,
|
[FromForm] IFormFileCollection files,
|
||||||
|
[FromForm] XAiKnowledgeScope scope = XAiKnowledgeScope.Global,
|
||||||
|
[FromForm] Guid? scopeId = null,
|
||||||
[FromForm] string knowledgeType = null,
|
[FromForm] string knowledgeType = null,
|
||||||
[FromForm] bool replaceExisting = true,
|
[FromForm] bool replaceExisting = true,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
@@ -80,9 +87,9 @@ namespace xAiApi.Controllers
|
|||||||
files: files,
|
files: files,
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
connectionId: connectionId,
|
connectionId: connectionId,
|
||||||
knowledgeType: knowledgeType,
|
|
||||||
replaceExisting: replaceExisting,
|
replaceExisting: replaceExisting,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken,
|
||||||
|
scope: BuildScope(scope, scopeId, knowledgeType)
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -156,55 +163,57 @@ namespace xAiApi.Controllers
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
try
|
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||||
{
|
|
||||||
//
|
|
||||||
// Validate ...
|
|
||||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
||||||
{
|
{
|
||||||
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 userInfo = await GetUserInfo();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Configure SSE Response Headers ...
|
await using var enumerator = ragService
|
||||||
Response.Headers["X-Accel-Buffering"] = "no";
|
.AskWithRAGAsEnumerable(
|
||||||
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();
|
|
||||||
|
|
||||||
//
|
|
||||||
var enumerable = ragService.AskWithRAGAsEnumerable(
|
|
||||||
request: request,
|
request: request,
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
)
|
||||||
|
.GetAsyncEnumerator(cancellationToken);
|
||||||
|
|
||||||
//
|
//
|
||||||
await foreach (var chunk in enumerable)
|
// Pull First Item before Starting Stream, so Scope / Ownership /
|
||||||
{
|
// Retrieval Errors are Returned as Regular Http Errors ...
|
||||||
//
|
var hasItem = await enumerator.MoveNextAsync();
|
||||||
if (chunk.IsNullOrDefault())
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
//
|
||||||
|
// Configure SSE Response ...
|
||||||
|
Response.PrepareSseResponse();
|
||||||
|
|
||||||
|
//
|
||||||
|
while (hasItem)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var chunk = enumerator.Current;
|
||||||
|
if (!chunk.IsNullOrDefault())
|
||||||
|
{
|
||||||
await WriteChunk(chunk, cancellationToken);
|
await WriteChunk(chunk, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
await Response.Body.FlushAsync(cancellationToken);
|
hasItem = await enumerator.MoveNextAsync();
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
|
||||||
|
//
|
||||||
|
await Response.WriteSseDoneAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||||
{
|
{
|
||||||
// Client Disconnected ...
|
// Client Disconnected ...
|
||||||
}
|
}
|
||||||
@@ -212,16 +221,16 @@ namespace xAiApi.Controllers
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
Logger.LogError(ex, "Knowledge: AskStream Failed");
|
Logger.LogError(ex, "Knowledge: AskStream Failed");
|
||||||
try
|
|
||||||
{
|
|
||||||
//
|
|
||||||
if (!Response.HasStarted)
|
if (!Response.HasStarted)
|
||||||
{
|
{
|
||||||
Response.StatusCode = StatusCodes.Status500InternalServerError;
|
//
|
||||||
|
var result = GetExceptionActionResult(ex);
|
||||||
|
await result.ExecuteResultAsync(ControllerContext);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
await Response.Body.FlushAsync(CancellationToken.None);
|
|
||||||
}
|
//
|
||||||
catch { /* ignore */ }
|
await Response.WriteSseErrorAsync(ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
@@ -229,12 +238,18 @@ namespace xAiApi.Controllers
|
|||||||
//
|
//
|
||||||
#region Documents ...
|
#region Documents ...
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// List Ingested Documents of Current User ...
|
/// List Ingested Documents of a Knowledge Scope ...
|
||||||
/// </summary>
|
/// </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>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet("Documents")]
|
[HttpGet("Documents")]
|
||||||
public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
|
public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
|
||||||
|
[FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User,
|
||||||
|
[FromQuery] Guid? scopeId = null,
|
||||||
|
[FromQuery] string knowledgeType = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
@@ -247,7 +262,8 @@ namespace xAiApi.Controllers
|
|||||||
//
|
//
|
||||||
var result = await ragService.LoadDocumentsAsync(
|
var result = await ragService.LoadDocumentsAsync(
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken,
|
||||||
|
scope: BuildScope(scope, scopeId, knowledgeType)
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -262,14 +278,18 @@ namespace xAiApi.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Remove All Vectors of a Document ...
|
/// Remove All Vectors of a Document in a Knowledge Scope ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="fileName"></param>
|
/// <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>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns>Count of Removed Vectors</returns>
|
/// <returns>Count of Removed Vectors</returns>
|
||||||
[HttpDelete("Documents")]
|
[HttpDelete("Documents")]
|
||||||
public async Task<ActionResult<int>> DeleteDocument(
|
public async Task<ActionResult<int>> DeleteDocument(
|
||||||
[FromQuery] string fileName,
|
[FromQuery] string fileName,
|
||||||
|
[FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User,
|
||||||
|
[FromQuery] Guid? scopeId = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
@@ -287,7 +307,8 @@ namespace xAiApi.Controllers
|
|||||||
var result = await ragService.RemoveDocumentAsync(
|
var result = await ragService.RemoveDocumentAsync(
|
||||||
fileName: fileName,
|
fileName: fileName,
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken,
|
||||||
|
scope: BuildScope(scope, scopeId, null)
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -304,18 +325,40 @@ namespace xAiApi.Controllers
|
|||||||
|
|
||||||
//
|
//
|
||||||
#region Private ...
|
#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>
|
/// <summary>
|
||||||
/// Write a SSE Event ...
|
/// Write a SSE Event ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task WriteChunk(
|
private Task WriteChunk(
|
||||||
XAiDocumentAnswerChunk chunk,
|
XAiDocumentAnswerChunk chunk,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
var payload = chunk.ToJSON(camelCase: true);
|
return Response.WriteSseEventAsync(
|
||||||
await Response.WriteAsync($"data: {payload}\n\n", cancellationToken);
|
data: chunk,
|
||||||
await Response.Body.FlushAsync(cancellationToken);
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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.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
|
namespace xAiApi.Controllers
|
||||||
{
|
{
|
||||||
@@ -41,5 +44,20 @@ namespace xAiApi.Controllers
|
|||||||
//
|
//
|
||||||
return Ok(message);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
using xModels.Dtos;
|
using xModels.Dtos;
|
||||||
using System.Text.Json;
|
using xIdentityHelper;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using xAiModels.Models;
|
using xAiModels.Models;
|
||||||
|
using xAiApi.Extensions;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
@@ -10,6 +11,7 @@ using xAiModels.Extensions;
|
|||||||
using xAiModels.Models.Dtos;
|
using xAiModels.Models.Dtos;
|
||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using xHttpService.Extensions;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
@@ -18,7 +20,6 @@ using xIdentityService.Interfaces;
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xIdentityService.Controllers;
|
using xIdentityService.Controllers;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using System.Linq;
|
|
||||||
|
|
||||||
namespace xAiApi.Controllers
|
namespace xAiApi.Controllers
|
||||||
{
|
{
|
||||||
@@ -53,8 +54,8 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="question"></param>
|
/// <param name="question"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[AllowAnonymous]
|
|
||||||
[HttpGet("AskText")]
|
[HttpGet("AskText")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public virtual async Task<ActionResult<string>> AskText(
|
public virtual async Task<ActionResult<string>> AskText(
|
||||||
[FromQuery] string question,
|
[FromQuery] string question,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
@@ -90,39 +91,27 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="question"></param>
|
/// <param name="question"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[AllowAnonymous]
|
|
||||||
[HttpGet("AskTextStream")]
|
[HttpGet("AskTextStream")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public virtual async Task AskTextStream(
|
public virtual async Task AskTextStream(
|
||||||
[FromQuery] string question,
|
[FromQuery] string question,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
//
|
||||||
|
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||||
|
if (question.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
await WriteStreamValidationError();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Validate ...
|
// Configure SSE Response ...
|
||||||
ValidationProvider.NotEmpty(question);
|
Response.PrepareSseResponse();
|
||||||
|
|
||||||
//
|
|
||||||
// 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
|
|
||||||
};
|
|
||||||
|
|
||||||
//
|
//
|
||||||
var enumerable = aiService.AskTextAsEnumerable(
|
var enumerable = aiService.AskTextAsEnumerable(
|
||||||
@@ -131,37 +120,58 @@ namespace xAiApi.Controllers
|
|||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
|
// Format: data: {"text":"..."}\n\n
|
||||||
await foreach (var chunk in enumerable)
|
await foreach (var chunk in enumerable)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Skip empty chunks ...
|
// Skip Empty Chunks ...
|
||||||
if (string.IsNullOrEmpty(chunk))
|
if (string.IsNullOrEmpty(chunk))
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Build SSE message ...
|
await Response.WriteSseEventAsync(
|
||||||
// Format: data: <json>\n\n
|
data: new { text = chunk },
|
||||||
// var payload = JsonSerializer.Serialize(
|
cancellationToken: cancellationToken
|
||||||
// new { text = chunk },
|
);
|
||||||
// jsonOptions
|
|
||||||
// );
|
|
||||||
var payload = chunk;
|
|
||||||
|
|
||||||
//
|
|
||||||
// Write SSE Event ...
|
|
||||||
await Response.WriteAsync($"{payload}\n\n", cancellationToken);
|
|
||||||
await Response.Body.FlushAsync(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
|
#endregion
|
||||||
|
|
||||||
@@ -174,6 +184,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet("Projects")]
|
[HttpGet("Projects")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public async Task<ActionResult<IEnumerable<XAiProjectDto>>> LoadProjects(
|
public async Task<ActionResult<IEnumerable<XAiProjectDto>>> LoadProjects(
|
||||||
[FromQuery] bool includeDefaults = false,
|
[FromQuery] bool includeDefaults = false,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
@@ -211,6 +222,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="projectId"></param>
|
/// <param name="projectId"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
[HttpGet("Projects/{projectId}/Conversations")]
|
[HttpGet("Projects/{projectId}/Conversations")]
|
||||||
public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations(
|
public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations(
|
||||||
[FromRoute] Guid projectId,
|
[FromRoute] Guid projectId,
|
||||||
@@ -255,6 +267,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="conversationId"></param>
|
/// <param name="conversationId"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
[HttpGet("Conversations/{conversationId}/Messages")]
|
[HttpGet("Conversations/{conversationId}/Messages")]
|
||||||
public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages(
|
public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages(
|
||||||
[FromRoute] Guid conversationId,
|
[FromRoute] Guid conversationId,
|
||||||
@@ -300,6 +313,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet("Projects/Query")]
|
[HttpGet("Projects/Query")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public async Task<ActionResult<XQueryResult<XAiProjectDto>>> QueryProjects(
|
public async Task<ActionResult<XQueryResult<XAiProjectDto>>> QueryProjects(
|
||||||
[FromQuery] XQuery query,
|
[FromQuery] XQuery query,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
@@ -337,6 +351,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="query"></param>
|
/// <param name="query"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
[HttpGet("Projects/{projectId}/Conversations/Query")]
|
[HttpGet("Projects/{projectId}/Conversations/Query")]
|
||||||
public async Task<ActionResult<XQueryResult<XAiConversationDto>>> QueryConversations(
|
public async Task<ActionResult<XQueryResult<XAiConversationDto>>> QueryConversations(
|
||||||
[FromRoute] Guid projectId,
|
[FromRoute] Guid projectId,
|
||||||
@@ -377,6 +392,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="query"></param>
|
/// <param name="query"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
[HttpGet("Conversations/{conversationId}/Messages/Query")]
|
[HttpGet("Conversations/{conversationId}/Messages/Query")]
|
||||||
public async Task<ActionResult<XQueryResult<XAiMessageDto>>> QueryMessages(
|
public async Task<ActionResult<XQueryResult<XAiMessageDto>>> QueryMessages(
|
||||||
[FromRoute] Guid conversationId,
|
[FromRoute] Guid conversationId,
|
||||||
@@ -420,6 +436,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("Projects")]
|
[HttpPost("Projects")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public async Task<ActionResult<XAiProjectDto>> CreateProject(
|
public async Task<ActionResult<XAiProjectDto>> CreateProject(
|
||||||
[FromBody] XAiProjectDto item,
|
[FromBody] XAiProjectDto item,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
@@ -473,6 +490,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="item"></param>
|
/// <param name="item"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
[HttpPost("Projects/{projectId}/Conversations")]
|
[HttpPost("Projects/{projectId}/Conversations")]
|
||||||
public async Task<ActionResult<XAiConversationDto>> CreateConversation(
|
public async Task<ActionResult<XAiConversationDto>> CreateConversation(
|
||||||
[FromRoute] Guid projectId,
|
[FromRoute] Guid projectId,
|
||||||
@@ -535,9 +553,10 @@ namespace xAiApi.Controllers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("ExtractContent")]
|
[HttpPost("ExtractContent")]
|
||||||
[Consumes("multipart/form-data")]
|
[Consumes("multipart/form-data")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public async Task<ActionResult<string>> ExtractContent(
|
public async Task<ActionResult<string>> ExtractContent(
|
||||||
[FromForm] IFormFileCollection files,
|
[FromForm] IFormFileCollection files,
|
||||||
[FromForm] string extractors = null,
|
[FromForm] string extractors = "*",
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
) {
|
) {
|
||||||
//
|
//
|
||||||
@@ -588,6 +607,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("Ask")]
|
[HttpPost("Ask")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public async Task<ActionResult<string>> Ask(
|
public async Task<ActionResult<string>> Ask(
|
||||||
[FromBody] XAiResponseRequest request,
|
[FromBody] XAiResponseRequest request,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
@@ -637,37 +657,30 @@ namespace xAiApi.Controllers
|
|||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("AskStream")]
|
[HttpPost("AskStream")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public async Task AskStream(
|
public async Task AskStream(
|
||||||
[FromBody] XAiResponseRequest request,
|
[FromBody] XAiResponseRequest request,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
try
|
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||||
{
|
|
||||||
//
|
|
||||||
// Validate ...
|
|
||||||
if (!request.IsValid())
|
if (!request.IsValid())
|
||||||
{
|
{
|
||||||
XException.InvalidArgs.Throw();
|
await WriteStreamValidationError();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var userInfo = await GetUserInfo();
|
var userInfo = await GetUserInfo();
|
||||||
var connectionId = GetConnectionId();
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Configure SSE Response Headers ...
|
// Configure SSE Response ...
|
||||||
Response.Headers["X-Accel-Buffering"] = "no";
|
Response.PrepareSseResponse();
|
||||||
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();
|
|
||||||
|
|
||||||
//
|
//
|
||||||
// TODO: Reading Fiels Form Collection and Attach it ...
|
// 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)
|
await foreach (var resp in enumerable)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -692,20 +706,33 @@ namespace xAiApi.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
var payload = resp.ToJSON(camelCase: true);
|
await Response.WriteSseEventAsync(
|
||||||
|
data: resp,
|
||||||
//
|
cancellationToken: cancellationToken
|
||||||
// Write SSE Event ...
|
);
|
||||||
await Response.WriteAsync($"{payload}", cancellationToken);
|
|
||||||
await Response.Body.FlushAsync(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>
|
/// <returns></returns>
|
||||||
[HttpPost("AskWithFiles")]
|
[HttpPost("AskWithFiles")]
|
||||||
[Consumes("multipart/form-data")]
|
[Consumes("multipart/form-data")]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
public async Task<ActionResult<string>> AskWithFiles(
|
public async Task<ActionResult<string>> AskWithFiles(
|
||||||
[FromForm] XAiResponseRequest request,
|
[FromForm] XAiResponseRequest request,
|
||||||
[FromForm] IFormFileCollection files,
|
[FromForm] IFormFileCollection files,
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ namespace xAiApi.Database
|
|||||||
nameof(XTagEntityRegisterar),
|
nameof(XTagEntityRegisterar),
|
||||||
nameof(XFileEntityRegisterar),
|
nameof(XFileEntityRegisterar),
|
||||||
nameof(XStringEntityRegisterar),
|
nameof(XStringEntityRegisterar),
|
||||||
|
nameof(XAiVectorEntityRegisterar),
|
||||||
nameof(XAiMessageEntityRegisterar),
|
nameof(XAiMessageEntityRegisterar),
|
||||||
nameof(XAiProjectEntityRegisterar),
|
nameof(XAiProjectEntityRegisterar),
|
||||||
nameof(XAiConversationEntityRegisterar),
|
nameof(XAiConversationEntityRegisterar),
|
||||||
|
|||||||
@@ -288,7 +288,7 @@ namespace xAiApi.Extensions
|
|||||||
//
|
//
|
||||||
// Instance Ollama Client using Custom HttpCLient ...
|
// Instance Ollama Client using Custom HttpCLient ...
|
||||||
var openAiClient = new OpenAIClient(
|
var openAiClient = new OpenAIClient(
|
||||||
new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiApiConstants.XOpenAINoKey : apiKey),
|
new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : apiKey),
|
||||||
new OpenAIClientOptions
|
new OpenAIClientOptions
|
||||||
{
|
{
|
||||||
Endpoint = url,
|
Endpoint = url,
|
||||||
|
|||||||
@@ -11,15 +11,16 @@ namespace xAiApi.Interfaces
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Persistent RAG Service over XAiVector Table:
|
/// Persistent RAG Service over XAiVector Table:
|
||||||
/// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
|
/// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
|
||||||
|
/// Isolation is Scope Based (Conversation / Project / User / Global) ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IXAiRAGService
|
public interface IXAiRAGService
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ingest Files into Owner's Knowledge Base:
|
/// Ingest Files into Specified Knowledge Scope:
|
||||||
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
|
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="files"></param>
|
/// <param name="files"></param>
|
||||||
/// <param name="knowledgeType"></param>
|
/// <param name="scope">Target Scope (Null = User Scope)</param>
|
||||||
/// <param name="userInfo"></param>
|
/// <param name="userInfo"></param>
|
||||||
/// <param name="connectionId"></param>
|
/// <param name="connectionId"></param>
|
||||||
/// <param name="replaceExisting"></param>
|
/// <param name="replaceExisting"></param>
|
||||||
@@ -27,7 +28,7 @@ namespace xAiApi.Interfaces
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<XAiKnowledgeIngestResult> IngestAsync(
|
Task<XAiKnowledgeIngestResult> IngestAsync(
|
||||||
IFormFileCollection files,
|
IFormFileCollection files,
|
||||||
string knowledgeType = null,
|
XAiKnowledgeScopeDescriptor scope = null,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
string connectionId = null,
|
string connectionId = null,
|
||||||
bool replaceExisting = true,
|
bool replaceExisting = true,
|
||||||
@@ -35,21 +36,15 @@ namespace xAiApi.Interfaces
|
|||||||
);
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Embed Prompt and Retrieve Relevant Chunks from Owner's Knowledge Base ...
|
/// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="prompt"></param>
|
/// <param name="request"></param>
|
||||||
/// <param name="userInfo"></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>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<IList<XAiVectorSearchResult>> RetrieveAsync(
|
Task<IList<XAiVectorSearchResult>> RetrieveAsync(
|
||||||
string prompt,
|
XAiKnowledgeAskRequest request,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
int? topK = null,
|
|
||||||
float? minScore = null,
|
|
||||||
string fileName = null,
|
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -81,25 +76,41 @@ namespace xAiApi.Interfaces
|
|||||||
);
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// List Ingested Documents of Owner ...
|
/// List Ingested Documents of Specified Scope ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="scope">Target Scope (Null = User Scope)</param>
|
||||||
/// <param name="userInfo"></param>
|
/// <param name="userInfo"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
|
Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
|
||||||
|
XAiKnowledgeScopeDescriptor scope = null,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Remove All Vectors of a Document ...
|
/// Remove All Vectors of a Document in Specified Scope ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="fileName"></param>
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="scope">Target Scope (Null = User Scope)</param>
|
||||||
/// <param name="userInfo"></param>
|
/// <param name="userInfo"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns>Count of Removed Vectors</returns>
|
/// <returns>Count of Removed Vectors</returns>
|
||||||
Task<int> RemoveDocumentAsync(
|
Task<int> RemoveDocumentAsync(
|
||||||
string fileName,
|
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,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,10 +1,5 @@
|
|||||||
using xAiApi.Constants;
|
|
||||||
|
|
||||||
using xAiApi.Constants;
|
|
||||||
|
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using xAiApi.Constants;
|
using xAiModels.Constants;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace xAiApi.Models
|
namespace xAiApi.Models
|
||||||
@@ -17,10 +12,10 @@ namespace xAiApi.Models
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Scope Kind ...
|
/// Scope Kind ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public XAiKnowledgeScope Scope { get; set; }
|
public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Scope Identifier (ProjectId / ConversationId) - Null for Global ...
|
/// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Guid? ScopeId { get; set; }
|
public Guid? ScopeId { get; set; }
|
||||||
|
|
||||||
@@ -29,20 +24,60 @@ namespace xAiApi.Models
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public string Type { get; set; }
|
public string Type { get; set; }
|
||||||
|
|
||||||
//
|
/// <summary>
|
||||||
public static XAiKnowledgeScopeDescriptor Global(string type = null) => new()
|
/// 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,
|
Type = type,
|
||||||
ScopeId = null,
|
ScopeId = null,
|
||||||
Scope = XAiKnowledgeScope.Global,
|
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,
|
Type = type,
|
||||||
ScopeId = projectId,
|
ScopeId = projectId,
|
||||||
Scope = XAiKnowledgeScope.Project,
|
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,
|
Type = type,
|
||||||
ScopeId = conversationId,
|
ScopeId = conversationId,
|
||||||
@@ -98,7 +133,7 @@ namespace xAiApi.Models
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ask Request over Persistent Knowledge Base ...
|
/// 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>
|
/// </summary>
|
||||||
public class XAiKnowledgeAskRequest
|
public class XAiKnowledgeAskRequest
|
||||||
{
|
{
|
||||||
@@ -118,6 +153,16 @@ namespace xAiApi.Models
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public Guid? ProjectId { get; set; }
|
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>
|
/// <summary>
|
||||||
/// Optional: Restrict Retrieval to a Knowledge Type / Domain ...
|
/// Optional: Restrict Retrieval to a Knowledge Type / Domain ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ namespace xAiApi.Providers.Extractors
|
|||||||
//
|
//
|
||||||
var result = await ExtractRichAsync(
|
var result = await ExtractRichAsync(
|
||||||
fileStream,
|
fileStream,
|
||||||
"book.epub",
|
string.Empty,
|
||||||
mimeType,
|
mimeType,
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
@@ -112,12 +112,18 @@ namespace xAiApi.Providers.Extractors
|
|||||||
detectEncodingFromByteOrderMarks: true
|
detectEncodingFromByteOrderMarks: true
|
||||||
);
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
var content = await reader.ReadToEndAsync();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Normalize line endings for consistent downstream processing ...
|
// Normalize line endings for consistent downstream processing ...
|
||||||
result.Text = result.Text?
|
content = content?
|
||||||
.Replace("\r\n", "\n")
|
.Replace("\r\n", "\n")
|
||||||
.Replace("\r", "\n");
|
.Replace("\r", "\n");
|
||||||
|
|
||||||
|
//
|
||||||
|
result.Text = content;
|
||||||
|
|
||||||
//
|
//
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -195,7 +195,7 @@ namespace xAiApi.Providers
|
|||||||
case XAiModelProviderType.OpenAI:
|
case XAiModelProviderType.OpenAI:
|
||||||
//
|
//
|
||||||
var openAiClient = new OpenAIClient(
|
var openAiClient = new OpenAIClient(
|
||||||
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiApiConstants.XOpenAINoKey : descriptor.ApiKey),
|
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : descriptor.ApiKey),
|
||||||
new OpenAIClientOptions
|
new OpenAIClientOptions
|
||||||
{
|
{
|
||||||
Endpoint = new Uri(descriptor.Url),
|
Endpoint = new Uri(descriptor.Url),
|
||||||
|
|||||||
+564
-105
@@ -1,7 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using xAiApi.Models;
|
using xAiApi.Models;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
using xIdentityHelper;
|
||||||
using xAiApi.Constants;
|
using xAiApi.Constants;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
@@ -17,12 +19,18 @@ using System.Collections.Generic;
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
using System.Runtime.CompilerServices;
|
using System.Runtime.CompilerServices;
|
||||||
|
using xAiModels.Constants;
|
||||||
|
|
||||||
namespace xAiApi.Providers
|
namespace xAiApi.Providers
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Persistent RAG Service over XAiVector Table ...
|
/// 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>
|
/// </summary>
|
||||||
public class XAiRAGService : IXAiRAGService
|
public class XAiRAGService : IXAiRAGService
|
||||||
{
|
{
|
||||||
@@ -35,6 +43,11 @@ namespace xAiApi.Providers
|
|||||||
private readonly IXDefaultEmbeddingService embeddingService;
|
private readonly IXDefaultEmbeddingService embeddingService;
|
||||||
private readonly IXFileContentExtractor fileContentExtractor;
|
private readonly IXFileContentExtractor fileContentExtractor;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Characters which are not Allowed in File Name Part of Identifier ...
|
||||||
|
/// </summary>
|
||||||
|
private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#'];
|
||||||
|
|
||||||
public XAiRAGService(
|
public XAiRAGService(
|
||||||
IXTextChunker textChunker,
|
IXTextChunker textChunker,
|
||||||
IXFileProvider fileProvider,
|
IXFileProvider fileProvider,
|
||||||
@@ -60,11 +73,11 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
#region Ingest ...
|
#region Ingest ...
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ingest Files into Owner's Knowledge Base:
|
/// Ingest Files into Specified Knowledge Scope:
|
||||||
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
|
/// Extract -> Chunk -> Embed -> Store (XAiVector) ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="files"></param>
|
/// <param name="files"></param>
|
||||||
/// <param name="knowledgeType"></param>
|
/// <param name="scope"></param>
|
||||||
/// <param name="userInfo"></param>
|
/// <param name="userInfo"></param>
|
||||||
/// <param name="connectionId"></param>
|
/// <param name="connectionId"></param>
|
||||||
/// <param name="replaceExisting"></param>
|
/// <param name="replaceExisting"></param>
|
||||||
@@ -72,7 +85,7 @@ namespace xAiApi.Providers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<XAiKnowledgeIngestResult> IngestAsync(
|
public async Task<XAiKnowledgeIngestResult> IngestAsync(
|
||||||
IFormFileCollection files,
|
IFormFileCollection files,
|
||||||
string knowledgeType = null,
|
XAiKnowledgeScopeDescriptor scope = null,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
string connectionId = null,
|
string connectionId = null,
|
||||||
bool replaceExisting = true,
|
bool replaceExisting = true,
|
||||||
@@ -81,21 +94,42 @@ namespace xAiApi.Providers
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Validate ...
|
// Validate ...
|
||||||
if (!files.HasChild() || userInfo.IsNullOrDefault())
|
if (!files.HasChild() || !IsValidUser(userInfo))
|
||||||
{
|
{
|
||||||
XException.InvalidArgs.Throw();
|
XException.InvalidArgs.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Normalize ...
|
var rag = configuration.RAGDescriptor;
|
||||||
if (knowledgeType.IsNullOrEmpty())
|
if (rag.MaxFilesPerIngest > 0 && files.Count > rag.MaxFilesPerIngest)
|
||||||
{
|
{
|
||||||
knowledgeType = XAiApiConstants.XAiDefaultKnowledgeType;
|
XException.InvalidArgs.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
var result = new XAiKnowledgeIngestResult();
|
// Resolve & Authorize Scope (Write) ...
|
||||||
var ingestedAtUtc = DateTime.UtcNow.ToString("O");
|
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)
|
foreach (var file in files)
|
||||||
@@ -110,6 +144,36 @@ namespace xAiApi.Providers
|
|||||||
continue;
|
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;
|
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
|
||||||
if (!fileContentExtractor.CanExtract(mimeType))
|
if (!fileContentExtractor.CanExtract(mimeType))
|
||||||
@@ -127,9 +191,8 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Chunk with Owner Scoped Source => Identifier = "{ownerId}/{fileName}#{index}" ...
|
// Chunk with Scoped Source => Identifier = "{scopePrefix}{fileName}#{index}" ...
|
||||||
var documentPrefix = GetDocumentPrefix(userInfo.UserId, file.FileName);
|
var chunks = textChunker.Chunk(text, $"{scopePrefix}{fileName}");
|
||||||
var chunks = textChunker.Chunk(text, documentPrefix);
|
|
||||||
if (!chunks.HasChild())
|
if (!chunks.HasChild())
|
||||||
{
|
{
|
||||||
result.SkippedFiles.Add(file.FileName);
|
result.SkippedFiles.Add(file.FileName);
|
||||||
@@ -148,10 +211,11 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
// Embed in Batches ...
|
// Embed in Batches ...
|
||||||
var vectors = await EmbedChunks(
|
var vectors = await EmbedChunks(
|
||||||
|
scope: scope,
|
||||||
chunks: chunks,
|
chunks: chunks,
|
||||||
|
fileName: fileName,
|
||||||
mimeType: mimeType,
|
mimeType: mimeType,
|
||||||
type: knowledgeType,
|
type: knowledgeType,
|
||||||
fileName: file.FileName,
|
|
||||||
ownerId: userInfo.UserId,
|
ownerId: userInfo.UserId,
|
||||||
ingestedAtUtc: ingestedAtUtc,
|
ingestedAtUtc: ingestedAtUtc,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
@@ -164,7 +228,7 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
result.ReplacedCount += await dataProvider.RemoveVectorsAsync(
|
result.ReplacedCount += await dataProvider.RemoveVectorsAsync(
|
||||||
cancellationToken: cancellationToken,
|
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.FilesCount++;
|
||||||
result.ChunksCount += storedCount;
|
result.ChunksCount += storedCount;
|
||||||
result.Documents.Add(new XAiKnowledgeDocumentInfo
|
result.Documents.Add(new XAiKnowledgeDocumentInfo
|
||||||
{
|
{
|
||||||
|
FileName = fileName,
|
||||||
MimeType = mimeType,
|
MimeType = mimeType,
|
||||||
FileName = file.FileName,
|
Type = knowledgeType,
|
||||||
|
Scope = scope.Scope,
|
||||||
|
ScopeId = scope.ScopeId,
|
||||||
ChunksCount = storedCount,
|
ChunksCount = storedCount,
|
||||||
IngestedAtUtc = DateTime.Parse(ingestedAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind)
|
OwnerId = userInfo.UserId,
|
||||||
|
IngestedAtUtc = ingestedAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
//
|
//
|
||||||
logger.LogInformation(
|
logger.LogInformation(
|
||||||
"Knowledge: Ingested {FileName} for {OwnerId} with {Chunks} Chunks",
|
"Knowledge: Ingested {FileName} into {Scope}:{ScopeId} by {OwnerId} with {Chunks} Chunks",
|
||||||
file.FileName, userInfo.UserId, storedCount
|
fileName, scope.Scope, scope.ScopeId, userInfo.UserId, storedCount
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,44 +267,50 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
|
||||||
//
|
//
|
||||||
#region Ask ...
|
#region Ask ...
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="prompt"></param>
|
/// <param name="request"></param>
|
||||||
/// <param name="userInfo"></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>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<IList<XAiVectorSearchResult>> RetrieveAsync(
|
public async Task<IList<XAiVectorSearchResult>> RetrieveAsync(
|
||||||
string prompt,
|
XAiKnowledgeAskRequest request,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
int? topK = null,
|
|
||||||
float? minScore = null,
|
|
||||||
string fileName = null,
|
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Validate ...
|
// Validate ...
|
||||||
if (prompt.IsNullOrEmpty() || userInfo.IsNullOrDefault())
|
if (
|
||||||
|
request.IsNullOrDefault() ||
|
||||||
|
request.Prompt.IsNullOrEmpty() ||
|
||||||
|
!IsValidUser(userInfo)
|
||||||
|
)
|
||||||
{
|
{
|
||||||
XException.InvalidArgs.Throw();
|
XException.InvalidArgs.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
var rag = configuration.RAGDescriptor;
|
var rag = configuration.RAGDescriptor;
|
||||||
var effectiveTopK = Math.Clamp(topK ?? rag.DefaultTopK, 1, rag.MaxTopK);
|
var effectiveTopK = Math.Clamp(request.TopK ?? rag.DefaultTopK, 1, rag.MaxTopK);
|
||||||
var effectiveMinScore = minScore ?? rag.DefaultMinScore;
|
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(
|
var queryEmbedding = await embeddingService.Embedding(
|
||||||
content: prompt,
|
content: request.Prompt,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
|
if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
|
||||||
@@ -244,13 +319,28 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Search in DB (Scoped to Owner or Owner + File) ...
|
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()
|
var prefix = fileName.IsNullOrEmpty()
|
||||||
? GetOwnerPrefix(userInfo.UserId)
|
? scopePrefix
|
||||||
: GetDocumentChunkPrefix(userInfo.UserId, fileName);
|
: GetDocumentChunkPrefix(scopePrefix, fileName);
|
||||||
|
|
||||||
|
//
|
||||||
var searchResult = await dataProvider.SearchVectorsAsync(
|
var searchResult = await dataProvider.SearchVectorsAsync(
|
||||||
type: null,
|
topK: remaining,
|
||||||
topK: effectiveTopK,
|
type: request.Type,
|
||||||
identifierPrefix: prefix,
|
identifierPrefix: prefix,
|
||||||
minScore: effectiveMinScore,
|
minScore: effectiveMinScore,
|
||||||
queryEmbedding: queryEmbedding,
|
queryEmbedding: queryEmbedding,
|
||||||
@@ -258,7 +348,16 @@ namespace xAiApi.Providers
|
|||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
var result = searchResult?.ToList() ?? [];
|
foreach (var item in searchResult ?? [])
|
||||||
|
{
|
||||||
|
if (seen.Add(item.Identifier ?? item.Id.ToString()))
|
||||||
|
{
|
||||||
|
result.Add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,20 +375,10 @@ namespace xAiApi.Providers
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Validate ...
|
// Retrieve (Validates Request) ...
|
||||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
|
||||||
{
|
|
||||||
XException.InvalidArgs.Throw();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
// Retrieve ...
|
|
||||||
var context = await RetrieveAsync(
|
var context = await RetrieveAsync(
|
||||||
|
request: request,
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
topK: request.TopK,
|
|
||||||
prompt: request.Prompt,
|
|
||||||
minScore: request.MinScore,
|
|
||||||
fileName: request.FileName,
|
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -333,20 +422,10 @@ namespace xAiApi.Providers
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Validate ...
|
// Retrieve (Validates Request) ...
|
||||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
|
||||||
{
|
|
||||||
XException.InvalidArgs.Throw();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
// Retrieve ...
|
|
||||||
var context = await RetrieveAsync(
|
var context = await RetrieveAsync(
|
||||||
|
request: request,
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
topK: request.TopK,
|
|
||||||
prompt: request.Prompt,
|
|
||||||
minScore: request.MinScore,
|
|
||||||
fileName: request.FileName,
|
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -403,46 +482,60 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
#region Documents ...
|
#region Documents ...
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// List Ingested Documents of Owner ...
|
/// List Ingested Documents of Specified Scope ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="scope"></param>
|
||||||
/// <param name="userInfo"></param>
|
/// <param name="userInfo"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
|
public async Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
|
||||||
|
XAiKnowledgeScopeDescriptor scope = null,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Validate ...
|
// Validate ...
|
||||||
if (userInfo.IsNullOrDefault())
|
if (!IsValidUser(userInfo))
|
||||||
{
|
{
|
||||||
XException.InvalidArgs.Throw();
|
XException.InvalidArgs.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Resolve & Authorize Scope (Read) ...
|
||||||
|
scope = NormalizeScope(scope);
|
||||||
|
await EnsureAccess(scope, userInfo, isWrite: false, cancellationToken);
|
||||||
|
|
||||||
//
|
//
|
||||||
var vectors = await dataProvider.LoadVectorsAsync(
|
var vectors = await dataProvider.LoadVectorsAsync(
|
||||||
|
type: scope.Type,
|
||||||
includeEmbedding: false,
|
includeEmbedding: false,
|
||||||
cancellationToken: cancellationToken,
|
cancellationToken: cancellationToken,
|
||||||
identifierPrefix: GetOwnerPrefix(userInfo.UserId)
|
identifierPrefix: GetScopePrefix(scope, userInfo)
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
var rag = configuration.RAGDescriptor;
|
var rag = configuration.RAGDescriptor;
|
||||||
var result = (vectors ?? [])
|
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 =>
|
.Select(g =>
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
var first = g.First();
|
var first = g.First();
|
||||||
var ingestedText = first.Metadata.GetMetadata(XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc);
|
var ingestedText = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc);
|
||||||
|
|
||||||
//
|
//
|
||||||
return new XAiKnowledgeDocumentInfo
|
return new XAiKnowledgeDocumentInfo
|
||||||
{
|
{
|
||||||
FileName = g.Key,
|
FileName = g.Key,
|
||||||
|
Type = first.Type,
|
||||||
|
Scope = scope.Scope,
|
||||||
ChunksCount = g.Count(),
|
ChunksCount = g.Count(),
|
||||||
|
ScopeId = scope.ScopeId,
|
||||||
MimeType = first.Metadata.GetMetadata(rag.MetadataMimeType),
|
MimeType = first.Metadata.GetMetadata(rag.MetadataMimeType),
|
||||||
|
OwnerId = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataOwnerId),
|
||||||
IngestedAtUtc = DateTime.TryParse(
|
IngestedAtUtc = DateTime.TryParse(
|
||||||
ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt
|
ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt
|
||||||
) ? dt : null
|
) ? dt : null
|
||||||
@@ -456,33 +549,114 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Remove All Vectors of a Document ...
|
/// Remove All Vectors of a Document in Specified Scope ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="fileName"></param>
|
/// <param name="fileName"></param>
|
||||||
|
/// <param name="scope"></param>
|
||||||
/// <param name="userInfo"></param>
|
/// <param name="userInfo"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns>Count of Removed Vectors</returns>
|
/// <returns>Count of Removed Vectors</returns>
|
||||||
public async Task<int> RemoveDocumentAsync(
|
public async Task<int> RemoveDocumentAsync(
|
||||||
string fileName,
|
string fileName,
|
||||||
|
XAiKnowledgeScopeDescriptor scope = null,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Validate ...
|
// Validate ...
|
||||||
if (
|
var normalizedFileName = NormalizeFileName(fileName);
|
||||||
fileName.IsNullOrEmpty() ||
|
if (normalizedFileName.IsNullOrEmpty() || !IsValidUser(userInfo))
|
||||||
userInfo.IsNullOrDefault() ||
|
|
||||||
userInfo.UserId.IsNullOrEmpty()
|
|
||||||
)
|
|
||||||
{
|
{
|
||||||
XException.InvalidArgs.Throw();
|
XException.InvalidArgs.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Resolve & Authorize Scope (Write) ...
|
||||||
|
scope = NormalizeScope(scope);
|
||||||
|
await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);
|
||||||
|
|
||||||
//
|
//
|
||||||
var result = await dataProvider.RemoveVectorsAsync(
|
var result = await dataProvider.RemoveVectorsAsync(
|
||||||
cancellationToken: cancellationToken,
|
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
|
return new XAiDocumentSource
|
||||||
{
|
{
|
||||||
|
Type = c.Type,
|
||||||
Score = c.Score,
|
Score = c.Score,
|
||||||
Identifier = c.Identifier,
|
Identifier = c.Identifier,
|
||||||
Snippet = text.Substring(0, snippetLength),
|
Snippet = text.Substring(0, snippetLength),
|
||||||
FileName = c.Metadata.GetMetadata(rag.MetadataFileName),
|
FileName = c.Metadata.GetMetadata(rag.MetadataFileName),
|
||||||
|
Scope = c.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataScope),
|
||||||
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null
|
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
@@ -525,34 +701,314 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
#endregion
|
#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 ...
|
#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>
|
/// <summary>
|
||||||
/// Extract Plain Text of a File (Text or Audio Transcript) ...
|
/// Extract Plain Text of a File (Text or Audio Transcript) ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -596,9 +1052,10 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Embed Chunks in Batches and Build Vectors ...
|
/// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<IList<XAiVectorDto>> EmbedChunks(
|
private async Task<IList<XAiVectorDto>> EmbedChunks(
|
||||||
|
XAiKnowledgeScopeDescriptor scope,
|
||||||
IList<XTextChunk> chunks,
|
IList<XTextChunk> chunks,
|
||||||
string type,
|
string type,
|
||||||
string ownerId,
|
string ownerId,
|
||||||
@@ -649,8 +1106,11 @@ namespace xAiApi.Providers
|
|||||||
[rag.MetadataFileName] = fileName,
|
[rag.MetadataFileName] = fileName,
|
||||||
[rag.MetadataMimeType] = mimeType,
|
[rag.MetadataMimeType] = mimeType,
|
||||||
[rag.MetadataChunkIndex] = chunk.Index.ToString(),
|
[rag.MetadataChunkIndex] = chunk.Index.ToString(),
|
||||||
[XAiApiConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
|
[XAiModelsConstants.XAiKnowledgeMetadataType] = type,
|
||||||
[XAiApiConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
|
[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
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+26
-15
@@ -18,6 +18,7 @@ using xStorageService.DI;
|
|||||||
using xIdentityService.DI;
|
using xIdentityService.DI;
|
||||||
using xDataService.Models;
|
using xDataService.Models;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
|
using xAiModels.Constants;
|
||||||
using xPushService.Helpers;
|
using xPushService.Helpers;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -204,27 +205,41 @@ namespace xAiApi
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
// Configure the HTTP request pipeline.
|
// Configure the HTTP request pipeline.
|
||||||
var isDevelopmentEnvironment = false;
|
// Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors
|
||||||
if (env.IsDevelopment())
|
// -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ...
|
||||||
|
var isDevelopmentEnvironment = env.IsDevelopment();
|
||||||
|
if (isDevelopmentEnvironment)
|
||||||
{
|
{
|
||||||
isDevelopmentEnvironment = true;
|
|
||||||
app.UseDeveloperExceptionPage();
|
app.UseDeveloperExceptionPage();
|
||||||
}
|
}
|
||||||
|
else
|
||||||
//
|
{
|
||||||
// Use Swagger Middleware ...
|
app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute);
|
||||||
app.UseXSwagger();
|
app.UseHsts();
|
||||||
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Force Https Redirection ...
|
// Force Https Redirection ...
|
||||||
app.UseHttpsRedirection();
|
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();
|
app.UseXCors();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Enable Model Proxy ...
|
// Enable Model Proxy (Handles its own Authentication) ...
|
||||||
app.UseXAiModelProxy();
|
app.UseXAiModelProxy();
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -232,7 +247,7 @@ namespace xAiApi
|
|||||||
app.UseRouting();
|
app.UseRouting();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Use xIdentityService ...
|
// Use xIdentityService (Authentication) ...
|
||||||
app.UseXIdentityService();
|
app.UseXIdentityService();
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -246,11 +261,7 @@ namespace xAiApi
|
|||||||
});
|
});
|
||||||
|
|
||||||
//
|
//
|
||||||
// Use Storage Service ...
|
// Use PushService (Legacy UseSignalR -> Registers its own Router) ...
|
||||||
app.UseXStorageService();
|
|
||||||
|
|
||||||
//
|
|
||||||
// Use PushService ...
|
|
||||||
var pushHelper = new XPushServiceHelper();
|
var pushHelper = new XPushServiceHelper();
|
||||||
app.UseXPushService(pushHelper);
|
app.UseXPushService(pushHelper);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user