last ...
This commit is contained in:
+269
-41
@@ -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
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user