1857 lines
59 KiB
C#
1857 lines
59 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using xModels.Dtos;
|
|
using xAiApi.Models;
|
|
using System.Threading;
|
|
using xAiApi.Constants;
|
|
using xAiModels.Models;
|
|
using TimeZoneConverter;
|
|
using xAiApi.Interfaces;
|
|
using xAiApi.Extensions;
|
|
using xCommons.Providers;
|
|
using xCommons.Extensions;
|
|
using xAiModels.Constants;
|
|
using xAiModels.Interfaces;
|
|
using xAiModels.Extensions;
|
|
using System.Globalization;
|
|
using xAiApi.Configurations;
|
|
using xExceptions.Constants;
|
|
using xAiModels.Models.Dtos;
|
|
using xAiService.Extensions;
|
|
using System.Threading.Tasks;
|
|
using xIdentityModels.Models;
|
|
using Microsoft.Extensions.AI;
|
|
using Microsoft.AspNetCore.Http;
|
|
using System.Collections.Generic;
|
|
using Microsoft.Extensions.Logging;
|
|
using xAiApi.Interfaces.Extractors;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
namespace xAiApi.Providers
|
|
{
|
|
/// <summary>
|
|
/// Base Ai Service ...
|
|
/// </summary>
|
|
public abstract class XAIServiceBase : IXAiServiceBase
|
|
{
|
|
/// <summary>
|
|
/// Chat Options ...
|
|
/// </summary>
|
|
public ChatOptions Options { get; }
|
|
|
|
/// <summary>
|
|
/// Descriptor of Models which used in Service ...
|
|
/// </summary>
|
|
public XAiModelDescriptor Descriptor { get; }
|
|
|
|
private readonly IXAiRAGService ragProvider;
|
|
private readonly IXAiDataProvider dataProvider;
|
|
private readonly ILogger<XAIServiceBase> logger;
|
|
private readonly XAiApiConfiguration configuration;
|
|
private readonly XValidationProvider validationProvider;
|
|
private readonly IXAiMcpServerProvider mcpServerProvider;
|
|
private readonly IXFileContentExtractor fileContentExtractor;
|
|
|
|
//
|
|
private readonly bool useProvidedMcpServers;
|
|
|
|
protected XAIServiceBase(
|
|
IXAiRAGService ragProvider,
|
|
IXAiDataProvider dataProvider,
|
|
ILogger<XAIServiceBase> logger,
|
|
XAiApiConfiguration configuration,
|
|
XValidationProvider validationProvider,
|
|
IXAiMcpServerProvider mcpServerProvider,
|
|
IXFileContentExtractor fileContentExtractor,
|
|
string model = null,
|
|
bool useProvidedMcpServers = true
|
|
)
|
|
{
|
|
//
|
|
this.logger = logger;
|
|
this.ragProvider = ragProvider;
|
|
this.dataProvider = dataProvider;
|
|
this.configuration = configuration;
|
|
this.mcpServerProvider = mcpServerProvider;
|
|
this.validationProvider = validationProvider;
|
|
this.fileContentExtractor = fileContentExtractor;
|
|
this.useProvidedMcpServers = useProvidedMcpServers;
|
|
|
|
//
|
|
// Prepare Embedding Model Descriptor ...
|
|
Descriptor = configuration.GetModel(model);
|
|
if (!Descriptor.IsValid())
|
|
{
|
|
XException.InvalidConfiguration.Throw();
|
|
}
|
|
|
|
//
|
|
// Prepare Chat Options based On Tools ...
|
|
Options = new ChatOptions();
|
|
}
|
|
|
|
//
|
|
#region Actions ...
|
|
/// <summary>
|
|
/// Base Method for Communicate with LLM ...
|
|
/// </summary>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<string> AskTextAsync(
|
|
string prompt,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Check Prompt Exists ...
|
|
if (prompt.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
using var client = Descriptor.GetClient();
|
|
var history = GetHistory(prompt);
|
|
|
|
//
|
|
// Handle Provided MCP Servers ...
|
|
if (useProvidedMcpServers)
|
|
{
|
|
//
|
|
var availableTools = await mcpServerProvider
|
|
.GetAvailableToolsAsync(
|
|
userInfo: userInfo,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
Options.Tools = [.. availableTools];
|
|
}
|
|
|
|
//
|
|
var response = await client.GetResponseAsync(
|
|
options: Options,
|
|
messages: history,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
// Validate Response ...
|
|
if (!response.IsValid())
|
|
{
|
|
//
|
|
// Dispose Client ...
|
|
client.Dispose();
|
|
XException.ActionFailed.Throw();
|
|
}
|
|
|
|
//
|
|
// Retrieve Response Text ...
|
|
var result = response.Text;
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Base Method for Communicate with LLM ...
|
|
/// </summary>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async IAsyncEnumerable<string> AskTextAsEnumerable(
|
|
string prompt,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
[EnumeratorCancellation]
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Check Prompt Exists ...
|
|
if (prompt.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
using var client = Descriptor.GetClient();
|
|
var history = GetHistory(prompt);
|
|
|
|
//
|
|
// Handle Provided MCP Servers ...
|
|
if (useProvidedMcpServers)
|
|
{
|
|
//
|
|
var availableTools = await mcpServerProvider
|
|
.GetAvailableToolsAsync(
|
|
userInfo: userInfo,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
Options.Tools = [.. availableTools.Cast<AITool>()];
|
|
}
|
|
|
|
//
|
|
var enumerable = client.GetStreamingResponseAsync(
|
|
options: Options,
|
|
messages: history
|
|
);
|
|
|
|
//
|
|
await foreach (var res in enumerable)
|
|
{
|
|
//
|
|
// Cancellation Token ...
|
|
if (cancellationToken.IsCancellationRequested)
|
|
{
|
|
yield break;
|
|
}
|
|
|
|
//
|
|
yield return res.Text;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ask a Question By Providing Vector Search Result ...
|
|
/// </summary>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="context"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<string> AskTextByContextAsync(
|
|
string prompt,
|
|
IList<XAiVectorSearchResult> context = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
validationProvider
|
|
.GroupValidationBuilder()
|
|
.AddNotEmpty(prompt)
|
|
.AddNotNull(userInfo)
|
|
.AddNotEmpty(userInfo.UserId)
|
|
.ValidateGroup();
|
|
|
|
//
|
|
using var client = Descriptor.GetClient();
|
|
var history = GetHistory(prompt, context);
|
|
|
|
//
|
|
// Handle Provided MCP Servers ...
|
|
if (useProvidedMcpServers)
|
|
{
|
|
//
|
|
var availableTools = await mcpServerProvider
|
|
.GetAvailableToolsAsync(
|
|
userInfo: userInfo,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
Options.Tools = [.. availableTools.Cast<AITool>()];
|
|
}
|
|
|
|
//
|
|
var response = await client.GetResponseAsync(
|
|
options: Options,
|
|
messages: history,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
// Validate Response ...
|
|
if (!response.IsValid())
|
|
{
|
|
client.Dispose();
|
|
XException.ActionFailed.Throw();
|
|
}
|
|
|
|
//
|
|
var result = response.Text;
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ask a Question By By Providing Vector Search Result and Stream Response ...
|
|
/// </summary>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="context"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async IAsyncEnumerable<string> AskTextByContextAsEnumerable(
|
|
string prompt,
|
|
IList<XAiVectorSearchResult> context = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
[EnumeratorCancellation]
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
validationProvider
|
|
.GroupValidationBuilder()
|
|
.AddNotEmpty(prompt)
|
|
.AddNotNull(userInfo)
|
|
.AddNotEmpty(userInfo.UserId)
|
|
.ValidateGroup();
|
|
|
|
//
|
|
using var client = Descriptor.GetClient();
|
|
var history = GetHistory(prompt, context);
|
|
|
|
//
|
|
// Handle Provided MCP Servers ...
|
|
if (useProvidedMcpServers)
|
|
{
|
|
//
|
|
var availableTools = await mcpServerProvider
|
|
.GetAvailableToolsAsync(
|
|
userInfo: userInfo,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
Options.Tools = [.. availableTools.Cast<AITool>()];
|
|
}
|
|
|
|
//
|
|
var enumerable = client.GetStreamingResponseAsync(
|
|
options: Options,
|
|
messages: history,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
await foreach (var res in enumerable)
|
|
{
|
|
//
|
|
if (cancellationToken.IsCancellationRequested)
|
|
{
|
|
yield break;
|
|
}
|
|
|
|
//
|
|
yield return res.Text;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ask a Question By Rag Retrive From Knowledge ...
|
|
/// </summary>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="type"></param>
|
|
/// <param name="topK"></param>
|
|
/// <param name="minScore"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<string> AskTextFromKnowledgeAsync(
|
|
string prompt,
|
|
string type = null,
|
|
int? topK = null,
|
|
float? minScore = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validation ...
|
|
validationProvider
|
|
.GroupValidationBuilder()
|
|
.AddNotEmpty(prompt)
|
|
.AddNotNull(userInfo)
|
|
.AddNotEmpty(userInfo.UserId)
|
|
.ValidateGroup();
|
|
|
|
//
|
|
// Prepare Requirements ...
|
|
var prep = await PrepareChatRequirementsAsync(
|
|
topK: topK,
|
|
type: type,
|
|
files: null,
|
|
prompt: prompt,
|
|
projectId: null,
|
|
minScore: minScore,
|
|
userInfo: userInfo,
|
|
connectionId: null,
|
|
conversationId: null,
|
|
persistPrompt: false,
|
|
additionalContents: null,
|
|
addFilesToKnowledge: false,
|
|
resolveConversation: false,
|
|
extractFileContents: false,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
using var client = Descriptor.GetClient();
|
|
|
|
//
|
|
// Handle Provided MCP Servers ...
|
|
if (useProvidedMcpServers)
|
|
{
|
|
//
|
|
var availableTools = await mcpServerProvider
|
|
.GetAvailableToolsAsync(
|
|
userInfo: userInfo,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
Options.Tools = [.. availableTools.Cast<AITool>()];
|
|
}
|
|
|
|
//
|
|
var response = await client
|
|
.GetResponseAsync(
|
|
options: Options,
|
|
messages: prep.History,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (!response.IsValid())
|
|
{
|
|
client.Dispose();
|
|
XException.ActionFailed.Throw();
|
|
}
|
|
|
|
//
|
|
return response.Text;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ask a Question By Rag Retrive From Knowledge and Stream Response ...
|
|
/// </summary>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="type"></param>
|
|
/// <param name="topK"></param>
|
|
/// <param name="minScore"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async IAsyncEnumerable<string> AskTextFromKnowledgeAsEnumerable(
|
|
string prompt,
|
|
string type = null,
|
|
int? topK = null,
|
|
float? minScore = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
[EnumeratorCancellation]
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validation ...
|
|
validationProvider
|
|
.GroupValidationBuilder()
|
|
.AddNotEmpty(prompt)
|
|
.AddNotNull(userInfo)
|
|
.AddNotEmpty(userInfo.UserId)
|
|
.ValidateGroup();
|
|
|
|
//
|
|
// Prepare Requirements ...
|
|
var prep = await PrepareChatRequirementsAsync(
|
|
topK: topK,
|
|
type: type,
|
|
files: null,
|
|
prompt: prompt,
|
|
projectId: null,
|
|
minScore: minScore,
|
|
userInfo: userInfo,
|
|
connectionId: null,
|
|
conversationId: null,
|
|
persistPrompt: false,
|
|
additionalContents: null,
|
|
resolveConversation: false,
|
|
addFilesToKnowledge: false,
|
|
extractFileContents: false,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
using var client = Descriptor.GetClient();
|
|
|
|
//
|
|
// Handle Provided MCP Servers ...
|
|
if (useProvidedMcpServers)
|
|
{
|
|
//
|
|
var availableTools = await mcpServerProvider
|
|
.GetAvailableToolsAsync(
|
|
userInfo: userInfo,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
Options.Tools = [.. availableTools.Cast<AITool>()];
|
|
}
|
|
|
|
//
|
|
var stream = client
|
|
.GetStreamingResponseAsync(
|
|
options: Options,
|
|
messages: prep.History,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
await foreach (var res in stream)
|
|
{
|
|
//
|
|
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="type"></param>
|
|
/// <param name="topK"></param>
|
|
/// <param name="minScore"></param>
|
|
/// <param name="projectId"></param>
|
|
/// <param name="conversationId"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="extractFileContents"></param>
|
|
/// <param name="addFilesToKnowledge"></param>
|
|
/// <param name="files"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<XAiMessageDto> AskAsync(
|
|
string prompt,
|
|
string type = null,
|
|
int? topK = null,
|
|
float? minScore = null,
|
|
Guid? projectId = null,
|
|
Guid? conversationId = null,
|
|
string connectionId = null,
|
|
bool extractFileContents = false,
|
|
bool addFilesToKnowledge = true,
|
|
IFormFileCollection files = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
validationProvider
|
|
.GroupValidationBuilder()
|
|
.AddNotEmpty(prompt)
|
|
.AddNotNull(userInfo)
|
|
.AddNotEmpty(userInfo.UserId)
|
|
.ValidateGroup();
|
|
|
|
//
|
|
var prep = await PrepareChatRequirementsAsync(
|
|
type: type,
|
|
topK: topK,
|
|
files: files,
|
|
prompt: prompt,
|
|
minScore: minScore,
|
|
userInfo: userInfo,
|
|
persistPrompt: true,
|
|
projectId: projectId,
|
|
additionalContents: null,
|
|
resolveConversation: true,
|
|
connectionId: connectionId,
|
|
conversationId: conversationId,
|
|
cancellationToken: cancellationToken,
|
|
extractFileContents: extractFileContents,
|
|
addFilesToKnowledge: addFilesToKnowledge
|
|
);
|
|
|
|
//
|
|
using var client = Descriptor.GetClient();
|
|
|
|
//
|
|
// Handle Provided MCP Servers ...
|
|
if (useProvidedMcpServers)
|
|
{
|
|
//
|
|
var availableTools = await mcpServerProvider
|
|
.GetAvailableToolsAsync(
|
|
userInfo: userInfo,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
Options.Tools = [.. availableTools.Cast<AITool>()];
|
|
}
|
|
|
|
//
|
|
var response = await client.GetResponseAsync(
|
|
options: Options,
|
|
messages: prep.History,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (!response.IsValid())
|
|
{
|
|
//
|
|
client.Dispose();
|
|
XException.ActionFailed.Throw();
|
|
}
|
|
|
|
//
|
|
var result = await dataProvider.AddMessage(
|
|
item: new XAiMessageDto
|
|
{
|
|
Content = response.Text,
|
|
OwnerId = userInfo.UserId,
|
|
CreatedOn = DateTime.UtcNow,
|
|
Role = XAiChatRole.Assistant,
|
|
ConversationId = prep.Conversation.Id,
|
|
ConversationTitle = prep.Conversation.Title,
|
|
},
|
|
connectionId: connectionId,
|
|
conversationId: prep.Conversation.Id,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
|
|
/// </summary>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="type"></param>
|
|
/// <param name="topK"></param>
|
|
/// <param name="minScore"></param>
|
|
/// <param name="projectId"></param>
|
|
/// <param name="conversationId"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="extractFileContents"></param>
|
|
/// <param name="addFilesToKnowledge"></param>
|
|
/// <param name="files"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
|
|
string prompt,
|
|
string type = null,
|
|
int? topK = null,
|
|
float? minScore = null,
|
|
Guid? projectId = null,
|
|
Guid? conversationId = null,
|
|
string connectionId = null,
|
|
bool extractFileContents = false,
|
|
bool addFilesToKnowledge = true,
|
|
IFormFileCollection files = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
[EnumeratorCancellation]
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
validationProvider
|
|
.GroupValidationBuilder()
|
|
.AddNotEmpty(prompt)
|
|
.AddNotNull(userInfo)
|
|
.AddNotEmpty(userInfo.UserId)
|
|
.ValidateGroup();
|
|
|
|
//
|
|
var prep = await PrepareChatRequirementsAsync(
|
|
type: type,
|
|
topK: topK,
|
|
files: files,
|
|
prompt: prompt,
|
|
minScore: minScore,
|
|
userInfo: userInfo,
|
|
persistPrompt: true,
|
|
projectId: projectId,
|
|
additionalContents: null,
|
|
resolveConversation: true,
|
|
connectionId: connectionId,
|
|
conversationId: conversationId,
|
|
cancellationToken: cancellationToken,
|
|
extractFileContents: extractFileContents,
|
|
addFilesToKnowledge: addFilesToKnowledge
|
|
);
|
|
|
|
//
|
|
using var client = Descriptor.GetClient();
|
|
|
|
//
|
|
// Handle Provided MCP Servers ...
|
|
if (useProvidedMcpServers)
|
|
{
|
|
//
|
|
var availableTools = await mcpServerProvider
|
|
.GetAvailableToolsAsync(
|
|
userInfo: userInfo,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
Options.Tools = [.. availableTools.Cast<AITool>()];
|
|
}
|
|
|
|
//
|
|
var stream = client
|
|
.GetStreamingResponseAsync(
|
|
options: Options,
|
|
messages: prep.History,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
var answer = new System.Text.StringBuilder();
|
|
long sequence = 1;
|
|
await foreach (var res in stream)
|
|
{
|
|
//
|
|
if (cancellationToken.IsCancellationRequested)
|
|
{
|
|
yield break;
|
|
}
|
|
|
|
//
|
|
answer.Append(res.Text);
|
|
yield return new XAiResonseMessage
|
|
{
|
|
Content = res.Text,
|
|
Sequence = sequence++,
|
|
OwnerId = userInfo.UserId,
|
|
Role = XAiChatRole.Assistant,
|
|
RespondedOn = DateTime.UtcNow,
|
|
RespondTo = prep.PersistedPromptMessage.Id,
|
|
};
|
|
}
|
|
|
|
//
|
|
// Adding Full Message ...
|
|
await dataProvider.AddMessage(
|
|
item: new XAiMessageDto
|
|
{
|
|
OwnerId = userInfo.UserId,
|
|
Content = answer.ToString(),
|
|
CreatedOn = DateTime.UtcNow,
|
|
Role = XAiChatRole.Assistant,
|
|
ConversationId = prep.Conversation.Id,
|
|
},
|
|
connectionId: connectionId,
|
|
conversationId: prep.Conversation.Id,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
}
|
|
#endregion
|
|
|
|
//
|
|
#region Loaders ...
|
|
/// <summary>
|
|
/// Load AI Projects ...
|
|
/// </summary>
|
|
/// <param name="ownerId"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="includeDefaults"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<IEnumerable<XAiProjectDto>> LoadProjects(
|
|
string ownerId,
|
|
string connectionId = null,
|
|
bool includeDefaults = false,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
if (ownerId.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var result = await dataProvider.LoadProjects(
|
|
ownerId: ownerId,
|
|
fillConversations: false,
|
|
connectionId: connectionId,
|
|
fillConversationMessages: false,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
// Handle Defaults Including ...
|
|
if (includeDefaults)
|
|
{
|
|
//
|
|
// Here we have to fill Conversations of Default Project ...
|
|
var defaultProjectId = result.GetDafaultProject(ownerId);
|
|
var defaultProject = result.FirstOrDefault(x => x.Id == defaultProjectId);
|
|
result = result.Where(x => x.Id != defaultProjectId);
|
|
|
|
//
|
|
// Reading Conversations of Specified Default Project ...
|
|
var defaultProjectConversations = await dataProvider.LoadConversations(
|
|
fillMessages: false,
|
|
connectionId: connectionId,
|
|
projectId: defaultProjectId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
var defaultConversationId = defaultProjectConversations.GetDefaultConversation(
|
|
ownerId: ownerId,
|
|
projectId: defaultProjectId
|
|
);
|
|
var defaultConversation = defaultProjectConversations.First(x => x.Id == defaultConversationId);
|
|
defaultProjectConversations = defaultProjectConversations.Where(x => x.Id != defaultConversationId);
|
|
|
|
//
|
|
// Reading Default Conversations Messages ...
|
|
var defaultConversationMessages = await dataProvider.LoadMessages(
|
|
cancellationToken: cancellationToken,
|
|
conversationId: defaultConversationId
|
|
);
|
|
|
|
//
|
|
defaultConversation.Messages = [.. defaultConversationMessages.OrderByDescending(m => m.CreatedOn)];
|
|
defaultProjectConversations = [defaultConversation, .. defaultProjectConversations];
|
|
defaultProject.Conversations = [.. defaultProjectConversations];
|
|
result = [defaultProject, .. result];
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load Conversations of Specified AI Project ...
|
|
/// </summary>
|
|
/// <param name="projectId"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<IEnumerable<XAiConversationDto>> LoadConversations(
|
|
Guid projectId,
|
|
string connectionId = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
if (projectId.IsDefaultGuid())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var result = await dataProvider.LoadConversations(
|
|
fillMessages: false,
|
|
projectId: projectId,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load Messages of Specified Conversation ...
|
|
/// </summary>
|
|
/// <param name="conversationId"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<IEnumerable<XAiMessageDto>> LoadMessages(
|
|
Guid conversationId,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
if (conversationId.IsDefaultGuid())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var result = await dataProvider.LoadMessages(
|
|
conversationId: conversationId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
|
|
//
|
|
#region Queries ...
|
|
/// <summary>
|
|
/// Query Projects ...
|
|
/// </summary>
|
|
/// <param name="ownerId"></param>
|
|
/// <param name="query"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<XQueryResult<XAiProjectDto>> QueryProjects(
|
|
string ownerId,
|
|
XQuery query,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (ownerId.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var result = await dataProvider.QueryProjects(
|
|
query: query,
|
|
ownerId: ownerId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Query Conversations ...
|
|
/// </summary>
|
|
/// <param name="ownerId"></param>
|
|
/// <param name="projectId"></param>
|
|
/// <param name="query"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<XQueryResult<XAiConversationDto>> QueryConversations(
|
|
string ownerId,
|
|
Guid projectId,
|
|
XQuery query,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (ownerId.IsNullOrEmpty() ||
|
|
projectId.IsDefaultGuid())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
// Retrieve Project ...
|
|
var project = await dataProvider.GetProject(
|
|
id: projectId,
|
|
fillConversations: false,
|
|
fillConversationMessages: false,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (project.IsNullOrDefault())
|
|
{
|
|
XException.NotFound.Throw();
|
|
}
|
|
|
|
//
|
|
// Validate Owner ...
|
|
if (ownerId != project.OwnerId)
|
|
{
|
|
XException.NotAllowed.Throw();
|
|
}
|
|
|
|
//
|
|
var result = await dataProvider.QueryConversations(
|
|
query: query,
|
|
ownerId: ownerId,
|
|
projectId: projectId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Query Messages ...
|
|
/// </summary>
|
|
/// <param name="ownerId"></param>
|
|
/// <param name="conversationId"></param>
|
|
/// <param name="query"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<XQueryResult<XAiMessageDto>> QueryMessages(
|
|
string ownerId,
|
|
Guid conversationId,
|
|
XQuery query,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (ownerId.IsNullOrEmpty() ||
|
|
conversationId.IsDefaultGuid())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
// Retrieve Conversation ...
|
|
var conversation = await dataProvider.GetConversation(
|
|
id: conversationId,
|
|
fillMessages: false,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (conversation.IsNullOrDefault())
|
|
{
|
|
XException.NotFound.Throw();
|
|
}
|
|
|
|
//
|
|
// Validate Owner ...
|
|
if (ownerId != conversation.OwnerId)
|
|
{
|
|
XException.NotAllowed.Throw();
|
|
}
|
|
|
|
//
|
|
var result = await dataProvider.QueryMessages(
|
|
query: query,
|
|
ownerId: ownerId,
|
|
conversationId: conversationId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
|
|
//
|
|
#region Creators ...
|
|
/// <summary>
|
|
/// Create an AI Project ...
|
|
/// </summary>
|
|
/// <param name="ownerId"></param>
|
|
/// <param name="item"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<XAiProjectDto> CreateProject(
|
|
string ownerId,
|
|
XAiProjectDto item,
|
|
string connectionId = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
var result = await dataProvider.CreateProject(
|
|
item: item,
|
|
ownerId: ownerId,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create an AI Conversation ...
|
|
/// </summary>
|
|
/// <param name="ownerId"></param>
|
|
/// <param name="projectId"></param>
|
|
/// <param name="item"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public virtual async Task<XAiConversationDto> CreateConversation(
|
|
string ownerId,
|
|
Guid projectId,
|
|
XAiConversationDto item,
|
|
string connectionId = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
var result = await dataProvider.CreateConversation(
|
|
item: item,
|
|
ownerId: ownerId,
|
|
projectId: projectId,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
|
|
//
|
|
#region Content Extraction ...
|
|
/// <summary>
|
|
/// Try to Extract Files Content ...
|
|
/// </summary>
|
|
/// <param name="files"></param>
|
|
/// <param name="extractors"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<string> ExtractContent(
|
|
IFormFileCollection files,
|
|
string[] extractors = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
if (!files.HasChild())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var extractionResults = new List<XFileExtractionResult>();
|
|
foreach (var file in files)
|
|
{
|
|
//
|
|
if (file.IsNull() || file.Length == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
//
|
|
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
|
|
if (!fileContentExtractor.CanExtract(mimeType, extractors))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
//
|
|
try
|
|
{
|
|
//
|
|
using var stream = file.OpenReadStream();
|
|
|
|
//
|
|
var fr = await fileContentExtractor.ExtractRichAsync(
|
|
fileStream: stream,
|
|
mimeType: mimeType,
|
|
extractors: extractors,
|
|
fileName: file.FileName,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
if (fr.IsValid())
|
|
{
|
|
extractionResults.Add(fr);
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
throw;
|
|
}
|
|
catch
|
|
{
|
|
continue;
|
|
}
|
|
}
|
|
|
|
//
|
|
var result = string.Empty;
|
|
if (extractionResults.HasChild())
|
|
{
|
|
//
|
|
extractionResults.ForEach(er =>
|
|
{
|
|
result += $"File {er.FileName} Content:{Environment.NewLine}{er.Text ?? er.AudioTranscript}{Environment.NewLine}----";
|
|
});
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
|
|
/// <summary>
|
|
/// Base Dispose Action ...
|
|
/// </summary>
|
|
/// <exception cref="NotImplementedException"></exception>
|
|
public virtual void Dispose()
|
|
{ }
|
|
|
|
//
|
|
#region Private ...
|
|
/// <summary>
|
|
/// Prepare a Message History List for LLM Communication based on Prompt ...
|
|
/// </summary>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="forcePrompt"></param>
|
|
/// <returns></returns>
|
|
private IList<ChatMessage> GetHistory(
|
|
string prompt = null,
|
|
bool forcePrompt = true
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
if (prompt.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
// User Prompt ...
|
|
var promptMessage = new ChatMessage(
|
|
ChatRole.User,
|
|
prompt
|
|
);
|
|
|
|
//
|
|
// Preparing Introduction Prompt ...
|
|
var introductionPrompt = new ChatMessage(
|
|
ChatRole.System,
|
|
configuration.GetPrompt()
|
|
);
|
|
|
|
//
|
|
List<ChatMessage> result =
|
|
[
|
|
introductionPrompt,
|
|
];
|
|
|
|
//
|
|
// Prepare Datetime ...
|
|
var datetimeContext = BuildDateTimeContext();
|
|
if (!datetimeContext.IsNullOrEmpty())
|
|
{
|
|
//
|
|
result.Add(new ChatMessage(
|
|
ChatRole.Assistant,
|
|
datetimeContext
|
|
));
|
|
}
|
|
|
|
//
|
|
if (forcePrompt &&
|
|
prompt is not null &&
|
|
!prompt.IsNullOrEmpty())
|
|
{
|
|
result.Add(promptMessage);
|
|
}
|
|
|
|
//
|
|
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>
|
|
private IList<ChatMessage> GetHistory(
|
|
string prompt,
|
|
IEnumerable<XAiVectorSearchResult> context
|
|
)
|
|
{
|
|
//
|
|
var introductionPrompt = configuration.GetPrompt();
|
|
var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
|
|
if (ragPrompt.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidConfiguration.Throw();
|
|
}
|
|
|
|
//
|
|
var datetimeContext = BuildDateTimeContext();
|
|
var contextBlock = BuildContextBlock(context);
|
|
var systemText = introductionPrompt;
|
|
if (context.HasChild() &&
|
|
!contextBlock.IsNullOrEmpty()
|
|
)
|
|
{
|
|
//
|
|
systemText =
|
|
$"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}";
|
|
|
|
//
|
|
if (!datetimeContext.IsNullOrEmpty())
|
|
{
|
|
//
|
|
systemText += $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
|
|
}
|
|
|
|
//
|
|
systemText +=
|
|
$"{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>
|
|
/// <param name="project"></param>
|
|
/// <param name="messages"></param>
|
|
/// <param name="context"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
private async Task<IList<ChatMessage>> PrepareMemory(
|
|
XAiProjectDto project,
|
|
IEnumerable<XAiMessageDto> messages,
|
|
IEnumerable<XAiVectorSearchResult> context = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
var result = new List<ChatMessage>();
|
|
|
|
//
|
|
await Task.FromResult(true);
|
|
|
|
//
|
|
// Retrieve Introduction Prompt ...
|
|
var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
|
|
var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName);
|
|
if (ragPrompt.IsNullOrEmpty() ||
|
|
introductionPrompt.IsNullOrEmpty()
|
|
)
|
|
{
|
|
XException.InvalidData.Throw();
|
|
}
|
|
|
|
//
|
|
var contextBlock = BuildContextBlock(context);
|
|
var systemText = introductionPrompt;
|
|
if (context.HasChild() &&
|
|
!contextBlock.IsNullOrEmpty())
|
|
{
|
|
//
|
|
systemText =
|
|
$"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" +
|
|
$"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
|
|
$"Context:{Environment.NewLine}{contextBlock}";
|
|
}
|
|
|
|
//
|
|
// Prepare Datetime ...
|
|
var datetimeContext = BuildDateTimeContext();
|
|
if (!datetimeContext.IsNullOrEmpty())
|
|
{
|
|
//
|
|
systemText +=
|
|
$"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
|
|
}
|
|
|
|
//
|
|
// Apply Project Prompt as System Text ...
|
|
if (!project.IsNullOrDefault() &&
|
|
!project.Prompt.IsNullOrEmpty())
|
|
{
|
|
systemText += $"{project.Prompt}{Environment.NewLine}{Environment.NewLine}";
|
|
}
|
|
|
|
//
|
|
// Add System Message ...
|
|
result.Add(new ChatMessage(ChatRole.System, systemText));
|
|
|
|
//
|
|
// Attach Message ...
|
|
if (messages.HasChild())
|
|
{
|
|
//
|
|
// TODO: Here we can Implement Memory Management based on
|
|
// Last nth of Messages, or Summarization of Messages, etc ...
|
|
result = [..result, ..messages
|
|
.OrderBy(m => m.CreatedOn)
|
|
.Select(m => m.ToChatMessages())];
|
|
}
|
|
|
|
//
|
|
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>
|
|
/// Normalizing Rag Params ...
|
|
/// </summary>
|
|
/// <param name="topK"></param>
|
|
/// <param name="minScore"></param>
|
|
/// <param name="type"></param>
|
|
private void NormalizeRagParams(
|
|
ref int? topK,
|
|
ref float? minScore,
|
|
ref string type
|
|
)
|
|
{
|
|
//
|
|
var rag = configuration.RAGDescriptor;
|
|
|
|
//
|
|
// TopK ...
|
|
if (!topK.HasValue || topK.Value < 1)
|
|
{
|
|
topK = rag.DefaultTopK;
|
|
}
|
|
else if (topK.Value > rag.MaxTopK)
|
|
{
|
|
topK = rag.MaxTopK;
|
|
}
|
|
|
|
//
|
|
// Min Score ...
|
|
if (!minScore.HasValue || minScore.Value < 0 || minScore.Value > 1)
|
|
{
|
|
minScore = rag.DefaultMinScore;
|
|
}
|
|
|
|
//
|
|
// Type ...
|
|
if (type.IsNullOrEmpty())
|
|
{
|
|
type = XAiModelsConstants.XAiDefaultKnowledgeType;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Retrieve Prepared Chat Context ...
|
|
/// </summary>
|
|
/// <param name="topK"></param>
|
|
/// <param name="type"></param>
|
|
/// <param name="prompt"></param>
|
|
/// <param name="minScore"></param>
|
|
/// <param name="projectId"></param>
|
|
/// <param name="persistPrompt"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="conversationId"></param>
|
|
/// <param name="resolveConversation"></param>
|
|
/// <param name="files"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="extractFileContents"></param>
|
|
/// <param name="addFilesToKnowledge"></param>
|
|
/// <param name="additionalContents"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
private async Task<XPreparedChatContext> PrepareChatRequirementsAsync(
|
|
int? topK,
|
|
string type,
|
|
string prompt,
|
|
float? minScore,
|
|
Guid? projectId,
|
|
bool persistPrompt,
|
|
string connectionId,
|
|
Guid? conversationId,
|
|
bool resolveConversation,
|
|
IFormFileCollection files,
|
|
XUserClaimsInfoDto userInfo,
|
|
bool extractFileContents = true,
|
|
bool addFilesToKnowledge = false,
|
|
IList<AIContent> additionalContents = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Validate Args ...
|
|
validationProvider
|
|
.GroupValidationBuilder()
|
|
.AddNotEmpty(prompt)
|
|
.AddNotNull(userInfo)
|
|
.AddNotEmpty(userInfo.UserId)
|
|
.ValidateGroup();
|
|
|
|
//
|
|
// Normalize ...
|
|
NormalizeRagParams(
|
|
topK: ref topK,
|
|
type: ref type,
|
|
minScore: ref minScore
|
|
);
|
|
|
|
//
|
|
// Resolve Project and Conversation ...
|
|
XAiProjectDto project = null;
|
|
XAiConversationDto conversation = null;
|
|
if (resolveConversation)
|
|
{
|
|
//
|
|
// Check Project ...
|
|
if (!projectId.HasValue || projectId.Value.IsDefaultGuid())
|
|
{
|
|
//
|
|
project = await dataProvider.GetDefaultProject(
|
|
ownerId: userInfo.UserId,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
projectId = project.Id;
|
|
}
|
|
else
|
|
{
|
|
//
|
|
project = await dataProvider.GetProject(
|
|
id: projectId.Value,
|
|
fillConversations: false,
|
|
fillConversationMessages: false,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
}
|
|
if (project.IsNullOrDefault())
|
|
{
|
|
XException.NotFound.Throw();
|
|
}
|
|
|
|
//
|
|
// Check Conversation ...
|
|
if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid())
|
|
{
|
|
//
|
|
conversation = await dataProvider.GetDefaultConversation(
|
|
ownerId: userInfo.UserId,
|
|
projectId: projectId.Value,
|
|
connectionId: connectionId,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
conversationId = conversation.Id;
|
|
}
|
|
else
|
|
{
|
|
//
|
|
conversation = await dataProvider.GetConversation(
|
|
fillMessages: false,
|
|
id: conversationId.Value,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
}
|
|
if (conversation.IsNullOrDefault())
|
|
{
|
|
XException.NotFound.Throw();
|
|
}
|
|
}
|
|
|
|
//
|
|
// Ingest Files if Provided and also Resolve Conversation Flagged ...
|
|
if (
|
|
files.HasChild() &&
|
|
resolveConversation &&
|
|
addFilesToKnowledge
|
|
)
|
|
{
|
|
//
|
|
try
|
|
{
|
|
//
|
|
var ingestResult = await ragProvider
|
|
.IngestAsync(
|
|
files: files,
|
|
userInfo: userInfo,
|
|
replaceExisting: true,
|
|
connectionId: connectionId,
|
|
scope: XAiKnowledgeScopeDescriptor
|
|
.Conversation(
|
|
type: type,
|
|
conversationId: conversationId.Value
|
|
),
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (ingestResult.SkippedFiles.HasChild())
|
|
{
|
|
//
|
|
logger.LogWarning(
|
|
"Ingest skipped {Count} file(s): {Files}",
|
|
ingestResult.SkippedFiles.Count,
|
|
string.Join(", ", ingestResult.SkippedFiles));
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
throw;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
//
|
|
logger.LogError(ex,
|
|
"Ingest failed for prompt '{Prompt}'. Continuing without attachments.",
|
|
prompt
|
|
);
|
|
}
|
|
}
|
|
|
|
//
|
|
// If there isn't Files need to add Files to Knowledge ...
|
|
if (files.HasChild() &&
|
|
!addFilesToKnowledge
|
|
)
|
|
{
|
|
//
|
|
// Extract File Content and add them to Additional Contents ...
|
|
foreach (var file in files)
|
|
{
|
|
//
|
|
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
|
|
if (mimeType.IsNullOrEmpty() ||
|
|
!fileContentExtractor.CanExtract(mimeType))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
//
|
|
using var stream = file.OpenReadStream();
|
|
|
|
//
|
|
// Extract File Content if necessary ...
|
|
if (extractFileContents)
|
|
{
|
|
//
|
|
var content = await fileContentExtractor.ExtractAsync(
|
|
fileStream: stream,
|
|
mimeType: mimeType,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
if (!content.IsNullOrEmpty())
|
|
{
|
|
//
|
|
var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}");
|
|
additionalContents = [.. additionalContents, fileContent];
|
|
}
|
|
}
|
|
else
|
|
{
|
|
//
|
|
var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken);
|
|
additionalContents = [.. additionalContents, fileContent];
|
|
}
|
|
}
|
|
}
|
|
|
|
//
|
|
// Request Knowledge ...
|
|
var knowledgeRequest = new XAiKnowledgeAskRequest
|
|
{
|
|
TopK = topK,
|
|
Type = type,
|
|
Prompt = prompt,
|
|
IncludeUser = true,
|
|
MinScore = minScore,
|
|
IncludeGlobal = true,
|
|
ProjectId = resolveConversation ? projectId : null,
|
|
ConversationId = resolveConversation ? conversationId : null,
|
|
};
|
|
var context = await ragProvider
|
|
.RetrieveAsync(
|
|
userInfo: userInfo,
|
|
request: knowledgeRequest,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
// Prepare History and Persisted Prompt Message ...
|
|
IList<ChatMessage> history;
|
|
XAiMessageDto persistedPromptMessage = null;
|
|
if (persistPrompt)
|
|
{
|
|
//
|
|
// Retrieve Conversation Message ...
|
|
var messages = await dataProvider
|
|
.LoadMessages(
|
|
conversationId: conversationId.Value,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
// Prepare History based on Memory Strategies ...
|
|
history = await PrepareMemory(
|
|
context: context,
|
|
project: project,
|
|
messages: messages,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
// Persist Prompt Message ...
|
|
persistedPromptMessage = await dataProvider.AddMessage(
|
|
item: new XAiMessageDto
|
|
{
|
|
Content = prompt,
|
|
Role = XAiChatRole.User,
|
|
OwnerId = userInfo.UserId,
|
|
CreatedOn = DateTime.UtcNow,
|
|
ConversationId = conversationId.Value,
|
|
ConversationTitle = conversation.Title,
|
|
},
|
|
connectionId: connectionId,
|
|
conversationId: conversationId.Value,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
history
|
|
.Add(persistedPromptMessage
|
|
.ToChatMessages(additionalContents: additionalContents));
|
|
}
|
|
else
|
|
{
|
|
//
|
|
history = GetHistory(prompt, context);
|
|
}
|
|
|
|
//
|
|
// Prepare Result ...
|
|
var result = new XPreparedChatContext
|
|
{
|
|
Project = project,
|
|
Context = context,
|
|
History = history,
|
|
Conversation = conversation,
|
|
PersistedPromptMessage = persistedPromptMessage,
|
|
};
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
private string BuildDateTimeContext()
|
|
{
|
|
//
|
|
var cfg = configuration.DateTime;
|
|
if (cfg == null || !cfg.InjectIntoSystemPrompt)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
|
|
//
|
|
try
|
|
{
|
|
//
|
|
var tz = ResolveTimezone(cfg.DefaultTimezone);
|
|
var nowUtc = DateTime.UtcNow;
|
|
var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz);
|
|
|
|
//
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine("[CURRENT DATETIME — for your reference]");
|
|
sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}");
|
|
|
|
//
|
|
if (cfg.IncludeDayOfWeek)
|
|
{
|
|
sb.AppendLine($"Day of week: {nowLocal:dddd}");
|
|
}
|
|
|
|
//
|
|
if (cfg.IncludePersianCalendar)
|
|
{
|
|
//
|
|
var pc = new PersianCalendar();
|
|
sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}");
|
|
}
|
|
|
|
//
|
|
if (cfg.IncludeUnixTimestamp)
|
|
{
|
|
sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}");
|
|
}
|
|
|
|
//
|
|
sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations.");
|
|
return sb.ToString().TrimEnd();
|
|
}
|
|
catch
|
|
{
|
|
return string.Empty;
|
|
}
|
|
}
|
|
|
|
private static TimeZoneInfo ResolveTimezone(string id)
|
|
{
|
|
//
|
|
if (id.IsNullOrEmpty())
|
|
{
|
|
return TimeZoneInfo.Utc;
|
|
}
|
|
|
|
//
|
|
try
|
|
{
|
|
return TZConvert.GetTimeZoneInfo(id);
|
|
}
|
|
catch
|
|
{
|
|
return TimeZoneInfo.Utc;
|
|
}
|
|
}
|
|
#endregion
|
|
}
|
|
} |