Integrate RAG into Chat Pipeline and Decouple Embedding Service
- AskAsync: accept Guid? projectId / conversationId; resolve defaults;
- AskAsync: ingest attached files into Conversation scope (replaceExisting)
via IXAiRAGService instead of Upload + Extract + raw content attachment;
- AskAsync: retrieve context (Conversation -> Project -> User -> Global)
and build a single System message: Introduction + ChatWithDocuments prompt
+ Context block (+ Project prompt);
- XAIServiceBase / XDefaultAiService / XDefaultThinkingAiService:
inject IXAiRAGService instead of IXFileProvider;
- Add IXAiEmbeddingService + XAiEmbeddingService; remove
IXDefaultEmbeddingService + XDefaultEmbeddingService;
- XAiEmbeddingServiceBase no longer inherits XAIServiceBase;
IXAiEmbeddingServiceBase / IXAiEmbeddingServiceControllerBase no longer
extend chat interfaces; XAiEmbeddingServiceControllerBase derives from
XBaseIdentityApiV1Controller;
- XAiRAGService: drop IXDefaultAiService dependency (removes circular
dependency); remove AskWithRAGAsync / AskWithRAGAsEnumerable; add file
reference (AddReference) for scoped ingests;
- KnowledgeController: remove POST Ask and POST AskStream;
- DI: add AddXRagService() and call it from Startup before AddXAiServices();
- Add XAiApiRagPromptName = "ChatWithDocuments";
- Knowledge scope factories default Type to XAiDefaultKnowledgeType;
- ChatWithDocuments ask request: TopK and MinScore are now required.
BREAKING: /Knowledge/Ask and /Knowledge/AskStream removed;
IXDefaultEmbeddingService replaced by IXAiEmbeddingService.
This commit is contained in:
@@ -11,6 +11,7 @@ namespace xAiApi.Constants
|
|||||||
public const string XDILogTag = "XAiApi";
|
public const string XDILogTag = "XAiApi";
|
||||||
|
|
||||||
//
|
//
|
||||||
|
public const string XAiApiRagPromptName = "ChatWithDocuments";
|
||||||
public const string XAiApiIntroductionPromptName = "Introduction";
|
public const string XAiApiIntroductionPromptName = "Introduction";
|
||||||
public const string XAiApiContentExtractionPromptName = "ContentExtraction";
|
public const string XAiApiContentExtractionPromptName = "ContentExtraction";
|
||||||
|
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ namespace xAiApi.Controllers
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Embedding Service ...
|
/// Embedding Service ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private readonly IXDefaultEmbeddingService embeddingService;
|
private readonly IXAiEmbeddingService embeddingService;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// File Context Extractor Service ...
|
/// File Context Extractor Service ...
|
||||||
@@ -68,8 +68,8 @@ namespace xAiApi.Controllers
|
|||||||
XAppConfiguration appConfiguration,
|
XAppConfiguration appConfiguration,
|
||||||
IXIdentityProvider identityProvider,
|
IXIdentityProvider identityProvider,
|
||||||
XAiApiConfiguration apiConfiguration,
|
XAiApiConfiguration apiConfiguration,
|
||||||
|
IXAiEmbeddingService embeddingService,
|
||||||
XValidationProvider validationProvider,
|
XValidationProvider validationProvider,
|
||||||
IXDefaultEmbeddingService embeddingService,
|
|
||||||
ILogger<ChatWithDocumentsController> logger,
|
ILogger<ChatWithDocumentsController> logger,
|
||||||
IXFileContentExtractor fileContentExtractor
|
IXFileContentExtractor fileContentExtractor
|
||||||
) : base(logger, appConfiguration, identityProvider, validationProvider)
|
) : base(logger, appConfiguration, identityProvider, validationProvider)
|
||||||
|
|||||||
@@ -10,20 +10,20 @@ namespace xAiApi.Controllers
|
|||||||
{
|
{
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route("[controller]")]
|
[Route("[controller]")]
|
||||||
public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase<IXDefaultEmbeddingService>
|
public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase<IXAiEmbeddingService>
|
||||||
{
|
{
|
||||||
public DefaultEmbeddingController(
|
public DefaultEmbeddingController(
|
||||||
ILogger<DefaultEmbeddingController> logger,
|
ILogger<DefaultEmbeddingController> logger,
|
||||||
IXDefaultEmbeddingService aiService,
|
IXAiEmbeddingService embeddingService,
|
||||||
XAppConfiguration appConfiguration,
|
XAppConfiguration appConfiguration,
|
||||||
IXIdentityProvider identityProvider,
|
IXIdentityProvider identityProvider,
|
||||||
XValidationProvider validationProvider
|
XValidationProvider validationProvider
|
||||||
) : base(
|
) : base(
|
||||||
logger,
|
logger: logger,
|
||||||
aiService,
|
appConfiguration: appConfiguration,
|
||||||
appConfiguration,
|
identityProvider: identityProvider,
|
||||||
identityProvider,
|
embeddingService: embeddingService,
|
||||||
validationProvider
|
validationProvider: validationProvider
|
||||||
)
|
)
|
||||||
{ }
|
{ }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ namespace xAiApi.Controllers
|
|||||||
XValidationProvider validationProvider
|
XValidationProvider validationProvider
|
||||||
) : base(logger, appConfiguration, identityProvider, validationProvider)
|
) : base(logger, appConfiguration, identityProvider, validationProvider)
|
||||||
{
|
{
|
||||||
//
|
|
||||||
this.ragService = ragService;
|
this.ragService = ragService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,137 +103,6 @@ namespace xAiApi.Controllers
|
|||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
//
|
|
||||||
#region Ask ...
|
|
||||||
/// <summary>
|
|
||||||
/// Ask a Question over Knowledge Base (RAG) ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost("Ask")]
|
|
||||||
public async Task<ActionResult<XAiDocumentAnswer>> Ask(
|
|
||||||
[FromBody] XAiKnowledgeAskRequest request,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
try
|
|
||||||
{
|
|
||||||
//
|
|
||||||
// Validate ...
|
|
||||||
if (request.IsNullOrDefault() || request.Prompt.IsNullOrEmpty())
|
|
||||||
{
|
|
||||||
XException.InvalidArgs.Throw();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
var userInfo = await GetUserInfo();
|
|
||||||
|
|
||||||
//
|
|
||||||
var result = await ragService.AskWithRAGAsync(
|
|
||||||
request: request,
|
|
||||||
userInfo: userInfo,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var result = GetExceptionActionResult(ex);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask a Question over Knowledge Base and Stream Response (SSE) ...
|
|
||||||
/// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has isFinal = true ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpPost("AskStream")]
|
|
||||||
public async Task AskStream(
|
|
||||||
[FromBody] XAiKnowledgeAskRequest request,
|
|
||||||
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
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var userInfo = await GetUserInfo();
|
|
||||||
|
|
||||||
//
|
|
||||||
await using var enumerator = ragService
|
|
||||||
.AskWithRAGAsEnumerable(
|
|
||||||
request: request,
|
|
||||||
userInfo: userInfo,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
)
|
|
||||||
.GetAsyncEnumerator(cancellationToken);
|
|
||||||
|
|
||||||
//
|
|
||||||
// Pull First Item before Starting Stream, so Scope / Ownership /
|
|
||||||
// Retrieval Errors are Returned as Regular Http Errors ...
|
|
||||||
var hasItem = await enumerator.MoveNextAsync();
|
|
||||||
|
|
||||||
//
|
|
||||||
// Configure SSE Response ...
|
|
||||||
Response.PrepareSseResponse();
|
|
||||||
|
|
||||||
//
|
|
||||||
while (hasItem)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var chunk = enumerator.Current;
|
|
||||||
if (!chunk.IsNullOrDefault())
|
|
||||||
{
|
|
||||||
await WriteChunk(chunk, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
hasItem = await enumerator.MoveNextAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
await Response.WriteSseDoneAsync(cancellationToken);
|
|
||||||
}
|
|
||||||
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
|
|
||||||
{
|
|
||||||
// Client Disconnected ...
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
Logger.LogError(ex, "Knowledge: AskStream Failed");
|
|
||||||
if (!Response.HasStarted)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var result = GetExceptionActionResult(ex);
|
|
||||||
await result.ExecuteResultAsync(ControllerContext);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
await Response.WriteSseErrorAsync(ex.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
//
|
//
|
||||||
#region Documents ...
|
#region Documents ...
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -8,32 +8,32 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using xIdentityService.Interfaces;
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using xIdentityService.Controllers;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
namespace xAiApi.Controllers
|
namespace xAiApi.Controllers
|
||||||
{
|
{
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route("[controller]")]
|
[Route("[controller]")]
|
||||||
public abstract class XAiEmbeddingServiceControllerBase<TAiService> : XAiServiceControllerBase<TAiService>, IXAiEmbeddingServiceControllerBase
|
public abstract class XAiEmbeddingServiceControllerBase<TEmbeddingService> : XBaseIdentityApiV1Controller, IXAiEmbeddingServiceControllerBase
|
||||||
where TAiService : IXAiEmbeddingServiceBase
|
where TEmbeddingService : IXAiEmbeddingServiceBase
|
||||||
{
|
{
|
||||||
private readonly TAiService aiService;
|
private readonly TEmbeddingService embeddingService;
|
||||||
|
|
||||||
protected XAiEmbeddingServiceControllerBase(
|
protected XAiEmbeddingServiceControllerBase(
|
||||||
ILogger logger,
|
ILogger logger,
|
||||||
TAiService aiService,
|
|
||||||
XAppConfiguration appConfiguration,
|
XAppConfiguration appConfiguration,
|
||||||
IXIdentityProvider identityProvider,
|
IXIdentityProvider identityProvider,
|
||||||
XValidationProvider validationProvider
|
XValidationProvider validationProvider,
|
||||||
|
TEmbeddingService embeddingService
|
||||||
) : base(
|
) : base(
|
||||||
logger,
|
logger,
|
||||||
aiService,
|
|
||||||
appConfiguration,
|
appConfiguration,
|
||||||
identityProvider,
|
identityProvider,
|
||||||
validationProvider
|
validationProvider
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.aiService = aiService;
|
this.embeddingService = embeddingService;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -57,7 +57,7 @@ namespace xAiApi.Controllers
|
|||||||
ValidationProvider.NotEmpty(content);
|
ValidationProvider.NotEmpty(content);
|
||||||
|
|
||||||
//
|
//
|
||||||
var result = await aiService.Embedding(
|
var result = await embeddingService.Embedding(
|
||||||
content: content,
|
content: content,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
@@ -94,7 +94,7 @@ namespace xAiApi.Controllers
|
|||||||
ValidationProvider.NotZeroChilds(batch);
|
ValidationProvider.NotZeroChilds(batch);
|
||||||
|
|
||||||
//
|
//
|
||||||
var result = await aiService.Embeddings(
|
var result = await embeddingService.Embeddings(
|
||||||
batch: batch,
|
batch: batch,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -689,9 +689,9 @@ namespace xAiApi.Controllers
|
|||||||
prompt: request.Prompt,
|
prompt: request.Prompt,
|
||||||
ownerId: userInfo.UserId,
|
ownerId: userInfo.UserId,
|
||||||
connectionId: connectionId,
|
connectionId: connectionId,
|
||||||
projectId: request.ProjectId,
|
projectId: request.ProjectId.Value,
|
||||||
cancellationToken: cancellationToken,
|
cancellationToken: cancellationToken,
|
||||||
conversationId: request.ConversationId
|
conversationId: request.ConversationId.Value
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -73,6 +73,20 @@ namespace xAiApi.DI
|
|||||||
source.AddSingleton(configuration);
|
source.AddSingleton(configuration);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register Rag Service ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void AddXRagService(
|
||||||
|
this IServiceCollection source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Persistent RAG (Knowledge over XAiVector Table) ...
|
||||||
|
source.AddScoped<IXAiEmbeddingService, XAiEmbeddingService>();
|
||||||
|
source.AddScoped<IXAiRAGService, XAiRAGService>();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Register Ai Services ...
|
/// Register Ai Services ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -83,12 +97,7 @@ namespace xAiApi.DI
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
source.AddScoped<IXDefaultAiService, XDefaultAiService>();
|
source.AddScoped<IXDefaultAiService, XDefaultAiService>();
|
||||||
source.AddScoped<IXDefaultEmbeddingService, XDefaultEmbeddingService>();
|
|
||||||
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
|
source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
|
||||||
|
|
||||||
//
|
|
||||||
// Persistent RAG (Knowledge over XAiVector Table) ...
|
|
||||||
source.AddScoped<IXAiRAGService, XAiRAGService>();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -74,8 +74,8 @@ namespace xAiApi.Extensions
|
|||||||
!source.IsNullOrDefault() &&
|
!source.IsNullOrDefault() &&
|
||||||
!source.Prompt.IsNullOrEmpty() &&
|
!source.Prompt.IsNullOrEmpty() &&
|
||||||
!source.SessionId.IsDefaultGuid() &&
|
!source.SessionId.IsDefaultGuid() &&
|
||||||
(!source.TopK.HasValue || source.TopK.Value > 0) &&
|
source.TopK.HasValue && source.TopK.Value > 0 &&
|
||||||
(!source.MinScore.HasValue || (source.MinScore.Value >= -1f && source.MinScore.Value <= 1f));
|
source.MinScore.HasValue && source.MinScore.Value >= -1f && source.MinScore.Value <= 1f;
|
||||||
|
|
||||||
//
|
//
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
namespace xAiApi.Interfaces
|
||||||
|
{
|
||||||
|
public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase
|
||||||
|
{ }
|
||||||
|
}
|
||||||
@@ -1,15 +1,14 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
using OllamaSharp;
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace xAiApi.Interfaces
|
namespace xAiApi.Interfaces
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Base Embedding Provider Service ...
|
/// Base Embedding Provider Service ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IXAiEmbeddingServiceBase : IXAiServiceBase
|
public interface IXAiEmbeddingServiceBase // : IXAiServiceBase
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Embedding Specified String ...
|
/// Embedding Specified String ...
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace xAiApi.Interfaces
|
namespace xAiApi.Interfaces
|
||||||
{
|
{
|
||||||
public interface IXAiEmbeddingServiceControllerBase : IXAiServiceControllerBase
|
public interface IXAiEmbeddingServiceControllerBase
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Request For Embedding Specified String ...
|
/// Request For Embedding Specified String ...
|
||||||
|
|||||||
@@ -48,33 +48,6 @@ namespace xAiApi.Interfaces
|
|||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask a Question with RAG (Retrieve from DB then Generate) ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="userInfo"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<XAiDocumentAnswer> AskWithRAGAsync(
|
|
||||||
XAiKnowledgeAskRequest request,
|
|
||||||
XUserClaimsInfoDto userInfo = null,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask a Question with RAG and Stream Response ...
|
|
||||||
/// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="userInfo"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
IAsyncEnumerable<XAiDocumentAnswerChunk> AskWithRAGAsEnumerable(
|
|
||||||
XAiKnowledgeAskRequest request,
|
|
||||||
XUserClaimsInfoDto userInfo = null,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// List Ingested Documents of Specified Scope ...
|
/// List Ingested Documents of Specified Scope ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -258,8 +258,8 @@ namespace xAiApi.Interfaces
|
|||||||
Task<XAiMessageDto> AskAsync(
|
Task<XAiMessageDto> AskAsync(
|
||||||
string prompt,
|
string prompt,
|
||||||
string ownerId,
|
string ownerId,
|
||||||
Guid projectId,
|
Guid? projectId,
|
||||||
Guid conversationId,
|
Guid? conversationId,
|
||||||
string connectionId = null,
|
string connectionId = null,
|
||||||
IFormFileCollection files = null,
|
IFormFileCollection files = null,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
namespace xAiApi.Interfaces
|
|
||||||
{
|
|
||||||
public interface IXDefaultEmbeddingService : IXAiEmbeddingServiceBase
|
|
||||||
{ }
|
|
||||||
}
|
|
||||||
@@ -33,7 +33,8 @@ namespace xAiApi.Models
|
|||||||
string type = null
|
string type = null
|
||||||
) => new()
|
) => new()
|
||||||
{
|
{
|
||||||
Type = type,
|
//
|
||||||
|
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
|
||||||
ScopeId = null,
|
ScopeId = null,
|
||||||
Scope = XAiKnowledgeScope.User,
|
Scope = XAiKnowledgeScope.User,
|
||||||
};
|
};
|
||||||
@@ -47,7 +48,7 @@ namespace xAiApi.Models
|
|||||||
string type = null
|
string type = null
|
||||||
) => new()
|
) => new()
|
||||||
{
|
{
|
||||||
Type = type,
|
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
|
||||||
ScopeId = null,
|
ScopeId = null,
|
||||||
Scope = XAiKnowledgeScope.Global,
|
Scope = XAiKnowledgeScope.Global,
|
||||||
};
|
};
|
||||||
@@ -63,7 +64,7 @@ namespace xAiApi.Models
|
|||||||
string type = null
|
string type = null
|
||||||
) => new()
|
) => new()
|
||||||
{
|
{
|
||||||
Type = type,
|
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
|
||||||
ScopeId = projectId,
|
ScopeId = projectId,
|
||||||
Scope = XAiKnowledgeScope.Project,
|
Scope = XAiKnowledgeScope.Project,
|
||||||
};
|
};
|
||||||
@@ -79,7 +80,7 @@ namespace xAiApi.Models
|
|||||||
string type = null
|
string type = null
|
||||||
) => new()
|
) => new()
|
||||||
{
|
{
|
||||||
Type = type,
|
Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
|
||||||
ScopeId = conversationId,
|
ScopeId = conversationId,
|
||||||
Scope = XAiKnowledgeScope.Conversation,
|
Scope = XAiKnowledgeScope.Conversation,
|
||||||
};
|
};
|
||||||
|
|||||||
+128
-184
@@ -1,6 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using xModels.Dtos;
|
using xModels.Dtos;
|
||||||
|
using xAiApi.Models;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using xAiApi.Constants;
|
using xAiApi.Constants;
|
||||||
using xAiModels.Models;
|
using xAiModels.Models;
|
||||||
@@ -11,14 +12,12 @@ using xCommons.Extensions;
|
|||||||
using xAiModels.Constants;
|
using xAiModels.Constants;
|
||||||
using xAiModels.Interfaces;
|
using xAiModels.Interfaces;
|
||||||
using xAiModels.Extensions;
|
using xAiModels.Extensions;
|
||||||
using xAiService.Constants;
|
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
using xAiModels.Models.Dtos;
|
using xAiModels.Models.Dtos;
|
||||||
using xAiService.Extensions;
|
using xAiService.Extensions;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using xIdentityModels.Models;
|
using xIdentityModels.Models;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -43,7 +42,7 @@ namespace xAiApi.Providers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public XAiModelDescriptor Descriptor { get; }
|
public XAiModelDescriptor Descriptor { get; }
|
||||||
|
|
||||||
private readonly IXFileProvider fileProvider;
|
private readonly IXAiRAGService ragProvider;
|
||||||
private readonly IXAiDataProvider dataProvider;
|
private readonly IXAiDataProvider dataProvider;
|
||||||
private readonly ILogger<XAIServiceBase> logger;
|
private readonly ILogger<XAIServiceBase> logger;
|
||||||
private readonly XAiApiConfiguration configuration;
|
private readonly XAiApiConfiguration configuration;
|
||||||
@@ -51,7 +50,7 @@ namespace xAiApi.Providers
|
|||||||
private readonly IXFileContentExtractor fileContentExtractor;
|
private readonly IXFileContentExtractor fileContentExtractor;
|
||||||
|
|
||||||
protected XAIServiceBase(
|
protected XAIServiceBase(
|
||||||
IXFileProvider fileProvider,
|
IXAiRAGService ragProvider,
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
ILogger<XAIServiceBase> logger,
|
ILogger<XAIServiceBase> logger,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
@@ -62,7 +61,7 @@ namespace xAiApi.Providers
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.fileProvider = fileProvider;
|
this.ragProvider = ragProvider;
|
||||||
this.dataProvider = dataProvider;
|
this.dataProvider = dataProvider;
|
||||||
this.configuration = configuration;
|
this.configuration = configuration;
|
||||||
this.validationProvider = validationProvider;
|
this.validationProvider = validationProvider;
|
||||||
@@ -377,56 +376,6 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Convert Context Chunks to a Numbered Text Block ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="context"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
protected virtual string BuildContextBlock(
|
|
||||||
IEnumerable<XAiVectorSearchResult> context
|
|
||||||
)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var result = "(no context)";
|
|
||||||
|
|
||||||
//
|
|
||||||
var items = context?
|
|
||||||
.Where(c =>
|
|
||||||
!c.IsNullOrDefault() &&
|
|
||||||
!c.Text.IsNullOrEmpty()
|
|
||||||
)
|
|
||||||
.ToList() ?? [];
|
|
||||||
if (!items.HasChild())
|
|
||||||
{
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
var index = 1;
|
|
||||||
var builder = new System.Text.StringBuilder();
|
|
||||||
foreach (var item in items)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var identifier = item.Identifier.IsNullOrEmpty()
|
|
||||||
? item.Id.ToString()
|
|
||||||
: item.Identifier;
|
|
||||||
|
|
||||||
//
|
|
||||||
builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})");
|
|
||||||
builder.AppendLine(item.Text.Trim());
|
|
||||||
builder.AppendLine("----");
|
|
||||||
|
|
||||||
//
|
|
||||||
index++;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
result = builder.ToString();
|
|
||||||
|
|
||||||
//
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -874,8 +823,8 @@ namespace xAiApi.Providers
|
|||||||
public virtual async Task<XAiMessageDto> AskAsync(
|
public virtual async Task<XAiMessageDto> AskAsync(
|
||||||
string prompt,
|
string prompt,
|
||||||
string ownerId,
|
string ownerId,
|
||||||
Guid projectId,
|
Guid? projectId,
|
||||||
Guid conversationId,
|
Guid? conversationId,
|
||||||
string connectionId = null,
|
string connectionId = null,
|
||||||
IFormFileCollection files = null,
|
IFormFileCollection files = null,
|
||||||
XUserClaimsInfoDto userInfo = null,
|
XUserClaimsInfoDto userInfo = null,
|
||||||
@@ -893,7 +842,7 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
// Check Project ...
|
// Check Project ...
|
||||||
XAiProjectDto project = null;
|
XAiProjectDto project = null;
|
||||||
if (projectId.IsDefaultGuid())
|
if (!projectId.HasValue || projectId.Value.IsDefaultGuid())
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
project = await dataProvider.GetDefaultProject(
|
project = await dataProvider.GetDefaultProject(
|
||||||
@@ -909,7 +858,7 @@ namespace xAiApi.Providers
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
project = await dataProvider.GetProject(
|
project = await dataProvider.GetProject(
|
||||||
id: projectId,
|
id: projectId.Value,
|
||||||
fillConversations: false,
|
fillConversations: false,
|
||||||
fillConversationMessages: false,
|
fillConversationMessages: false,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
@@ -923,12 +872,12 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
// Check Conversation ...
|
// Check Conversation ...
|
||||||
XAiConversationDto conversation = null;
|
XAiConversationDto conversation = null;
|
||||||
if (conversationId.IsDefaultGuid())
|
if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid())
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
conversation = await dataProvider.GetDefaultConversation(
|
conversation = await dataProvider.GetDefaultConversation(
|
||||||
ownerId: ownerId,
|
ownerId: ownerId,
|
||||||
projectId: projectId,
|
projectId: projectId.Value,
|
||||||
connectionId: connectionId,
|
connectionId: connectionId,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
@@ -940,8 +889,8 @@ namespace xAiApi.Providers
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
conversation = await dataProvider.GetConversation(
|
conversation = await dataProvider.GetConversation(
|
||||||
id: conversationId,
|
|
||||||
fillMessages: false,
|
fillMessages: false,
|
||||||
|
id: conversationId.Value,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -951,38 +900,58 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Reading Messages ...
|
// Ingest Files based on Conversation ...
|
||||||
var messages = await dataProvider.LoadMessages(
|
XAiKnowledgeIngestResult ingestResult;
|
||||||
conversationId: conversationId,
|
if (files.HasChild())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
ingestResult = await ragProvider
|
||||||
|
.IngestAsync(
|
||||||
|
files: files,
|
||||||
|
userInfo: userInfo,
|
||||||
|
replaceExisting: true,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken,
|
||||||
|
scope: XAiKnowledgeScopeDescriptor.Conversation(
|
||||||
|
type: null,
|
||||||
|
conversationId: conversationId.Value
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Prepare Knowledge Request ...
|
||||||
|
var knowledgeRequest = new XAiKnowledgeAskRequest
|
||||||
|
{
|
||||||
|
Prompt = prompt,
|
||||||
|
IncludeUser = true,
|
||||||
|
IncludeGlobal = true,
|
||||||
|
ProjectId = projectId,
|
||||||
|
ConversationId = conversationId
|
||||||
|
};
|
||||||
|
var context = await ragProvider.RetrieveAsync(
|
||||||
|
userInfo: userInfo,
|
||||||
|
request: knowledgeRequest,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
// Upload Files ...
|
// Reading Messages ...
|
||||||
IEnumerable<xFileService.Models.Dtos.XFileDto> uploadedFiles = null;
|
var messages = await dataProvider.LoadMessages(
|
||||||
if (files.HasChild())
|
conversationId: conversationId.Value,
|
||||||
{
|
cancellationToken: cancellationToken
|
||||||
//
|
);
|
||||||
// Validate User Info ...
|
|
||||||
if (userInfo.IsNullOrDefault())
|
|
||||||
{
|
|
||||||
XException.InvalidArgs.Throw();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
// Upload Files ...
|
|
||||||
uploadedFiles = await fileProvider.Upload(
|
|
||||||
files: files,
|
|
||||||
userInfo: userInfo,
|
|
||||||
connectionId: connectionId,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
//
|
||||||
// Handle Memory ...
|
// Handle Memory ...
|
||||||
IList<ChatMessage> history = await PrepareMemory(
|
IList<ChatMessage> history = await PrepareMemory(
|
||||||
project: project,
|
project: project,
|
||||||
|
context: context,
|
||||||
messages: messages,
|
messages: messages,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
@@ -995,102 +964,23 @@ namespace xAiApi.Providers
|
|||||||
OwnerId = ownerId,
|
OwnerId = ownerId,
|
||||||
Role = XAiChatRole.User,
|
Role = XAiChatRole.User,
|
||||||
CreatedOn = DateTime.UtcNow,
|
CreatedOn = DateTime.UtcNow,
|
||||||
ConversationId = conversationId,
|
ConversationId = conversationId.Value,
|
||||||
ConversationTitle = conversation.Title
|
ConversationTitle = conversation.Title
|
||||||
};
|
};
|
||||||
|
|
||||||
//
|
|
||||||
// Attached Uploaded File Id's as Meta Data ...
|
|
||||||
if (uploadedFiles.HasChild())
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var fileIds = uploadedFiles.Select(f => f.Id).ToList();
|
|
||||||
promptMessage.MetaDatas = new Dictionary<string, object>
|
|
||||||
{
|
|
||||||
{ XAiServiceConstants.XMetaDataFileIdsIdentifier, fileIds }
|
|
||||||
}.ToJSON();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
//
|
||||||
// Save Prompt Message ...
|
// Save Prompt Message ...
|
||||||
promptMessage = await dataProvider.AddMessage(
|
promptMessage = await dataProvider.AddMessage(
|
||||||
item: promptMessage,
|
item: promptMessage,
|
||||||
connectionId: connectionId,
|
connectionId: connectionId,
|
||||||
conversationId: conversationId,
|
conversationId: conversationId.Value,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
|
||||||
// Since Prompt Message Has Id now, we can Attach Uploaded Files to it ...
|
|
||||||
IList<AIContent> fileContents = [];
|
|
||||||
if (uploadedFiles.HasChild())
|
|
||||||
{
|
|
||||||
//
|
|
||||||
foreach (var uf in uploadedFiles)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
try
|
|
||||||
{
|
|
||||||
//
|
|
||||||
// Add Reference File to Prompt Message ...
|
|
||||||
await fileProvider.AddReference(
|
|
||||||
id: uf.Id,
|
|
||||||
userInfo: userInfo,
|
|
||||||
connectionId: connectionId,
|
|
||||||
forProvidedId: promptMessage.Id,
|
|
||||||
cancellationToken: cancellationToken,
|
|
||||||
providedFor: XAiServiceConstants.XAiMessageFilesIdentifier
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
// Handle File Content Extraction and Attach to Prompt Message ...
|
|
||||||
var fileDescriptor = await fileProvider.GetFileDescriptor(
|
|
||||||
id: uf.Id,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
if (fileDescriptor == null || fileDescriptor.Stream == null)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
var extractionResult = await fileContentExtractor.ExtractRichAsync(
|
|
||||||
fileStream: fileDescriptor.Stream,
|
|
||||||
fileName: uf.FileName ?? uf.Name,
|
|
||||||
mimeType: fileDescriptor.MIMEType,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
if (extractionResult.IsValid())
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var contents = extractionResult.ToAIContents();
|
|
||||||
fileContents = [.. fileContents, .. contents];
|
|
||||||
|
|
||||||
//
|
|
||||||
// ذخیره Metadata برای ردیابی
|
|
||||||
logger.LogInformation(
|
|
||||||
"File {FileName} extracted successfully. Text: {HasText}, Images: {ImageCount}, Fallback: {UsedFallback}",
|
|
||||||
uf.FileName,
|
|
||||||
!string.IsNullOrEmpty(extractionResult.Text),
|
|
||||||
extractionResult.Images.Count,
|
|
||||||
extractionResult.UsedImageFallback
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
fileDescriptor.Stream.Dispose();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, "Failed to extract content from file: {FileName}", uf.FileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
//
|
||||||
// Converts to ChatMessage ...
|
// Converts to ChatMessage ...
|
||||||
var promptChatMessage = promptMessage
|
var promptChatMessage = promptMessage
|
||||||
.ToChatMessages(fileContents);
|
.ToChatMessages(additionalContents: []);
|
||||||
|
|
||||||
//
|
//
|
||||||
// Ask Questions From LLM ...
|
// Ask Questions From LLM ...
|
||||||
@@ -1108,13 +998,13 @@ namespace xAiApi.Providers
|
|||||||
OwnerId = ownerId,
|
OwnerId = ownerId,
|
||||||
CreatedOn = DateTime.UtcNow,
|
CreatedOn = DateTime.UtcNow,
|
||||||
Role = XAiChatRole.Assistant,
|
Role = XAiChatRole.Assistant,
|
||||||
ConversationId = conversationId,
|
ConversationId = conversationId.Value,
|
||||||
ConversationTitle = conversation.Title
|
ConversationTitle = conversation.Title
|
||||||
};
|
};
|
||||||
result = await dataProvider.AddMessage(
|
result = await dataProvider.AddMessage(
|
||||||
item: result,
|
item: result,
|
||||||
connectionId: connectionId,
|
connectionId: connectionId,
|
||||||
conversationId: conversationId,
|
conversationId: conversationId.Value,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1330,11 +1220,13 @@ namespace xAiApi.Providers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="project"></param>
|
/// <param name="project"></param>
|
||||||
/// <param name="messages"></param>
|
/// <param name="messages"></param>
|
||||||
|
/// <param name="context"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
private async Task<IList<ChatMessage>> PrepareMemory(
|
private async Task<IList<ChatMessage>> PrepareMemory(
|
||||||
XAiProjectDto project,
|
XAiProjectDto project,
|
||||||
IEnumerable<XAiMessageDto> messages,
|
IEnumerable<XAiMessageDto> messages,
|
||||||
|
IEnumerable<XAiVectorSearchResult> context = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
@@ -1343,35 +1235,37 @@ namespace xAiApi.Providers
|
|||||||
|
|
||||||
//
|
//
|
||||||
// Retrieve Introduction Prompt ...
|
// Retrieve Introduction Prompt ...
|
||||||
|
var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
|
||||||
var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName);
|
var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName);
|
||||||
if (introductionPrompt.IsNullOrEmpty())
|
if (ragPrompt.IsNullOrEmpty() ||
|
||||||
|
introductionPrompt.IsNullOrEmpty()
|
||||||
|
)
|
||||||
{
|
{
|
||||||
XException.InvalidData.Throw();
|
XException.InvalidData.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
var introductionMessage = new ChatMessage(
|
var contextBlock = BuildContextBlock(context);
|
||||||
role: ChatRole.System,
|
var systemText =
|
||||||
content: introductionPrompt
|
$"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" +
|
||||||
);
|
$"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
|
||||||
|
$"Context:{Environment.NewLine}{contextBlock}";
|
||||||
//
|
|
||||||
result.Add(introductionMessage);
|
|
||||||
|
|
||||||
//
|
//
|
||||||
|
// Apply Project Prompt as System Text ...
|
||||||
if (!project.IsNullOrDefault() &&
|
if (!project.IsNullOrDefault() &&
|
||||||
!project.Prompt.IsNullOrEmpty())
|
!project.Prompt.IsNullOrEmpty())
|
||||||
{
|
{
|
||||||
//
|
systemText += $"Project:{Environment.NewLine}{project.Prompt}";
|
||||||
// TODO: Handle Project Files Here ...
|
|
||||||
var projectMessage = new ChatMessage(
|
|
||||||
role: ChatRole.System,
|
|
||||||
contents: [new TextContent(project.Prompt)]
|
|
||||||
);
|
|
||||||
result.Add(projectMessage);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
|
// Add System Message ...
|
||||||
|
result
|
||||||
|
.Add(new ChatMessage(ChatRole.System, systemText));
|
||||||
|
|
||||||
|
//
|
||||||
|
// Attach Message ...
|
||||||
if (messages.HasChild())
|
if (messages.HasChild())
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -1386,6 +1280,56 @@ namespace xAiApi.Providers
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Convert Context Chunks to a Numbered Text Block ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private string BuildContextBlock(
|
||||||
|
IEnumerable<XAiVectorSearchResult> context
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var result = "(no context)";
|
||||||
|
|
||||||
|
//
|
||||||
|
var items = context?
|
||||||
|
.Where(c =>
|
||||||
|
!c.IsNullOrDefault() &&
|
||||||
|
!c.Text.IsNullOrEmpty()
|
||||||
|
)
|
||||||
|
.ToList() ?? [];
|
||||||
|
if (!items.HasChild())
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var index = 1;
|
||||||
|
var builder = new System.Text.StringBuilder();
|
||||||
|
foreach (var item in items)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var identifier = item.Identifier.IsNullOrEmpty()
|
||||||
|
? item.Id.ToString()
|
||||||
|
: item.Identifier;
|
||||||
|
|
||||||
|
//
|
||||||
|
builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})");
|
||||||
|
builder.AppendLine(item.Text.Trim());
|
||||||
|
builder.AppendLine("----");
|
||||||
|
|
||||||
|
//
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
result = builder.ToString();
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ask Quetion from LLM ...
|
/// Ask Quetion from LLM ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -1,25 +1,22 @@
|
|||||||
using xAiApi.Constants;
|
using xAiApi.Constants;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
|
using xCommons.Providers;
|
||||||
using xAiModels.Interfaces;
|
using xAiModels.Interfaces;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
using xCommons.Providers;
|
|
||||||
|
|
||||||
namespace xAiApi.Providers
|
namespace xAiApi.Providers
|
||||||
{
|
{
|
||||||
public class XDefaultEmbeddingService : XAiEmbeddingServiceBase, IXDefaultEmbeddingService
|
public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService
|
||||||
{
|
{
|
||||||
public XDefaultEmbeddingService(
|
public XAiEmbeddingService(
|
||||||
IXFileProvider fileProvider,
|
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
|
ILogger<XAiEmbeddingService> logger,
|
||||||
XValidationProvider validationProvider,
|
XValidationProvider validationProvider,
|
||||||
ILogger<XDefaultEmbeddingService> logger,
|
|
||||||
IXFileContentExtractor fileContentExtractor
|
IXFileContentExtractor fileContentExtractor
|
||||||
) : base(
|
) : base(
|
||||||
fileProvider,
|
|
||||||
dataProvider,
|
dataProvider,
|
||||||
configuration,
|
configuration,
|
||||||
validationProvider,
|
validationProvider,
|
||||||
@@ -17,7 +17,6 @@ using xAiModels.Interfaces;
|
|||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -29,28 +28,23 @@ namespace xAiApi.Providers
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Base Embedding Provider Service ...
|
/// Base Embedding Provider Service ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public abstract class XAiEmbeddingServiceBase : XAIServiceBase, IXAiEmbeddingServiceBase
|
public abstract class XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase
|
||||||
{
|
{
|
||||||
private readonly IXFileProvider fileProvider;
|
private readonly string embeddingModelName;
|
||||||
private readonly XAiModelDescriptor descriptor;
|
private readonly XAiModelDescriptor descriptor;
|
||||||
|
private readonly IXAiDataProvider dataProvider;
|
||||||
|
private readonly XAiApiConfiguration configuration;
|
||||||
|
private readonly XValidationProvider validationProvider;
|
||||||
private readonly ILogger<XAiEmbeddingServiceBase> logger;
|
private readonly ILogger<XAiEmbeddingServiceBase> logger;
|
||||||
|
private readonly IXFileContentExtractor fileContentExtractor;
|
||||||
|
|
||||||
protected XAiEmbeddingServiceBase(
|
protected XAiEmbeddingServiceBase(
|
||||||
IXFileProvider fileProvider,
|
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
XValidationProvider validationProvider,
|
XValidationProvider validationProvider,
|
||||||
ILogger<XAiEmbeddingServiceBase> logger,
|
ILogger<XAiEmbeddingServiceBase> logger,
|
||||||
IXFileContentExtractor fileContentExtractor,
|
IXFileContentExtractor fileContentExtractor,
|
||||||
string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
|
string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
|
||||||
) : base(
|
|
||||||
fileProvider,
|
|
||||||
dataProvider,
|
|
||||||
logger,
|
|
||||||
configuration,
|
|
||||||
validationProvider,
|
|
||||||
fileContentExtractor,
|
|
||||||
null
|
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -61,10 +55,14 @@ namespace xAiApi.Providers
|
|||||||
XException.InvalidConfiguration.Throw();
|
XException.InvalidConfiguration.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
this.fileProvider = fileProvider;
|
this.dataProvider = dataProvider;
|
||||||
|
this.configuration = configuration;
|
||||||
|
this.validationProvider = validationProvider;
|
||||||
|
|
||||||
//
|
//
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
|
this.fileContentExtractor = fileContentExtractor;
|
||||||
|
this.embeddingModelName = embeddingModelName;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
+138
-242
@@ -2,10 +2,10 @@ using System;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using xAiApi.Models;
|
using xAiApi.Models;
|
||||||
using System.Threading;
|
|
||||||
using xIdentityHelper;
|
using xIdentityHelper;
|
||||||
using xAiApi.Constants;
|
using System.Threading;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
|
using xAiModels.Constants;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
using xAiModels.Interfaces;
|
using xAiModels.Interfaces;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
@@ -18,8 +18,6 @@ using Microsoft.AspNetCore.Http;
|
|||||||
using System.Collections.Generic;
|
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 xAiModels.Constants;
|
|
||||||
|
|
||||||
namespace xAiApi.Providers
|
namespace xAiApi.Providers
|
||||||
{
|
{
|
||||||
@@ -36,11 +34,10 @@ namespace xAiApi.Providers
|
|||||||
{
|
{
|
||||||
private readonly IXTextChunker textChunker;
|
private readonly IXTextChunker textChunker;
|
||||||
private readonly IXFileProvider fileProvider;
|
private readonly IXFileProvider fileProvider;
|
||||||
private readonly IXDefaultAiService aiService;
|
|
||||||
private readonly IXAiDataProvider dataProvider;
|
private readonly IXAiDataProvider dataProvider;
|
||||||
private readonly ILogger<XAiRAGService> logger;
|
private readonly ILogger<XAiRAGService> logger;
|
||||||
private readonly XAiApiConfiguration configuration;
|
private readonly XAiApiConfiguration configuration;
|
||||||
private readonly IXDefaultEmbeddingService embeddingService;
|
private readonly IXAiEmbeddingService embeddingService;
|
||||||
private readonly IXFileContentExtractor fileContentExtractor;
|
private readonly IXFileContentExtractor fileContentExtractor;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -51,17 +48,15 @@ namespace xAiApi.Providers
|
|||||||
public XAiRAGService(
|
public XAiRAGService(
|
||||||
IXTextChunker textChunker,
|
IXTextChunker textChunker,
|
||||||
IXFileProvider fileProvider,
|
IXFileProvider fileProvider,
|
||||||
IXDefaultAiService aiService,
|
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
ILogger<XAiRAGService> logger,
|
ILogger<XAiRAGService> logger,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
IXDefaultEmbeddingService embeddingService,
|
IXAiEmbeddingService embeddingService,
|
||||||
IXFileContentExtractor fileContentExtractor
|
IXFileContentExtractor fileContentExtractor
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.aiService = aiService;
|
|
||||||
this.textChunker = textChunker;
|
this.textChunker = textChunker;
|
||||||
this.fileProvider = fileProvider;
|
this.fileProvider = fileProvider;
|
||||||
this.dataProvider = dataProvider;
|
this.dataProvider = dataProvider;
|
||||||
@@ -201,13 +196,28 @@ namespace xAiApi.Providers
|
|||||||
|
|
||||||
//
|
//
|
||||||
// Handle File Save ...
|
// Handle File Save ...
|
||||||
await fileProvider.Upload(
|
var uploadedFile = await fileProvider.Upload(
|
||||||
file: file,
|
file: file,
|
||||||
userInfo: userInfo,
|
userInfo: userInfo,
|
||||||
connectionId: connectionId,
|
connectionId: connectionId,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Add Reference File to Prompt Message ...
|
||||||
|
if (scope.ScopeId.HasValue)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
await fileProvider.AddReference(
|
||||||
|
userInfo: userInfo,
|
||||||
|
id: uploadedFile.Id,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken,
|
||||||
|
providedFor: scope.Scope.GetStringValue(),
|
||||||
|
forProvidedId: scope.ScopeId.Value.ToString()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Embed in Batches ...
|
// Embed in Batches ...
|
||||||
var vectors = await EmbedChunks(
|
var vectors = await EmbedChunks(
|
||||||
@@ -360,123 +370,6 @@ namespace xAiApi.Providers
|
|||||||
//
|
//
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask a Question with RAG (Retrieve from DB then Generate) ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="userInfo"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public async Task<XAiDocumentAnswer> AskWithRAGAsync(
|
|
||||||
XAiKnowledgeAskRequest request,
|
|
||||||
XUserClaimsInfoDto userInfo = null,
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
// Retrieve (Validates Request) ...
|
|
||||||
var context = await RetrieveAsync(
|
|
||||||
request: request,
|
|
||||||
userInfo: userInfo,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
var result = new XAiDocumentAnswer
|
|
||||||
{
|
|
||||||
Sources = ToSources(context)
|
|
||||||
};
|
|
||||||
if (!context.HasChild())
|
|
||||||
{
|
|
||||||
//
|
|
||||||
result.NoContextFound = true;
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
// Generate ...
|
|
||||||
result.Answer = await aiService.AskWithContextAsync(
|
|
||||||
context: context,
|
|
||||||
prompt: request.Prompt,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ask a Question with RAG and Stream Response ...
|
|
||||||
/// First Item Carries Sources, Next Items Carry Text Deltas, Last Item has IsFinal = true ...
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="request"></param>
|
|
||||||
/// <param name="userInfo"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public async IAsyncEnumerable<XAiDocumentAnswerChunk> AskWithRAGAsEnumerable(
|
|
||||||
XAiKnowledgeAskRequest request,
|
|
||||||
XUserClaimsInfoDto userInfo = null,
|
|
||||||
[EnumeratorCancellation]
|
|
||||||
CancellationToken cancellationToken = default
|
|
||||||
)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
// Retrieve (Validates Request) ...
|
|
||||||
var context = await RetrieveAsync(
|
|
||||||
request: request,
|
|
||||||
userInfo: userInfo,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
// First Item: Sources ...
|
|
||||||
var hasContext = context.HasChild();
|
|
||||||
yield return new XAiDocumentAnswerChunk
|
|
||||||
{
|
|
||||||
Text = string.Empty,
|
|
||||||
IsFinal = !hasContext,
|
|
||||||
NoContextFound = !hasContext,
|
|
||||||
Sources = ToSources(context)
|
|
||||||
};
|
|
||||||
if (!hasContext)
|
|
||||||
{
|
|
||||||
yield break;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
// Stream Deltas ...
|
|
||||||
var enumerable = aiService.AskWithContextAsEnumerable(
|
|
||||||
context: context,
|
|
||||||
prompt: request.Prompt,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
await foreach (var delta in enumerable)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
if (cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
yield break;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
if (delta.IsNullOrEmpty())
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
yield return new XAiDocumentAnswerChunk { Text = delta };
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
// Final Item ...
|
|
||||||
yield return new XAiDocumentAnswerChunk
|
|
||||||
{
|
|
||||||
Text = string.Empty,
|
|
||||||
IsFinal = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -701,12 +594,125 @@ namespace xAiApi.Providers
|
|||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
//
|
||||||
|
#region Private ...
|
||||||
|
/// <summary>
|
||||||
|
/// Extract Plain Text of a File (Text or Audio Transcript) ...
|
||||||
|
/// </summary>
|
||||||
|
private async Task<string> ExtractText(
|
||||||
|
IFormFile file,
|
||||||
|
string mimeType,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//
|
||||||
|
using var stream = file.OpenReadStream();
|
||||||
|
var extraction = await fileContentExtractor.ExtractRichAsync(
|
||||||
|
fileStream: stream,
|
||||||
|
mimeType: mimeType,
|
||||||
|
fileName: file.FileName,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
var result = extraction?.Text;
|
||||||
|
if (string.IsNullOrWhiteSpace(result))
|
||||||
|
{
|
||||||
|
result = extraction?.AudioTranscript;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ...
|
||||||
|
/// </summary>
|
||||||
|
private async Task<IList<XAiVectorDto>> EmbedChunks(
|
||||||
|
XAiKnowledgeScopeDescriptor scope,
|
||||||
|
IList<XTextChunk> chunks,
|
||||||
|
string type,
|
||||||
|
string ownerId,
|
||||||
|
string fileName,
|
||||||
|
string mimeType,
|
||||||
|
string ingestedAtUtc,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var rag = configuration.RAGDescriptor;
|
||||||
|
var batchSize = Math.Max(1, rag.EmbeddingBatchSize);
|
||||||
|
var result = new List<XAiVectorDto>(chunks.Count);
|
||||||
|
|
||||||
|
//
|
||||||
|
for (var offset = 0; offset < chunks.Count; offset += batchSize)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
//
|
||||||
|
var batch = chunks.Skip(offset).Take(batchSize).ToList();
|
||||||
|
var embeddings = await embeddingService.Embeddings(
|
||||||
|
batch: batch.Select(c => c.Text).ToArray(),
|
||||||
|
cancellationToken: cancellationToken
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count)
|
||||||
|
{
|
||||||
|
XException.ActionFailed.Throw();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
for (var i = 0; i < batch.Count; i++)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var chunk = batch[i];
|
||||||
|
result.Add(new XAiVectorDto
|
||||||
|
{
|
||||||
|
//
|
||||||
|
Type = type,
|
||||||
|
Text = chunk.Text,
|
||||||
|
Embedding = embeddings[i],
|
||||||
|
Identifier = chunk.Identifier,
|
||||||
|
Metadata = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
[rag.MetadataFileName] = fileName,
|
||||||
|
[rag.MetadataMimeType] = mimeType,
|
||||||
|
[rag.MetadataChunkIndex] = chunk.Index.ToString(),
|
||||||
|
[XAiModelsConstants.XAiKnowledgeMetadataType] = type,
|
||||||
|
[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
|
||||||
|
[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(),
|
||||||
|
[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty,
|
||||||
|
[XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
#region Scope ...
|
#region Scope ...
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ...
|
/// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope)
|
private XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
var result = scope ?? XAiKnowledgeScopeDescriptor.User();
|
var result = scope ?? XAiKnowledgeScopeDescriptor.User();
|
||||||
@@ -916,7 +922,10 @@ namespace xAiApi.Providers
|
|||||||
/// Document Chunk Prefix: "{scopePrefix}{fileName}#" ...
|
/// Document Chunk Prefix: "{scopePrefix}{fileName}#" ...
|
||||||
/// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
|
/// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private string GetDocumentChunkPrefix(string scopePrefix, string fileName)
|
private string GetDocumentChunkPrefix(
|
||||||
|
string scopePrefix,
|
||||||
|
string fileName
|
||||||
|
)
|
||||||
{
|
{
|
||||||
return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}";
|
return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}";
|
||||||
}
|
}
|
||||||
@@ -1006,119 +1015,6 @@ namespace xAiApi.Providers
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
//
|
|
||||||
#region Private ...
|
|
||||||
/// <summary>
|
|
||||||
/// Extract Plain Text of a File (Text or Audio Transcript) ...
|
|
||||||
/// </summary>
|
|
||||||
private async Task<string> ExtractText(
|
|
||||||
IFormFile file,
|
|
||||||
string mimeType,
|
|
||||||
CancellationToken cancellationToken
|
|
||||||
)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
try
|
|
||||||
{
|
|
||||||
//
|
|
||||||
using var stream = file.OpenReadStream();
|
|
||||||
var extraction = await fileContentExtractor.ExtractRichAsync(
|
|
||||||
fileStream: stream,
|
|
||||||
mimeType: mimeType,
|
|
||||||
fileName: file.FileName,
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
var result = extraction?.Text;
|
|
||||||
if (string.IsNullOrWhiteSpace(result))
|
|
||||||
{
|
|
||||||
result = extraction?.AudioTranscript;
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
catch (OperationCanceledException)
|
|
||||||
{
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ...
|
|
||||||
/// </summary>
|
|
||||||
private async Task<IList<XAiVectorDto>> EmbedChunks(
|
|
||||||
XAiKnowledgeScopeDescriptor scope,
|
|
||||||
IList<XTextChunk> chunks,
|
|
||||||
string type,
|
|
||||||
string ownerId,
|
|
||||||
string fileName,
|
|
||||||
string mimeType,
|
|
||||||
string ingestedAtUtc,
|
|
||||||
CancellationToken cancellationToken
|
|
||||||
)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var rag = configuration.RAGDescriptor;
|
|
||||||
var batchSize = Math.Max(1, rag.EmbeddingBatchSize);
|
|
||||||
var result = new List<XAiVectorDto>(chunks.Count);
|
|
||||||
|
|
||||||
//
|
|
||||||
for (var offset = 0; offset < chunks.Count; offset += batchSize)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
|
||||||
|
|
||||||
//
|
|
||||||
var batch = chunks.Skip(offset).Take(batchSize).ToList();
|
|
||||||
var embeddings = await embeddingService.Embeddings(
|
|
||||||
batch: batch.Select(c => c.Text).ToArray(),
|
|
||||||
cancellationToken: cancellationToken
|
|
||||||
);
|
|
||||||
|
|
||||||
//
|
|
||||||
if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count)
|
|
||||||
{
|
|
||||||
XException.ActionFailed.Throw();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
for (var i = 0; i < batch.Count; i++)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
var chunk = batch[i];
|
|
||||||
result.Add(new XAiVectorDto
|
|
||||||
{
|
|
||||||
//
|
|
||||||
Type = type,
|
|
||||||
Text = chunk.Text,
|
|
||||||
Embedding = embeddings[i],
|
|
||||||
Identifier = chunk.Identifier,
|
|
||||||
Metadata = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
[rag.MetadataFileName] = fileName,
|
|
||||||
[rag.MetadataMimeType] = mimeType,
|
|
||||||
[rag.MetadataChunkIndex] = chunk.Index.ToString(),
|
|
||||||
[XAiModelsConstants.XAiKnowledgeMetadataType] = type,
|
|
||||||
[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
|
|
||||||
[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(),
|
|
||||||
[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty,
|
|
||||||
[XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ using xAiApi.Interfaces;
|
|||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
using xAiModels.Interfaces;
|
using xAiModels.Interfaces;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
@@ -12,14 +11,14 @@ namespace xAiApi.Providers
|
|||||||
public class XDefaultAiService : XAIServiceBase, IXDefaultAiService
|
public class XDefaultAiService : XAIServiceBase, IXDefaultAiService
|
||||||
{
|
{
|
||||||
public XDefaultAiService(
|
public XDefaultAiService(
|
||||||
IXFileProvider fileProvider,
|
IXAiRAGService ragProvider,
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
ILogger<XDefaultAiService> logger,
|
ILogger<XDefaultAiService> logger,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
XValidationProvider validationProvider,
|
XValidationProvider validationProvider,
|
||||||
IXFileContentExtractor fileContentExtractor
|
IXFileContentExtractor fileContentExtractor
|
||||||
) : base(
|
) : base(
|
||||||
fileProvider,
|
ragProvider,
|
||||||
dataProvider,
|
dataProvider,
|
||||||
logger,
|
logger,
|
||||||
configuration,
|
configuration,
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ using xCommons.Providers;
|
|||||||
using xAiModels.Interfaces;
|
using xAiModels.Interfaces;
|
||||||
using xAiApi.Configurations;
|
using xAiApi.Configurations;
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
using xFileService.Interfaces;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using xAiApi.Interfaces.Extractors;
|
using xAiApi.Interfaces.Extractors;
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ namespace xAiApi.Providers
|
|||||||
public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService
|
public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService
|
||||||
{
|
{
|
||||||
public XDefaultThinkingAiService(
|
public XDefaultThinkingAiService(
|
||||||
IXFileProvider fileProvider,
|
IXAiRAGService ragProvider,
|
||||||
IXAiDataProvider dataProvider,
|
IXAiDataProvider dataProvider,
|
||||||
ILogger<XAIServiceBase> logger,
|
ILogger<XAIServiceBase> logger,
|
||||||
XAiApiConfiguration configuration,
|
XAiApiConfiguration configuration,
|
||||||
@@ -22,7 +21,7 @@ namespace xAiApi.Providers
|
|||||||
ReasoningEffort effort = ReasoningEffort.Medium,
|
ReasoningEffort effort = ReasoningEffort.Medium,
|
||||||
ReasoningOutput output = ReasoningOutput.Full
|
ReasoningOutput output = ReasoningOutput.Full
|
||||||
) : base(
|
) : base(
|
||||||
fileProvider,
|
ragProvider,
|
||||||
dataProvider,
|
dataProvider,
|
||||||
logger,
|
logger,
|
||||||
configuration,
|
configuration,
|
||||||
|
|||||||
@@ -196,6 +196,10 @@ namespace xAiApi
|
|||||||
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
|
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
|
||||||
services.AddXAiChatWithDocuments();
|
services.AddXAiChatWithDocuments();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Persistent RAG (Knowledge over XAiVector Table) ...
|
||||||
|
services.AddXRagService();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Register Default AI Services ...
|
// Register Default AI Services ...
|
||||||
services.AddXAiServices();
|
services.AddXAiServices();
|
||||||
|
|||||||
Reference in New Issue
Block a user