Files
xSaherElmAiApi/Providers/XAiEmbeddingServiceBase.cs
T
saherelm a870d61e61 Refactor Chat Pipeline into PrepareChatRequirementsAsync and Harden RAG Services
- 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.
2026-11-02 16:37:57 +03:30

226 lines
6.7 KiB
C#

using System;
using OpenAI;
using System.Linq;
using OllamaSharp;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xAiModels.Helpers;
using System.ClientModel;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Extensions;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using System.ClientModel.Primitives;
namespace xAiApi.Providers
{
/// <summary>
/// Base Embedding Provider Service ...
/// </summary>
public abstract class XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase
{
private readonly string embeddingModelName;
private readonly XAiModelDescriptor descriptor;
private readonly IXAiDataProvider dataProvider;
private readonly XAiApiConfiguration configuration;
private readonly XValidationProvider validationProvider;
private readonly ILogger<XAiEmbeddingServiceBase> logger;
private readonly IXFileContentExtractor fileContentExtractor;
protected XAiEmbeddingServiceBase(
IXAiDataProvider dataProvider,
XAiApiConfiguration configuration,
XValidationProvider validationProvider,
ILogger<XAiEmbeddingServiceBase> logger,
IXFileContentExtractor fileContentExtractor,
string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
)
{
//
// Prepare Embedding Model Descriptor ...
descriptor = configuration.GetModel(embeddingModelName);
if (!descriptor.IsValid())
{
XException.InvalidConfiguration.Throw();
}
this.dataProvider = dataProvider;
this.configuration = configuration;
this.validationProvider = validationProvider;
//
this.logger = logger;
this.fileContentExtractor = fileContentExtractor;
this.embeddingModelName = embeddingModelName;
}
/// <summary>
/// Embedding Specified String ...
/// </summary>
/// <param name="content"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<float[]> Embedding(
string content,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (content.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var generator = GetEmbeddingGenerator();
//
GeneratedEmbeddings<Embedding<float>> response = null;
response = await generator.GenerateAsync(
values: [content],
cancellationToken: cancellationToken
);
//
if (response.IsNullOrDefault())
{
XException.ActionFailed.Throw();
}
//
// Generae Result ...
var result = response
.First()?
.Vector
.ToArray()
?? [];
if (result.Length == 0)
{
XException.ActionFailed.Throw();
}
//
// Normalize ...
VectorHelper.Normalize(result);
//
return result;
}
/// <summary>
/// Embedding Specified Batch ...
/// </summary>
/// <param name="batch"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IReadOnlyList<float[]>> Embeddings(
string[] batch,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!batch.HasChild() ||
!batch.All(x => !x.IsNullOrEmpty())
)
{
XException.InvalidArgs.Throw();
}
//
using var generator = GetEmbeddingGenerator();
//
GeneratedEmbeddings<Embedding<float>> response = null;
response = await generator.GenerateAsync(
values: [.. batch],
cancellationToken: cancellationToken
);
//
if (response.IsNullOrDefault())
{
XException.ActionFailed.Throw();
}
//
var result = response
.Select(e => e.Vector.ToArray())
.ToList();
//
// Normalize ...
foreach (var vector in result)
{
VectorHelper.Normalize(vector);
}
//
return result;
}
/// <summary>
/// Embedding Generator ...
/// </summary>
/// <returns></returns>
public IEmbeddingGenerator<string, Embedding<float>> GetEmbeddingGenerator()
{
//
IEmbeddingGenerator<string, Embedding<float>> result = null;
//
if (!descriptor.IsValid())
{
XException.InvalidData.Throw("Invalid Embedding Model ...");
}
//
switch (descriptor.Provider)
{
//
case XAiModelProviderType.OpenAI:
//
var openAiClient = new OpenAIClient(
new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : descriptor.ApiKey),
new OpenAIClientOptions
{
Endpoint = new Uri(descriptor.Url),
Transport = new HttpClientPipelineTransport(descriptor.Url.GetHttpClient())
}
);
result = openAiClient
.GetEmbeddingClient(descriptor.LLM)
.AsIEmbeddingGenerator();
break;
//
case XAiModelProviderType.Ollama:
//
var ollamaClient = new OllamaApiClient(new Uri(descriptor.Url));
result = ollamaClient;
break;
}
//
if (result.IsNull())
{
XException.InvalidData.Throw("Invalid Embedding Model ...");
}
//
return result;
}
}
}