This commit is contained in:
2026-10-31 17:19:17 +03:30
parent c1173042d4
commit ce5db9e349
6 changed files with 593 additions and 409 deletions
-30
View File
@@ -1,30 +0,0 @@
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
[Authorize]
[Route("[controller]")]
public class DefaultEmbeddingController : XAiEmbeddingServiceControllerBase<IXAiEmbeddingService>
{
public DefaultEmbeddingController(
ILogger<DefaultEmbeddingController> logger,
IXAiEmbeddingService embeddingService,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger: logger,
appConfiguration: appConfiguration,
identityProvider: identityProvider,
embeddingService: embeddingService,
validationProvider: validationProvider
)
{ }
}
}
@@ -1,26 +0,0 @@
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Configurations;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
namespace xAiApi.Controllers
{
public class DefaultThinkingAiController : XAiServiceControllerBase<IXDefaultThinkingAiService>
{
public DefaultThinkingAiController(
ILogger<DefaultThinkingAiController> logger,
IXDefaultThinkingAiService aiService,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger,
aiService,
appConfiguration,
identityProvider,
validationProvider
)
{ }
}
}
@@ -1,113 +0,0 @@
using System;
using System.Threading;
using xAiApi.Interfaces;
using xCommons.Providers;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using xIdentityService.Controllers;
using Microsoft.AspNetCore.Authorization;
namespace xAiApi.Controllers
{
[Authorize]
[Route("[controller]")]
public abstract class XAiEmbeddingServiceControllerBase<TEmbeddingService> : XBaseIdentityApiV1Controller, IXAiEmbeddingServiceControllerBase
where TEmbeddingService : IXAiEmbeddingServiceBase
{
private readonly TEmbeddingService embeddingService;
protected XAiEmbeddingServiceControllerBase(
ILogger logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider,
TEmbeddingService embeddingService
) : base(
logger,
appConfiguration,
identityProvider,
validationProvider
)
{
this.embeddingService = embeddingService;
}
/// <summary>
/// Request For Embedding Specified String ...
/// </summary>
/// <param name="content"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("Embedding")]
public async Task<ActionResult<float[]>> Embedding(
[FromQuery] string content,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
ValidationProvider.NotEmpty(content);
//
var result = await embeddingService.Embedding(
content: content,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Request For Embedding Specified Batch ...
/// </summary>
/// <param name="batch"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("Embeddings")]
public async Task<ActionResult<IReadOnlyList<float[]>>> Embeddings(
[FromQuery] string[] batch,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
ValidationProvider.NotZeroChilds(batch);
//
var result = await embeddingService.Embeddings(
batch: batch,
cancellationToken: cancellationToken
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
}
}
+284 -191
View File
@@ -162,16 +162,282 @@ namespace xAiApi.Controllers
}
/// <summary>
/// Write Validation Error for Streaming Endpoints (before Stream Starts) ...
/// Ask Question and Get Response ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[NonAction]
protected async Task WriteStreamValidationError()
[HttpPost("Ask")]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<string>> Ask(
[FromBody] XAiResponseRequest request,
CancellationToken cancellationToken = default
)
{
//
Response.StatusCode = StatusCodes.Status400BadRequest;
Response.ContentType = "application/json; charset=utf-8";
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
try
{
//
// Validate ...
if (!request.IsValid())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
var result = await aiService.AskAsync(
files: null,
topK: request.TopK,
userInfo: userInfo,
prompt: request.Prompt,
minScore: request.MinScore,
connectionId: connectionId,
projectId: request.ProjectId,
cancellationToken: cancellationToken,
conversationId: request.ConversationId
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Ask Question and Get Response Stream ...
/// </summary>
/// <param name="request"></param>
/// <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
{
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
// Configure SSE Response ...
Response.PrepareSseResponse();
//
var enumerable = aiService.AskAsEnumerable(
files: null,
topK: request.TopK,
userInfo: userInfo,
prompt: request.Prompt,
minScore: request.MinScore,
connectionId: connectionId,
projectId: request.ProjectId,
cancellationToken: cancellationToken,
conversationId: request.ConversationId
);
//
// Format: data: {json}\n\n
await foreach (var resp in enumerable)
{
//
// Skip Empty Responses ...
if (resp.IsNullOrDefault())
{
continue;
}
//
await Response.WriteSseEventAsync(
data: resp,
cancellationToken: cancellationToken
);
}
//
await Response.WriteSseDoneAsync(cancellationToken);
}
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
{
// 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);
}
}
/// <summary>
/// Ask Question with Files and Get Response ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AskWithFiles")]
[Consumes("multipart/form-data")]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<string>> AskWithFiles(
[FromForm] XAiResponseRequest request,
[FromForm] IFormFileCollection files,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (!request.IsValid())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
var result = await aiService.AskAsync(
files: null,
topK: request.TopK,
userInfo: userInfo,
prompt: request.Prompt,
minScore: request.MinScore,
connectionId: connectionId,
projectId: request.ProjectId,
cancellationToken: cancellationToken,
conversationId: request.ConversationId
);
//
return Ok(result);
}
catch (Exception ex)
{
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Ask Question with Files and Get Response Stream ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AskWithFilesStream")]
[Consumes("multipart/form-data")]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task AskWithFilesStream(
[FromForm] XAiResponseRequest request,
[FromForm] IFormFileCollection files,
CancellationToken cancellationToken = default
)
{
//
// Validate (before Stream Starts -> Proper Http Error) ...
if (!request.IsValid())
{
await WriteStreamValidationError();
return;
}
//
try
{
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
// Configure SSE Response ...
Response.PrepareSseResponse();
//
var enumerable = aiService.AskAsEnumerable(
files: files,
topK: request.TopK,
userInfo: userInfo,
prompt: request.Prompt,
minScore: request.MinScore,
connectionId: connectionId,
projectId: request.ProjectId,
cancellationToken: cancellationToken,
conversationId: request.ConversationId
);
//
// Format: data: {json}\n\n
await foreach (var resp in enumerable)
{
//
// Skip Empty Responses ...
if (resp.IsNullOrDefault())
{
continue;
}
//
await Response.WriteSseEventAsync(
data: resp,
cancellationToken: cancellationToken
);
}
//
await Response.WriteSseDoneAsync(cancellationToken);
}
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
{
// 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);
}
}
#endregion
@@ -541,7 +807,7 @@ namespace xAiApi.Controllers
}
}
#endregion
//
#region Content Extraction ...
/// <summary>
@@ -556,9 +822,10 @@ namespace xAiApi.Controllers
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<string>> ExtractContent(
[FromForm] IFormFileCollection files,
[FromForm] string extractors = "*",
CancellationToken cancellationToken = default
) {
[FromForm] string extractors = null,
CancellationToken cancellationToken = default
)
{
//
try
{
@@ -599,192 +866,18 @@ namespace xAiApi.Controllers
#endregion
//
#region Data Actions ...
#region Non Actions ...
/// <summary>
/// Ask Question and Get Response ...
/// Write Validation Error for Streaming Endpoints (before Stream Starts) ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Ask")]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<string>> Ask(
[FromBody] XAiResponseRequest request,
CancellationToken cancellationToken = default
)
[NonAction]
protected async Task WriteStreamValidationError()
{
//
try
{
//
// Validate ...
if (!request.IsValid())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
// TODO: Reading Fiels Form Collection and Attach it ...
var result = await aiService.AskAsync(
files: null,
prompt: request.Prompt,
ownerId: userInfo.UserId,
connectionId: connectionId,
projectId: request.ProjectId,
cancellationToken: cancellationToken,
conversationId: request.ConversationId
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Ask Question and Get Response Stream ...
/// </summary>
/// <param name="request"></param>
/// <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
{
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
// Configure SSE Response ...
Response.PrepareSseResponse();
//
// TODO: Reading Fiels Form Collection and Attach it ...
var enumerable = aiService.AskAsEnumerable(
files: null,
prompt: request.Prompt,
ownerId: userInfo.UserId,
connectionId: connectionId,
projectId: request.ProjectId.Value,
cancellationToken: cancellationToken,
conversationId: request.ConversationId.Value
);
//
// Format: data: {json}\n\n
await foreach (var resp in enumerable)
{
//
// Skip Empty Responses ...
if (resp.IsNullOrDefault())
{
continue;
}
//
await Response.WriteSseEventAsync(
data: resp,
cancellationToken: cancellationToken
);
}
//
await Response.WriteSseDoneAsync(cancellationToken);
}
catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
{
// 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);
}
}
/// <summary>
/// Ask Question with Files and Get Response ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AskWithFiles")]
[Consumes("multipart/form-data")]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<string>> AskWithFiles(
[FromForm] XAiResponseRequest request,
[FromForm] IFormFileCollection files,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (!request.IsValid())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
var result = await aiService.AskAsync(
files: files,
userInfo: userInfo,
prompt: request.Prompt,
ownerId: userInfo.UserId,
connectionId: connectionId,
projectId: request.ProjectId,
cancellationToken: cancellationToken,
conversationId: request.ConversationId
);
//
return Ok(result);
}
catch (Exception ex)
{
var result = GetExceptionActionResult(ex);
return result;
}
Response.StatusCode = StatusCodes.Status400BadRequest;
Response.ContentType = "application/json; charset=utf-8";
await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
}
#endregion
}
+40 -8
View File
@@ -50,11 +50,38 @@ namespace xAiApi.Interfaces
CancellationToken cancellationToken = default
);
/// <summary>
/// Ask a Question using Provided Context Chunks (RAG) without Persisting ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> AskWithContextAsync(
string prompt,
IEnumerable<XAiVectorSearchResult> context,
CancellationToken cancellationToken = default
);
/// <summary>
/// Ask a Question using Provided Context Chunks (RAG) and Stream Response ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IAsyncEnumerable<string> AskWithContextAsEnumerable(
string prompt,
IEnumerable<XAiVectorSearchResult> context,
CancellationToken cancellationToken = default
);
/// <summary>
/// Ask a Question as Prompt and Retrieve Response ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="ownerId"></param>
/// <param name="topK"></param>
/// <param name="minScore"></param>
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="connectionId"></param>
@@ -64,9 +91,10 @@ namespace xAiApi.Interfaces
/// <returns></returns>
Task<XAiMessageDto> AskAsync(
string prompt,
string ownerId,
Guid? projectId,
Guid? conversationId,
int? topK = null,
float? minScore = null,
Guid? projectId = null,
Guid? conversationId = null,
string connectionId = null,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
@@ -77,20 +105,24 @@ namespace xAiApi.Interfaces
/// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="ownerId"></param>
/// <param name="topK"></param>
/// <param name="minScore"></param>
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="connectionId"></param>
/// <param name="files"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
string prompt,
string ownerId,
Guid projectId,
Guid conversationId,
int? topK = null,
float? minScore = null,
Guid? projectId = null,
Guid? conversationId = null,
string connectionId = null,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
#endregion
+269 -41
View File
@@ -167,12 +167,100 @@ namespace xAiApi.Providers
yield return res.Text;
}
}
/// <summary>
/// Ask a Question using Provided Context Chunks (RAG) without Persisting ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> AskWithContextAsync(
string prompt,
IEnumerable<XAiVectorSearchResult> context,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
using var client = Descriptor.GetClient();
var history = GetHistory(prompt, context);
var response = await client.GetResponseAsync(
messages: history,
cancellationToken: cancellationToken
);
//
// Validate Response ...
if (!response.IsValid())
{
client.Dispose();
XException.ActionFailed.Throw();
}
//
var result = response.Text;
//
return result;
}
/// <summary>
/// Ask a Question using Provided Context Chunks (RAG) and Stream Response ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async IAsyncEnumerable<string> AskWithContextAsEnumerable(
string prompt,
IEnumerable<XAiVectorSearchResult> context,
[EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (prompt.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
using var client = Descriptor.GetClient();
var history = GetHistory(prompt, context);
var enumerable = client.GetStreamingResponseAsync(
options: null,
messages: history,
cancellationToken: cancellationToken
);
//
await foreach (var res in enumerable)
{
//
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
//
yield return res.Text;
}
}
/// <summary>
/// Ask a Question as Prompt and Retrieve Response ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="ownerId"></param>
/// <param name="topK"></param>
/// <param name="minScore"></param>
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="connectionId"></param>
@@ -182,9 +270,10 @@ namespace xAiApi.Providers
/// <returns></returns>
public virtual async Task<XAiMessageDto> AskAsync(
string prompt,
string ownerId,
Guid? projectId,
Guid? conversationId,
int? topK = null,
float? minScore = null,
Guid? projectId = null,
Guid? conversationId = null,
string connectionId = null,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
@@ -196,9 +285,36 @@ namespace xAiApi.Providers
validationProvider
.GroupValidationBuilder()
.AddNotEmpty(prompt)
.AddNotEmpty(ownerId)
.AddNotNull(userInfo)
.AddNotEmpty(userInfo.UserId)
.ValidateGroup();
//
// Normalize ...
if (!topK.HasValue ||
topK.Value < 1 ||
topK.Value > configuration.RAGDescriptor.MaxTopK
)
{
//
if (!topK.HasValue ||
(topK.HasValue && topK.Value < 1))
{
topK = configuration.RAGDescriptor.DefaultTopK;
}
else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK)
{
topK = configuration.RAGDescriptor.MaxTopK;
}
}
if (!minScore.HasValue ||
minScore.Value <= 0 ||
minScore.Value > 1
)
{
minScore = configuration.RAGDescriptor.DefaultMinScore;
}
//
// Check Project ...
XAiProjectDto project = null;
@@ -206,7 +322,7 @@ namespace xAiApi.Providers
{
//
project = await dataProvider.GetDefaultProject(
ownerId: ownerId,
ownerId: userInfo.UserId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
@@ -236,7 +352,7 @@ namespace xAiApi.Providers
{
//
conversation = await dataProvider.GetDefaultConversation(
ownerId: ownerId,
ownerId: userInfo.UserId,
projectId: projectId.Value,
connectionId: connectionId,
cancellationToken: cancellationToken
@@ -288,8 +404,10 @@ namespace xAiApi.Providers
// Prepare Knowledge Request ...
var knowledgeRequest = new XAiKnowledgeAskRequest
{
TopK = topK,
Prompt = prompt,
IncludeUser = true,
MinScore = minScore,
IncludeGlobal = true,
ProjectId = projectId,
ConversationId = conversationId
@@ -321,8 +439,8 @@ namespace xAiApi.Providers
var promptMessage = new XAiMessageDto
{
Content = prompt,
OwnerId = ownerId,
Role = XAiChatRole.User,
OwnerId = userInfo.UserId,
CreatedOn = DateTime.UtcNow,
ConversationId = conversationId.Value,
ConversationTitle = conversation.Title
@@ -355,7 +473,7 @@ namespace xAiApi.Providers
var result = new XAiMessageDto
{
Content = answer,
OwnerId = ownerId,
OwnerId = userInfo.UserId,
CreatedOn = DateTime.UtcNow,
Role = XAiChatRole.Assistant,
ConversationId = conversationId.Value,
@@ -376,20 +494,24 @@ namespace xAiApi.Providers
/// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="ownerId"></param>
/// <param name="topK"></param>
/// <param name="minScore"></param>
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="connectionId"></param>
/// <param name="files"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
string prompt,
string ownerId,
Guid projectId,
Guid conversationId,
int? topK = null,
float? minScore = null,
Guid? projectId = null,
Guid? conversationId = null,
string connectionId = null,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
[EnumeratorCancellation]
CancellationToken cancellationToken = default
)
@@ -399,17 +521,44 @@ namespace xAiApi.Providers
validationProvider
.GroupValidationBuilder()
.AddNotEmpty(prompt)
.AddNotEmpty(ownerId)
.AddNotNull(userInfo)
.AddNotEmpty(userInfo.UserId)
.ValidateGroup();
//
// Normalize ...
if (!topK.HasValue ||
topK.Value < 1 ||
topK.Value > configuration.RAGDescriptor.MaxTopK
)
{
//
if (!topK.HasValue ||
(topK.HasValue && topK.Value < 1))
{
topK = configuration.RAGDescriptor.DefaultTopK;
}
else if (topK.HasValue && topK.Value > configuration.RAGDescriptor.MaxTopK)
{
topK = configuration.RAGDescriptor.MaxTopK;
}
}
if (!minScore.HasValue ||
minScore.Value <= 0 ||
minScore.Value > 1
)
{
minScore = configuration.RAGDescriptor.DefaultMinScore;
}
//
// Check Project ...
XAiProjectDto project = null;
if (projectId.IsDefaultGuid())
if (!projectId.HasValue || projectId.Value.IsDefaultGuid())
{
//
project = await dataProvider.GetDefaultProject(
ownerId: ownerId,
ownerId: userInfo.UserId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
@@ -421,7 +570,7 @@ namespace xAiApi.Providers
{
//
project = await dataProvider.GetProject(
id: projectId,
id: projectId.Value,
fillConversations: false,
fillConversationMessages: false,
cancellationToken: cancellationToken
@@ -435,12 +584,12 @@ namespace xAiApi.Providers
//
// Check Conversation ...
XAiConversationDto conversation = null;
if (conversationId.IsDefaultGuid())
if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid())
{
//
conversation = await dataProvider.GetDefaultConversation(
ownerId: ownerId,
projectId: projectId,
ownerId: userInfo.UserId,
projectId: projectId.Value,
connectionId: connectionId,
cancellationToken: cancellationToken
);
@@ -452,8 +601,8 @@ namespace xAiApi.Providers
{
//
conversation = await dataProvider.GetConversation(
id: conversationId,
fillMessages: false,
id: conversationId.Value,
cancellationToken: cancellationToken
);
}
@@ -463,20 +612,60 @@ namespace xAiApi.Providers
}
//
// Reading Messages ...
var messages = await dataProvider.LoadMessages(
conversationId: conversationId,
// Ingest Files based on Conversation ...
XAiKnowledgeIngestResult ingestResult;
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
{
TopK = topK,
Prompt = prompt,
IncludeUser = true,
MinScore = minScore,
IncludeGlobal = true,
ProjectId = projectId,
ConversationId = conversationId
};
var context = await ragProvider.RetrieveAsync(
userInfo: userInfo,
request: knowledgeRequest,
cancellationToken: cancellationToken
);
//
// TODO: Parse Files ...
// for Attached them into Prompt Message ...
// Reading Messages ...
var messages = await dataProvider.LoadMessages(
conversationId: conversationId.Value,
cancellationToken: cancellationToken
);
//
// Handle Memory ...
IList<ChatMessage> history = await PrepareMemory(
project: project,
context: context,
messages: messages,
cancellationToken: cancellationToken
);
@@ -486,33 +675,33 @@ namespace xAiApi.Providers
var promptMessage = new XAiMessageDto
{
Content = prompt,
OwnerId = ownerId,
Role = XAiChatRole.User,
OwnerId = userInfo.UserId,
CreatedOn = DateTime.UtcNow,
ConversationId = conversationId,
ConversationId = conversationId.Value,
ConversationTitle = conversation.Title
};
//
// Save Prompt Message ...
promptMessage = await dataProvider.AddMessage(
item: promptMessage,
connectionId: connectionId,
conversationId: conversationId,
cancellationToken: cancellationToken
);
promptMessage = await dataProvider.Enrich(
source: promptMessage,
conversationId: conversationId.Value,
cancellationToken: cancellationToken
);
//
// Attach Uploaded Files ...
// Converts to ChatMessage ...
var promptChatMessage = promptMessage
.ToChatMessages();
.ToChatMessages(additionalContents: []);
history.Add(promptChatMessage);
//
// Ask Questions From LLM ...
using var client = Descriptor.GetClient();
var enumerable = client.GetStreamingResponseAsync(
options: null,
options: Options,
messages: history
);
@@ -531,9 +720,9 @@ namespace xAiApi.Providers
//
var resp = new XAiResonseMessage
{
OwnerId = ownerId,
Content = res.Text,
Sequence = sequence,
OwnerId = userInfo.UserId,
Role = XAiChatRole.System,
RespondTo = promptMessage.Id,
RespondedOn = DateTime.UtcNow,
@@ -552,15 +741,15 @@ namespace xAiApi.Providers
var result = new XAiMessageDto
{
Content = answer,
OwnerId = ownerId,
OwnerId = userInfo.UserId,
Role = XAiChatRole.System,
CreatedOn = DateTime.UtcNow,
ConversationId = conversationId
ConversationId = conversationId.Value
};
result = await dataProvider.AddMessage(
item: result,
connectionId: connectionId,
conversationId: conversationId,
conversationId: conversationId.Value,
cancellationToken: cancellationToken
);
}
@@ -1084,6 +1273,44 @@ namespace xAiApi.Providers
return result;
}
/// <summary>
/// Build Chat History for RAG:
/// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="context"></param>
/// <returns></returns>
protected virtual IList<ChatMessage> GetHistory(
string prompt,
IEnumerable<XAiVectorSearchResult> context
)
{
//
var introductionPrompt = configuration.GetPrompt();
var ragPrompt = configuration.GetPrompt(configuration.RAGDescriptor.PromptName);
if (ragPrompt.IsNullOrEmpty())
{
XException.InvalidConfiguration.Throw();
}
//
var contextBlock = BuildContextBlock(context);
var systemText =
$"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" +
$"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
$"Context:{Environment.NewLine}{contextBlock}";
//
List<ChatMessage> result =
[
new ChatMessage(ChatRole.System, systemText),
new ChatMessage(ChatRole.User, prompt),
];
//
return result;
}
/// <summary>
/// Implementing Memory Strategy here ...
/// </summary>
@@ -1222,6 +1449,7 @@ namespace xAiApi.Providers
history.Add(prompt);
using var client = Descriptor.GetClient();
var response = await client.GetResponseAsync(
options: Options,
messages: history,
cancellationToken: cancellationToken
);