- XAIServiceBase: add PrepareChatRequirementsAsync as the single entry point for chat prerequisites (normalize RAG params, resolve default project/conversation, ingest attachments, retrieve RAG context, build history, persist prompt message) and return the new XPreparedChatContext; - XAIServiceBase: add NormalizeRagParams (topK / minScore / type) and use it in all Ask* methods instead of duplicated inline normalization; - XAIServiceBase: rework GetHistory - the single GetHistory(ChatMessage, bool) signature is replaced by two overloads GetHistory(prompt, forcePrompt) and GetHistory(prompt, context); the latter is used by the non-persisted chat path; - XAIServiceBase: remove AskLLMAsync; LLM invocation is now inlined in each Ask* method over prep.History; - XAIServiceBase: rewrite AskAsync and AskAsEnumerable on top of PrepareChatRequirementsAsync; streamed responses now use Role = Assistant, RespondTo = prep.PersistedPromptMessage.Id and Sequence++; - XAIServiceBase: use XAiApiConstants.XAiApiRagPromptName instead of configuration.RAGDescriptor.PromptName; - XAIServiceBase.LoadConversations: call the renamed GetDafaultProject; - Add Models/XPreparedChatContext.cs (Project, Conversation, History, Context, PersistedPromptMessage) as the shared context between actions; - XAiRAGService: wrap each file ingest in its own try/catch with logger.LogError so one bad file no longer aborts the whole ingest; - XAiRAGService: upload the file and add a scope reference (providedFor / forProvidedId) for the ingested scope; - XAiRAGService: remove stale vectors of the same document via RemoveVectorsAsync(identifierPrefix) when replaceExisting is set; - XInMemoryVectorStore: make session retrieval thread-safe via lock (found.SyncRoot) and ReferenceEquals check against concurrent removal; - XAiServiceControllerBase.Ask: pass the attached files to the AI service (was files: null) so RAG works on attachments; - XModelsExtensions: relax ChatWithDocuments ask validation - TopK and MinScore are optional again (defaults come from RAGDescriptor); - XAiModelProxyMiddleware: use logical OR instead of bitwise OR in the authentication check; - XAiEmbeddingServiceBase: do not dispose the embedding generator (removed `using` to avoid premature disposal); - ChatWithDocumentsController: reorder EmbedChunks parameters; - Remove Interfaces/IXAiEmbeddingServiceControllerBase.cs.
315 lines
11 KiB
C#
315 lines
11 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Net.Http;
|
|
using System.Threading;
|
|
using xAiApi.Extensions;
|
|
using xCommons.Constants;
|
|
using xCommons.Extensions;
|
|
using xAiModels.Extensions;
|
|
using xAiApi.Configurations;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Net.Http.Headers;
|
|
using xIdentityService.Constants;
|
|
using xIdentityService.Interfaces;
|
|
using xIdentityService.Extensions;
|
|
using Microsoft.Extensions.Logging;
|
|
using xExceptions.Constants;
|
|
using xIdentityModels.Models;
|
|
using xIdentityModels.Constants;
|
|
|
|
namespace xAiApi.Middlewares
|
|
{
|
|
public class XAiModelProxyMiddleware
|
|
{
|
|
private readonly RequestDelegate next;
|
|
private readonly XAiApiConfiguration configuration;
|
|
private readonly IHttpClientFactory httpClientFactory;
|
|
private readonly ILogger<XAiModelProxyMiddleware> logger;
|
|
|
|
public XAiModelProxyMiddleware(
|
|
RequestDelegate next,
|
|
XAiApiConfiguration configuration,
|
|
IHttpClientFactory httpClientFactory,
|
|
ILogger<XAiModelProxyMiddleware> logger
|
|
)
|
|
{
|
|
//
|
|
this.next = next;
|
|
this.logger = logger;
|
|
this.configuration = configuration;
|
|
this.httpClientFactory = httpClientFactory;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle Routing ...
|
|
/// </summary>
|
|
/// <param name="context"></param>
|
|
/// <returns></returns>
|
|
public async Task InvokeAsync(
|
|
HttpContext context,
|
|
IXIdentityProvider identityProvider
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
var isValid =
|
|
!configuration.IsNull() &&
|
|
!configuration.ProxyConfiguration.IsNull() &&
|
|
configuration.ProxyConfiguration.Enabled &&
|
|
!configuration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty() &&
|
|
context.Request.Path.StartsWithSegments(configuration.ProxyConfiguration.RoutePrefix, out var remaining);
|
|
if (!isValid)
|
|
{
|
|
//
|
|
await next(context);
|
|
return;
|
|
}
|
|
|
|
//
|
|
// Validating Segment ...
|
|
var rawSegments = remaining.Value?
|
|
.Trim('/')
|
|
.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
|
if (!rawSegments.HasChild())
|
|
{
|
|
//
|
|
await next(context);
|
|
return;
|
|
}
|
|
|
|
//
|
|
// Extract Model Name and Retrieve Model Descriptor and do Validation ...
|
|
var modelName = Uri.UnescapeDataString(rawSegments[0]);
|
|
var descriptor = configuration.GetModel(modelName);
|
|
if (!descriptor.IsValid())
|
|
{
|
|
//
|
|
// Handle Error ...
|
|
await context.Response.WriteJsonAsync(
|
|
status: HttpStatusCode.NotFound,
|
|
data: new
|
|
{
|
|
error = $"Model '{modelName}' is not configured."
|
|
}
|
|
);
|
|
return;
|
|
}
|
|
|
|
//
|
|
var errorMessages = new string[] { };
|
|
var apiKey = context.ExtractApiKey();
|
|
var clientIP = context.Request.ExtractClientIP();
|
|
var tokenModel = await context.RetrieveTokensAsXTokenResponse();
|
|
var isAuthenticated =
|
|
//
|
|
(!apiKey.IsNullOrEmpty()) ||
|
|
//
|
|
(!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
|
|
;
|
|
if (isAuthenticated)
|
|
{
|
|
//
|
|
// Handle Authentication ...
|
|
if (!apiKey.IsNullOrEmpty())
|
|
{
|
|
//
|
|
// Try to Validate Api Key ...
|
|
var validationResult = await identityProvider.ValidateApiKey(
|
|
request: new XApiKeyValidationRequest
|
|
{
|
|
ApiKey = apiKey,
|
|
ClientIP = clientIP,
|
|
RequiredScope = XApiKeyScope.Read.GetStringValue()
|
|
}
|
|
);
|
|
isAuthenticated = !validationResult.Errors.HasChild();
|
|
if (!isAuthenticated)
|
|
{
|
|
errorMessages = [.. errorMessages, .. validationResult.Errors];
|
|
}
|
|
}
|
|
else if (!tokenModel.IsNullOrDefault())
|
|
{
|
|
//
|
|
// Try To Validate Token ...
|
|
var validationResult = await identityProvider.Validate(tokenModel);
|
|
isAuthenticated = !validationResult.IsError;
|
|
if (!isAuthenticated)
|
|
{
|
|
errorMessages = [..errorMessages, validationResult.Error];
|
|
}
|
|
}
|
|
else
|
|
{
|
|
isAuthenticated = false;
|
|
}
|
|
}
|
|
if (!isAuthenticated)
|
|
{
|
|
//
|
|
var error = XException.NotAuthorized.ToXError();
|
|
error.Message = $"{error.Message}: {errorMessages.ToListString(',')}";
|
|
await context.Response.WriteJsonAsync(
|
|
status: HttpStatusCode.Unauthorized,
|
|
data: error
|
|
);
|
|
return;
|
|
}
|
|
|
|
//
|
|
var suffixPath = Uri.UnescapeDataString(string.Join('/', rawSegments.Skip(1)));
|
|
var targetUri = BuildTargetUri(
|
|
descriptor.Url,
|
|
suffixPath,
|
|
context.Request.QueryString
|
|
);
|
|
|
|
//
|
|
// Collect Headers which need to Except ...
|
|
var exceptionHeaders = new string[]
|
|
{
|
|
XAuthorization.Header,
|
|
XAuthorization.ExpiresAt,
|
|
XAuthorization.XPoweredBy,
|
|
XAuthorization.AccessToken,
|
|
XAuthorization.RefreshToken,
|
|
XHeader.ApiKey.GetStringValue(),
|
|
XAuthorization.AccessTokenExpired,
|
|
XHeader.ConnectionId.GetStringValue(),
|
|
XHeader.ChecksumDigest.GetStringValue(),
|
|
};
|
|
|
|
//
|
|
using var upstreamRequest = new HttpRequestMessage(
|
|
new HttpMethod(context.Request.Method),
|
|
targetUri
|
|
);
|
|
|
|
//
|
|
context.CopyRequestHeaders(
|
|
dest: upstreamRequest,
|
|
exceptions: exceptionHeaders
|
|
);
|
|
|
|
//
|
|
if (
|
|
context.Request.ContentLength > 0 ||
|
|
context.Request.Headers.ContainsKey(HeaderNames.TransferEncoding)
|
|
)
|
|
{
|
|
//
|
|
context.Request.EnableBuffering();
|
|
using var reader = new StreamReader(
|
|
context.Request.Body,
|
|
Encoding.UTF8,
|
|
detectEncodingFromByteOrderMarks: true,
|
|
bufferSize: 1024,
|
|
leaveOpen: true
|
|
);
|
|
var bodyText = await reader.ReadToEndAsync();
|
|
var actualLength = Encoding.UTF8.GetByteCount(bodyText);
|
|
var declaredLength = context.Request.ContentLength;
|
|
var contentType = context.Request.ContentType ?? "application/octet-stream";
|
|
var mediaType = contentType.Split(';')[0].Trim();
|
|
upstreamRequest.Content = new StringContent(
|
|
bodyText,
|
|
Encoding.UTF8,
|
|
mediaType
|
|
);
|
|
context.Request.Body.Position = 0;
|
|
context.CopyRequestHeaders(
|
|
dest: upstreamRequest.Content,
|
|
exceptions: exceptionHeaders
|
|
);
|
|
}
|
|
|
|
//
|
|
// Handle Api Key of LLM ...
|
|
descriptor.AddModelDescriptorApiKey(
|
|
request: upstreamRequest
|
|
);
|
|
|
|
//
|
|
try
|
|
{
|
|
//
|
|
var client = httpClientFactory.CreateClient("XAiModelProxy");
|
|
client.Timeout = Timeout.InfiniteTimeSpan;
|
|
|
|
//
|
|
using var upstreamResponse = await client.SendAsync(
|
|
upstreamRequest,
|
|
HttpCompletionOption.ResponseHeadersRead,
|
|
context.RequestAborted
|
|
);
|
|
|
|
//
|
|
context.Response.StatusCode = (int)upstreamResponse.StatusCode;
|
|
|
|
//
|
|
upstreamResponse.CopyHeaders(
|
|
response: context.Response,
|
|
exceptions: exceptionHeaders
|
|
);
|
|
|
|
//
|
|
await using var responseStream = await upstreamResponse.Content
|
|
.ReadAsStreamAsync();
|
|
await responseStream.CopyToAsync(
|
|
context.Response.Body,
|
|
context.RequestAborted
|
|
);
|
|
}
|
|
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
|
|
{ }
|
|
catch (Exception ex)
|
|
{
|
|
//
|
|
logger.LogError(ex, "Proxy failed for model {ModelName}", modelName);
|
|
if (!context.Response.HasStarted)
|
|
{
|
|
//
|
|
// Handle Error ...
|
|
var error = XException.ActionFailed.ToXError();
|
|
error.Message = $"{error.Message}: {ex.Message}";
|
|
await context.Response.WriteJsonAsync(
|
|
status: HttpStatusCode.BadGateway,
|
|
data: error
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
//
|
|
#region Private ...
|
|
private static Uri BuildTargetUri(
|
|
string baseUrl,
|
|
string suffixPath,
|
|
QueryString query
|
|
)
|
|
{
|
|
//
|
|
var baseUri = new Uri(baseUrl, UriKind.Absolute);
|
|
var builder = new UriBuilder(baseUri);
|
|
var basePath = builder.Path.TrimEnd('/');
|
|
|
|
//
|
|
builder.Path = suffixPath.IsNullOrEmpty()
|
|
? basePath
|
|
: $"{basePath}/{suffixPath.TrimStart('/')}";
|
|
|
|
//
|
|
builder.Query = query.HasValue
|
|
? query.Value.TrimStart('?')
|
|
: string.Empty;
|
|
|
|
//
|
|
return builder.Uri;
|
|
}
|
|
#endregion
|
|
}
|
|
} |