Implement RAG Scopes, Remove ProxyController, Fix Pipeline Order and SSE Format
- RAG: real scopes with identifiers conversation/{id}/, project/{id}/, user/{ownerId}/, global/;
- RAG: ownership checks via GetProject/GetConversation; Global write requires admin role;
- RAG: tiered retrieval Conversation -> Project -> User -> Global (single embedding, dedup, TopK fill);
- RAG: apply Type filter, sanitize file names, enforce MaxFilesPerIngest/MaxFileSizeBytes/MaxDocumentsPerScope;
- RAG: store scope/scopeId/type/ownerId metadata; return it in documents and sources;
- RAG: add MigrateLegacyVectorsAsync + POST /Knowledge/MigrateLegacy ({ownerId}/... -> user/{ownerId}/...);
- Knowledge API: scope/scopeId on Ingest, Documents, DELETE Documents;
- Remove ProxyController (root route "{modelName}/{path}" + AllowAnonymous hijacked all 2-segment paths);
- Startup: ExceptionHandler("/error") + HSTS outside Development; Swagger only in Development;
static files before routing; CORS before model proxy; add /error endpoint;
- SSE: all stream endpoints use xHttpService XSseExtensions; validate before streaming;
pre-stream errors return proper HTTP status; remove "Connection: keep-alive";
- Use xAiModels.Constants for XAiKnowledgeScope / Knowledge constants / XOpenAINoKey;
- Register XAiVectorEntityRegisterar in XAiApiDbContext;
- XCodeFileContentExtractor: actually read stream content; drop hard-coded "book.epub".
BREAKING: AskTextStream emits data: {"text":"..."}; AskStream emits data: {json}; both end with event: done.
This commit is contained in:
@@ -10,10 +10,11 @@ using xAiApi.Configurations;
|
||||
using xExceptions.Constants;
|
||||
using xAiModels.Models.Dtos;
|
||||
using System.Threading.Tasks;
|
||||
using xHttpService.Extensions;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Interfaces;
|
||||
using xIdentityService.Controllers;
|
||||
using xAiApi.Interfaces.Extractors;
|
||||
@@ -314,15 +315,19 @@ namespace xAiApi.Controllers
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||
if (!request.IsValid())
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!request.IsValid())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
Response.ContentType = "application/json; charset=utf-8";
|
||||
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
var ownerId = userInfo.UserId;
|
||||
@@ -339,17 +344,8 @@ namespace xAiApi.Controllers
|
||||
var context = await Retrieve(request, ownerId, cancellationToken);
|
||||
|
||||
//
|
||||
// Configure SSE Response Headers ...
|
||||
Response.Headers["X-Accel-Buffering"] = "no";
|
||||
Response.Headers["Connection"] = "keep-alive";
|
||||
Response.Headers["Content-Type"] = "text/event-stream";
|
||||
Response.Headers["Cache-Control"] = "no-cache, no-store";
|
||||
|
||||
//
|
||||
// Disable response buffering ...
|
||||
var responseBodyFeature = HttpContext.Features
|
||||
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
|
||||
responseBodyFeature?.DisableBuffering();
|
||||
// Configure SSE Response ...
|
||||
Response.PrepareSseResponse();
|
||||
|
||||
//
|
||||
// First Event: Sources ...
|
||||
@@ -365,6 +361,7 @@ namespace xAiApi.Controllers
|
||||
//
|
||||
if (!hasContext)
|
||||
{
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -397,6 +394,11 @@ namespace xAiApi.Controllers
|
||||
Text = string.Empty,
|
||||
IsFinal = true
|
||||
}, cancellationToken);
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||
{
|
||||
// Client Disconnected ...
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -404,9 +406,14 @@ namespace xAiApi.Controllers
|
||||
Logger.LogError(ex, "ChatWithDocuments: AskStream Failed");
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
await result.ExecuteResultAsync(ControllerContext);
|
||||
return;
|
||||
}
|
||||
await Response.Body.FlushAsync();
|
||||
|
||||
//
|
||||
await Response.WriteSseErrorAsync(ex.Message);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
@@ -447,11 +454,10 @@ namespace xAiApi.Controllers
|
||||
CreatedAtUtc = session.CreatedAtUtc,
|
||||
LastAccessAtUtc = session.LastAccessAtUtc,
|
||||
ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl),
|
||||
Files = vectors
|
||||
.Select(v => GetMetadata(v.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName))
|
||||
Files = [.. vectors
|
||||
.Select(v => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName))
|
||||
.Where(f => !f.IsNullOrEmpty())
|
||||
.Distinct()
|
||||
.ToList()
|
||||
.Distinct()]
|
||||
};
|
||||
|
||||
//
|
||||
@@ -647,7 +653,7 @@ namespace xAiApi.Controllers
|
||||
.Select(c =>
|
||||
{
|
||||
//
|
||||
var chunkIndexText = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataChunkIndex);
|
||||
var chunkIndexText = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataChunkIndex);
|
||||
var text = c.Text ?? string.Empty;
|
||||
var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength);
|
||||
|
||||
@@ -658,7 +664,7 @@ namespace xAiApi.Controllers
|
||||
Identifier = c.Identifier,
|
||||
Snippet = text.Substring(0, snippetLength),
|
||||
ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null,
|
||||
FileName = GetMetadata(c.Metadata, apiConfiguration.RAGDescriptor.MetadataFileName)
|
||||
FileName = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)
|
||||
};
|
||||
})
|
||||
.ToList();
|
||||
@@ -667,36 +673,19 @@ namespace xAiApi.Controllers
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Safe Metadata Reader ...
|
||||
/// </summary>
|
||||
private string GetMetadata(
|
||||
IDictionary<string, string> metadata,
|
||||
string key
|
||||
)
|
||||
{
|
||||
//
|
||||
if (metadata.IsNullOrDefault() || !metadata.TryGetValue(key, out var value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write a SSE Event ...
|
||||
/// </summary>
|
||||
private async Task WriteChunk(
|
||||
private Task WriteChunk(
|
||||
XAiDocumentAnswerChunk chunk,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
//
|
||||
var payload = chunk.ToJSON(camelCase: true);
|
||||
await Response.WriteAsync($"data: {payload}\n\n", cancellationToken);
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
return Response.WriteSseEventAsync(
|
||||
data: chunk,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
@@ -3,9 +3,11 @@ using xAiApi.Models;
|
||||
using System.Threading;
|
||||
using xAiApi.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xAiModels.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xHttpService.Extensions;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -45,10 +47,13 @@ namespace xAiApi.Controllers
|
||||
//
|
||||
#region Ingest ...
|
||||
/// <summary>
|
||||
/// Ingest Files into Current User's Knowledge Base:
|
||||
/// Ingest Files into a Knowledge Scope:
|
||||
/// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
|
||||
/// </summary>
|
||||
/// <param name="files"></param>
|
||||
/// <param name="scope">Target Scope: User (default) / Project / Conversation / Global (Admin)</param>
|
||||
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
|
||||
/// <param name="knowledgeType">Optional Knowledge Type / Domain</param>
|
||||
/// <param name="replaceExisting">Replace Previously Stored Vectors of Same File (default true)</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
@@ -56,6 +61,8 @@ namespace xAiApi.Controllers
|
||||
[Consumes("multipart/form-data")]
|
||||
public async Task<ActionResult<XAiKnowledgeIngestResult>> Ingest(
|
||||
[FromForm] IFormFileCollection files,
|
||||
[FromForm] XAiKnowledgeScope scope = XAiKnowledgeScope.Global,
|
||||
[FromForm] Guid? scopeId = null,
|
||||
[FromForm] string knowledgeType = null,
|
||||
[FromForm] bool replaceExisting = true,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -80,9 +87,9 @@ namespace xAiApi.Controllers
|
||||
files: files,
|
||||
userInfo: userInfo,
|
||||
connectionId: connectionId,
|
||||
knowledgeType: knowledgeType,
|
||||
replaceExisting: replaceExisting,
|
||||
cancellationToken: cancellationToken
|
||||
cancellationToken: cancellationToken,
|
||||
scope: BuildScope(scope, scopeId, knowledgeType)
|
||||
);
|
||||
|
||||
//
|
||||
@@ -155,56 +162,58 @@ namespace xAiApi.Controllers
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
Response.ContentType = "application/json; charset=utf-8";
|
||||
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
// Configure SSE Response Headers ...
|
||||
Response.Headers["X-Accel-Buffering"] = "no";
|
||||
Response.Headers["Connection"] = "keep-alive";
|
||||
Response.Headers["Content-Type"] = "text/event-stream";
|
||||
Response.Headers["Cache-Control"] = "no-cache, no-store";
|
||||
await using var enumerator = ragService
|
||||
.AskWithRAGAsEnumerable(
|
||||
request: request,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
)
|
||||
.GetAsyncEnumerator(cancellationToken);
|
||||
|
||||
//
|
||||
// Disable Response Buffering ...
|
||||
var responseBodyFeature = HttpContext.Features
|
||||
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
|
||||
responseBodyFeature?.DisableBuffering();
|
||||
// Pull First Item before Starting Stream, so Scope / Ownership /
|
||||
// Retrieval Errors are Returned as Regular Http Errors ...
|
||||
var hasItem = await enumerator.MoveNextAsync();
|
||||
|
||||
//
|
||||
var enumerable = ragService.AskWithRAGAsEnumerable(
|
||||
request: request,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
// Configure SSE Response ...
|
||||
Response.PrepareSseResponse();
|
||||
|
||||
//
|
||||
await foreach (var chunk in enumerable)
|
||||
while (hasItem)
|
||||
{
|
||||
//
|
||||
if (chunk.IsNullOrDefault())
|
||||
var chunk = enumerator.Current;
|
||||
if (!chunk.IsNullOrDefault())
|
||||
{
|
||||
continue;
|
||||
await WriteChunk(chunk, cancellationToken);
|
||||
}
|
||||
|
||||
//
|
||||
await WriteChunk(chunk, cancellationToken);
|
||||
hasItem = await enumerator.MoveNextAsync();
|
||||
}
|
||||
|
||||
//
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||
{
|
||||
// Client Disconnected ...
|
||||
}
|
||||
@@ -212,16 +221,16 @@ namespace xAiApi.Controllers
|
||||
{
|
||||
//
|
||||
Logger.LogError(ex, "Knowledge: AskStream Failed");
|
||||
try
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
//
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
}
|
||||
await Response.Body.FlushAsync(CancellationToken.None);
|
||||
var result = GetExceptionActionResult(ex);
|
||||
await result.ExecuteResultAsync(ControllerContext);
|
||||
return;
|
||||
}
|
||||
catch { /* ignore */ }
|
||||
|
||||
//
|
||||
await Response.WriteSseErrorAsync(ex.Message);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
@@ -229,12 +238,18 @@ namespace xAiApi.Controllers
|
||||
//
|
||||
#region Documents ...
|
||||
/// <summary>
|
||||
/// List Ingested Documents of Current User ...
|
||||
/// List Ingested Documents of a Knowledge Scope ...
|
||||
/// </summary>
|
||||
/// <param name="scope">User (default) / Project / Conversation / Global</param>
|
||||
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
|
||||
/// <param name="knowledgeType">Optional Knowledge Type Filter</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("Documents")]
|
||||
public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
|
||||
[FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User,
|
||||
[FromQuery] Guid? scopeId = null,
|
||||
[FromQuery] string knowledgeType = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
@@ -247,7 +262,8 @@ namespace xAiApi.Controllers
|
||||
//
|
||||
var result = await ragService.LoadDocumentsAsync(
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
cancellationToken: cancellationToken,
|
||||
scope: BuildScope(scope, scopeId, knowledgeType)
|
||||
);
|
||||
|
||||
//
|
||||
@@ -262,14 +278,18 @@ namespace xAiApi.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove All Vectors of a Document ...
|
||||
/// Remove All Vectors of a Document in a Knowledge Scope ...
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="scope">User (default) / Project / Conversation / Global (Admin)</param>
|
||||
/// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns>Count of Removed Vectors</returns>
|
||||
[HttpDelete("Documents")]
|
||||
public async Task<ActionResult<int>> DeleteDocument(
|
||||
[FromQuery] string fileName,
|
||||
[FromQuery] XAiKnowledgeScope scope = XAiKnowledgeScope.User,
|
||||
[FromQuery] Guid? scopeId = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
@@ -287,7 +307,8 @@ namespace xAiApi.Controllers
|
||||
var result = await ragService.RemoveDocumentAsync(
|
||||
fileName: fileName,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
cancellationToken: cancellationToken,
|
||||
scope: BuildScope(scope, scopeId, null)
|
||||
);
|
||||
|
||||
//
|
||||
@@ -304,18 +325,40 @@ namespace xAiApi.Controllers
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
/// <summary>
|
||||
/// Build Scope Descriptor from Request Params ...
|
||||
/// </summary>
|
||||
private XAiKnowledgeScopeDescriptor BuildScope(
|
||||
XAiKnowledgeScope scope,
|
||||
Guid? scopeId,
|
||||
string knowledgeType
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = new XAiKnowledgeScopeDescriptor
|
||||
{
|
||||
Scope = scope,
|
||||
ScopeId = scopeId,
|
||||
Type = knowledgeType,
|
||||
};
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write a SSE Event ...
|
||||
/// </summary>
|
||||
private async Task WriteChunk(
|
||||
private Task WriteChunk(
|
||||
XAiDocumentAnswerChunk chunk,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
//
|
||||
var payload = chunk.ToJSON(camelCase: true);
|
||||
await Response.WriteAsync($"data: {payload}\n\n", cancellationToken);
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
return Response.WriteSseEventAsync(
|
||||
data: chunk,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
@@ -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.Extensions;
|
||||
using xCommons.Controllers;
|
||||
using xExceptions.Constants;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xAiApi.Controllers
|
||||
{
|
||||
@@ -41,5 +44,20 @@ namespace xAiApi.Controllers
|
||||
//
|
||||
return Ok(message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Global Exception Handler Endpoint (Production) ...
|
||||
/// Returns a Generic Error without Leaking Exception Details ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[Route("error")]
|
||||
[ApiExplorerSettings(IgnoreApi = true)]
|
||||
public virtual ActionResult Error()
|
||||
{
|
||||
//
|
||||
var error = XException.ActionFailed.ToXError();
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
using System;
|
||||
using xModels.Dtos;
|
||||
using System.Text.Json;
|
||||
using xIdentityHelper;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xAiApi.Extensions;
|
||||
using xAiApi.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Extensions;
|
||||
@@ -10,6 +11,7 @@ using xAiModels.Extensions;
|
||||
using xAiModels.Models.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xHttpService.Extensions;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -18,7 +20,6 @@ using xIdentityService.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xIdentityService.Controllers;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using System.Linq;
|
||||
|
||||
namespace xAiApi.Controllers
|
||||
{
|
||||
@@ -53,8 +54,8 @@ namespace xAiApi.Controllers
|
||||
/// <param name="question"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[HttpGet("AskText")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public virtual async Task<ActionResult<string>> AskText(
|
||||
[FromQuery] string question,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -90,39 +91,27 @@ namespace xAiApi.Controllers
|
||||
/// <param name="question"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[HttpGet("AskTextStream")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public virtual async Task AskTextStream(
|
||||
[FromQuery] string question,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||
if (question.IsNullOrEmpty())
|
||||
{
|
||||
await WriteStreamValidationError();
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
ValidationProvider.NotEmpty(question);
|
||||
|
||||
//
|
||||
// Configure SSE Response Headers ...
|
||||
Response.Headers["X-Accel-Buffering"] = "no";
|
||||
Response.Headers["Connection"] = "keep-alive";
|
||||
Response.Headers["Content-Type"] = "text/event-stream";
|
||||
Response.Headers["Cache-Control"] = "no-cache, no-store";
|
||||
|
||||
//
|
||||
// Disable response buffering ...
|
||||
var responseBodyFeature = HttpContext.Features
|
||||
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
|
||||
responseBodyFeature?.DisableBuffering();
|
||||
|
||||
//
|
||||
// Stream Response ...
|
||||
var jsonOptions = new JsonSerializerOptions
|
||||
{
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
// Configure SSE Response ...
|
||||
Response.PrepareSseResponse();
|
||||
|
||||
//
|
||||
var enumerable = aiService.AskTextAsEnumerable(
|
||||
@@ -131,37 +120,58 @@ namespace xAiApi.Controllers
|
||||
);
|
||||
|
||||
//
|
||||
// Format: data: {"text":"..."}\n\n
|
||||
await foreach (var chunk in enumerable)
|
||||
{
|
||||
//
|
||||
// Skip empty chunks ...
|
||||
// Skip Empty Chunks ...
|
||||
if (string.IsNullOrEmpty(chunk))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
// Build SSE message ...
|
||||
// Format: data: <json>\n\n
|
||||
// var payload = JsonSerializer.Serialize(
|
||||
// new { text = chunk },
|
||||
// jsonOptions
|
||||
// );
|
||||
var payload = chunk;
|
||||
|
||||
//
|
||||
// Write SSE Event ...
|
||||
await Response.WriteAsync($"{payload}\n\n", cancellationToken);
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseEventAsync(
|
||||
data: new { text = chunk },
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||
{
|
||||
await Response.Body.FlushAsync();
|
||||
// Client Disconnected ...
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
Logger.LogError(ex, "AskTextStream Failed");
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
await result.ExecuteResultAsync(ControllerContext);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
await Response.WriteSseErrorAsync(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write Validation Error for Streaming Endpoints (before Stream Starts) ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[NonAction]
|
||||
protected async Task WriteStreamValidationError()
|
||||
{
|
||||
//
|
||||
Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
Response.ContentType = "application/json; charset=utf-8";
|
||||
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
|
||||
}
|
||||
#endregion
|
||||
|
||||
@@ -174,6 +184,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("Projects")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<IEnumerable<XAiProjectDto>>> LoadProjects(
|
||||
[FromQuery] bool includeDefaults = false,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -211,6 +222,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="projectId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Projects/{projectId}/Conversations")]
|
||||
public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations(
|
||||
[FromRoute] Guid projectId,
|
||||
@@ -255,6 +267,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="conversationId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Conversations/{conversationId}/Messages")]
|
||||
public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages(
|
||||
[FromRoute] Guid conversationId,
|
||||
@@ -300,6 +313,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("Projects/Query")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XQueryResult<XAiProjectDto>>> QueryProjects(
|
||||
[FromQuery] XQuery query,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -337,6 +351,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="query"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Projects/{projectId}/Conversations/Query")]
|
||||
public async Task<ActionResult<XQueryResult<XAiConversationDto>>> QueryConversations(
|
||||
[FromRoute] Guid projectId,
|
||||
@@ -377,6 +392,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="query"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Conversations/{conversationId}/Messages/Query")]
|
||||
public async Task<ActionResult<XQueryResult<XAiMessageDto>>> QueryMessages(
|
||||
[FromRoute] Guid conversationId,
|
||||
@@ -420,6 +436,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("Projects")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XAiProjectDto>> CreateProject(
|
||||
[FromBody] XAiProjectDto item,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -473,6 +490,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="item"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPost("Projects/{projectId}/Conversations")]
|
||||
public async Task<ActionResult<XAiConversationDto>> CreateConversation(
|
||||
[FromRoute] Guid projectId,
|
||||
@@ -535,9 +553,10 @@ namespace xAiApi.Controllers
|
||||
/// <returns></returns>
|
||||
[HttpPost("ExtractContent")]
|
||||
[Consumes("multipart/form-data")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<string>> ExtractContent(
|
||||
[FromForm] IFormFileCollection files,
|
||||
[FromForm] string extractors = null,
|
||||
[FromForm] string extractors = "*",
|
||||
CancellationToken cancellationToken = default
|
||||
) {
|
||||
//
|
||||
@@ -588,6 +607,7 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("Ask")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<string>> Ask(
|
||||
[FromBody] XAiResponseRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -637,37 +657,30 @@ namespace xAiApi.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("AskStream")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task AskStream(
|
||||
[FromBody] XAiResponseRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate (before Stream Starts -> Proper Http Error) ...
|
||||
if (!request.IsValid())
|
||||
{
|
||||
await WriteStreamValidationError();
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!request.IsValid())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
var connectionId = GetConnectionId();
|
||||
|
||||
//
|
||||
// Configure SSE Response Headers ...
|
||||
Response.Headers["X-Accel-Buffering"] = "no";
|
||||
Response.Headers["Connection"] = "keep-alive";
|
||||
Response.Headers["Content-Type"] = "text/event-stream";
|
||||
Response.Headers["Cache-Control"] = "no-cache, no-store";
|
||||
|
||||
//
|
||||
// Disable response buffering ...
|
||||
var responseBodyFeature = HttpContext.Features
|
||||
.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>();
|
||||
responseBodyFeature?.DisableBuffering();
|
||||
// Configure SSE Response ...
|
||||
Response.PrepareSseResponse();
|
||||
|
||||
//
|
||||
// TODO: Reading Fiels Form Collection and Attach it ...
|
||||
@@ -682,6 +695,7 @@ namespace xAiApi.Controllers
|
||||
);
|
||||
|
||||
//
|
||||
// Format: data: {json}\n\n
|
||||
await foreach (var resp in enumerable)
|
||||
{
|
||||
//
|
||||
@@ -692,20 +706,33 @@ namespace xAiApi.Controllers
|
||||
}
|
||||
|
||||
//
|
||||
var payload = resp.ToJSON(camelCase: true);
|
||||
|
||||
//
|
||||
// Write SSE Event ...
|
||||
await Response.WriteAsync($"{payload}", cancellationToken);
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseEventAsync(
|
||||
data: resp,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
await Response.Body.FlushAsync(cancellationToken);
|
||||
await Response.WriteSseDoneAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
||||
{
|
||||
await Response.Body.FlushAsync();
|
||||
// Client Disconnected ...
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
Logger.LogError(ex, "AskStream Failed");
|
||||
if (!Response.HasStarted)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
await result.ExecuteResultAsync(ControllerContext);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
await Response.WriteSseErrorAsync(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,6 +744,7 @@ namespace xAiApi.Controllers
|
||||
/// <returns></returns>
|
||||
[HttpPost("AskWithFiles")]
|
||||
[Consumes("multipart/form-data")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<string>> AskWithFiles(
|
||||
[FromForm] XAiResponseRequest request,
|
||||
[FromForm] IFormFileCollection files,
|
||||
|
||||
Reference in New Issue
Block a user