diff --git a/Controllers/ChatWithDocumentsController.cs b/Controllers/ChatWithDocumentsController.cs
index 5f04993..c7df8bd 100644
--- a/Controllers/ChatWithDocumentsController.cs
+++ b/Controllers/ChatWithDocumentsController.cs
@@ -34,7 +34,7 @@ namespace xAiApi.Controllers
///
/// Default AI Service ...
///
- private readonly IXDefaultAiService aiService;
+ private readonly IXAiService aiService;
///
/// Text Chunker Service ...
@@ -62,8 +62,8 @@ namespace xAiApi.Controllers
private readonly IXFileContentExtractor fileContentExtractor;
public ChatWithDocumentsController(
+ IXAiService aiService,
IXTextChunker textChunker,
- IXDefaultAiService aiService,
IXInMemoryVectorStore vectorStore,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
diff --git a/Controllers/DefaultAiController.cs b/Controllers/XAiController.cs
similarity index 75%
rename from Controllers/DefaultAiController.cs
rename to Controllers/XAiController.cs
index 1ca2e82..3726c60 100644
--- a/Controllers/DefaultAiController.cs
+++ b/Controllers/XAiController.cs
@@ -10,11 +10,11 @@ namespace xAiApi.Controllers
{
[Authorize]
[Route("[controller]")]
- public class DefaultAiController : XAiServiceControllerBase
+ public class XAiController : XAiServiceControllerBase
{
- public DefaultAiController(
- ILogger logger,
- IXDefaultAiService aiService,
+ public XAiController(
+ ILogger logger,
+ IXAiService aiService,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs
index f38c63c..1066bb6 100644
--- a/DI/XDIHelperExtension.cs
+++ b/DI/XDIHelperExtension.cs
@@ -96,7 +96,7 @@ namespace xAiApi.DI
)
{
//
- source.AddScoped();
+ source.AddScoped();
source.AddScoped();
}
diff --git a/Interfaces/IXAiService.cs b/Interfaces/IXAiService.cs
new file mode 100644
index 0000000..18da89d
--- /dev/null
+++ b/Interfaces/IXAiService.cs
@@ -0,0 +1,5 @@
+namespace xAiApi.Interfaces
+{
+ public interface IXAiService : IXAiServiceBase
+ { }
+}
\ No newline at end of file
diff --git a/Interfaces/IXAiServiceBase.cs b/Interfaces/IXAiServiceBase.cs
index 8c3f7f3..abce7f6 100644
--- a/Interfaces/IXAiServiceBase.cs
+++ b/Interfaces/IXAiServiceBase.cs
@@ -51,53 +51,46 @@ namespace xAiApi.Interfaces
);
///
- /// Prepare a Message History List for LLM Communication based on Prompt ...
+ /// Ask a Question as Prompt and Retrieve Response ...
///
///
- ///
- ///
- IList GetHistory(
- string prompt = null,
- bool forcePrompt = true
- );
-
- ///
- /// Prepare a Message History List for LLM Communication based on Prompt ...
- ///
- ///
- ///
- ///
- IList GetHistory(
- ChatMessage message = null,
- bool forceMessage = true
- );
- #endregion
-
- //
- #region Context Actions ...
- ///
- /// Ask a Question using Provided Context Chunks (RAG) without Persisting ...
- ///
- ///
- ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
///
///
- Task AskWithContextAsync(
+ Task AskAsync(
string prompt,
- IEnumerable context,
+ string ownerId,
+ Guid? projectId,
+ Guid? conversationId,
+ string connectionId = null,
+ IFormFileCollection files = null,
+ XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
///
- /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ...
+ /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
///
///
- ///
+ ///
+ ///
+ ///
+ ///
+ ///
///
///
- IAsyncEnumerable AskWithContextAsEnumerable(
+ IAsyncEnumerable AskAsEnumerable(
string prompt,
- IEnumerable context,
+ string ownerId,
+ Guid projectId,
+ Guid conversationId,
+ string connectionId = null,
+ IFormFileCollection files = null,
CancellationToken cancellationToken = default
);
#endregion
@@ -240,52 +233,5 @@ namespace xAiApi.Interfaces
CancellationToken cancellationToken = default
);
#endregion
-
- //
- #region Data Actions ...
- ///
- /// Ask a Question as Prompt and Retrieve Response ...
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- Task AskAsync(
- string prompt,
- string ownerId,
- Guid? projectId,
- Guid? conversationId,
- string connectionId = null,
- IFormFileCollection files = null,
- XUserClaimsInfoDto userInfo = null,
- CancellationToken cancellationToken = default
- );
-
- ///
- /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- IAsyncEnumerable AskAsEnumerable(
- string prompt,
- string ownerId,
- Guid projectId,
- Guid conversationId,
- string connectionId = null,
- IFormFileCollection files = null,
- CancellationToken cancellationToken = default
- );
- #endregion
}
}
\ No newline at end of file
diff --git a/Interfaces/IXDefaultAiService.cs b/Interfaces/IXDefaultAiService.cs
deleted file mode 100644
index 1bc6a1f..0000000
--- a/Interfaces/IXDefaultAiService.cs
+++ /dev/null
@@ -1,5 +0,0 @@
-namespace xAiApi.Interfaces
-{
- public interface IXDefaultAiService : IXAiServiceBase
- { }
-}
\ No newline at end of file
diff --git a/Providers/XAIServiceBase.cs b/Providers/XAIServiceBase.cs
index a15b378..3ee112c 100644
--- a/Providers/XAIServiceBase.cs
+++ b/Providers/XAIServiceBase.cs
@@ -167,214 +167,402 @@ namespace xAiApi.Providers
yield return res.Text;
}
}
-
+
///
- /// Prepare a Message History List for LLM Communication based on Prompt ...
+ /// Ask a Question as Prompt and Retrieve Response ...
///
///
- ///
- ///
- public virtual IList 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 result =
- [
- introductionPrompt,
- ];
- if (forcePrompt &&
- prompt is not null &&
- !string.IsNullOrWhiteSpace(prompt))
- {
- result.Add(promptMessage);
- }
-
- //
- return result;
- }
-
- ///
- /// Prepare a Message History List for LLM Communication based on Prompt ...
- ///
- ///
- ///
- ///
- public virtual IList GetHistory(
- ChatMessage message = null,
- bool forceMessage = true
- )
- {
- //
- // Preparing Introduction Prompt ...
- var introductionPrompt = new ChatMessage(
- ChatRole.System,
- configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName)
- );
-
- //
- List result =
- [
- introductionPrompt,
- ];
- if (forceMessage &&
- !message.IsNullOrDefault())
- {
- result.Add(message);
- }
-
- //
- return result;
- }
- #endregion
-
- //
- #region Context Actions ...
- ///
- /// Ask a Question using Provided Context Chunks (RAG) without Persisting ...
- ///
- ///
- ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
///
///
- public virtual async Task AskWithContextAsync(
+ public virtual async Task AskAsync(
string prompt,
- IEnumerable context,
+ string ownerId,
+ Guid? projectId,
+ Guid? conversationId,
+ string connectionId = null,
+ IFormFileCollection files = null,
+ XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
- if (prompt.IsNullOrEmpty())
+ validationProvider
+ .GroupValidationBuilder()
+ .AddNotEmpty(prompt)
+ .AddNotEmpty(ownerId)
+ .ValidateGroup();
+
+ //
+ // Check Project ...
+ XAiProjectDto project = null;
+ if (!projectId.HasValue || projectId.Value.IsDefaultGuid())
{
- XException.InvalidArgs.Throw();
+ //
+ project = await dataProvider.GetDefaultProject(
+ ownerId: ownerId,
+ 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();
}
//
- using var client = Descriptor.GetClient();
- var history = GetContextHistory(prompt, context);
- var response = await client.GetResponseAsync(
- messages: history,
+ // Check Conversation ...
+ XAiConversationDto conversation = null;
+ if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid())
+ {
+ //
+ conversation = await dataProvider.GetDefaultConversation(
+ ownerId: ownerId,
+ 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 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
+ {
+ Prompt = prompt,
+ IncludeUser = true,
+ IncludeGlobal = true,
+ ProjectId = projectId,
+ ConversationId = conversationId
+ };
+ var context = await ragProvider.RetrieveAsync(
+ userInfo: userInfo,
+ request: knowledgeRequest,
cancellationToken: cancellationToken
);
//
- // Validate Response ...
- if (!response.IsValid())
- {
- client.Dispose();
- XException.ActionFailed.Throw();
- }
+ // Reading Messages ...
+ var messages = await dataProvider.LoadMessages(
+ conversationId: conversationId.Value,
+ cancellationToken: cancellationToken
+ );
//
- var result = response.Text;
+ // Handle Memory ...
+ IList history = await PrepareMemory(
+ project: project,
+ context: context,
+ messages: messages,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ // Prepare and Add Prompt Message ...
+ var promptMessage = new XAiMessageDto
+ {
+ Content = prompt,
+ OwnerId = ownerId,
+ Role = XAiChatRole.User,
+ CreatedOn = DateTime.UtcNow,
+ ConversationId = conversationId.Value,
+ ConversationTitle = conversation.Title
+ };
+
+ //
+ // Save Prompt Message ...
+ promptMessage = await dataProvider.AddMessage(
+ item: promptMessage,
+ connectionId: connectionId,
+ conversationId: conversationId.Value,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ // Converts to ChatMessage ...
+ var promptChatMessage = promptMessage
+ .ToChatMessages(additionalContents: []);
+
+ //
+ // Ask Questions From LLM ...
+ var answer = await AskLLMAsync(
+ history: history,
+ prompt: promptChatMessage,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ // Prepare Answer AI Message ...
+ var result = new XAiMessageDto
+ {
+ Content = answer,
+ OwnerId = ownerId,
+ CreatedOn = DateTime.UtcNow,
+ Role = XAiChatRole.Assistant,
+ ConversationId = conversationId.Value,
+ ConversationTitle = conversation.Title
+ };
+ result = await dataProvider.AddMessage(
+ item: result,
+ connectionId: connectionId,
+ conversationId: conversationId.Value,
+ cancellationToken: cancellationToken
+ );
//
return result;
}
///
- /// Ask a Question using Provided Context Chunks (RAG) and Stream Response ...
+ /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
///
///
- ///
+ ///
+ ///
+ ///
+ ///
+ ///
///
///
- public virtual async IAsyncEnumerable AskWithContextAsEnumerable(
+ public virtual async IAsyncEnumerable AskAsEnumerable(
string prompt,
- IEnumerable context,
+ string ownerId,
+ Guid projectId,
+ Guid conversationId,
+ string connectionId = null,
+ IFormFileCollection files = null,
[EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
- if (prompt.IsNullOrEmpty())
+ validationProvider
+ .GroupValidationBuilder()
+ .AddNotEmpty(prompt)
+ .AddNotEmpty(ownerId)
+ .ValidateGroup();
+
+ //
+ // Check Project ...
+ XAiProjectDto project = null;
+ if (projectId.IsDefaultGuid())
{
- XException.InvalidArgs.Throw();
+ //
+ project = await dataProvider.GetDefaultProject(
+ ownerId: ownerId,
+ connectionId: connectionId,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ projectId = project.Id;
+ }
+ else
+ {
+ //
+ project = await dataProvider.GetProject(
+ id: projectId,
+ fillConversations: false,
+ fillConversationMessages: false,
+ cancellationToken: cancellationToken
+ );
+ }
+ if (project.IsNullOrDefault())
+ {
+ XException.NotFound.Throw();
}
//
- using var client = Descriptor.GetClient();
- var history = GetContextHistory(prompt, context);
- var enumerable = client.GetStreamingResponseAsync(
- options: null,
- messages: history,
+ // Check Conversation ...
+ XAiConversationDto conversation = null;
+ if (conversationId.IsDefaultGuid())
+ {
+ //
+ conversation = await dataProvider.GetDefaultConversation(
+ ownerId: ownerId,
+ projectId: projectId,
+ connectionId: connectionId,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ conversationId = conversation.Id;
+ }
+ else
+ {
+ //
+ conversation = await dataProvider.GetConversation(
+ id: conversationId,
+ fillMessages: false,
+ cancellationToken: cancellationToken
+ );
+ }
+ if (conversation.IsNullOrDefault())
+ {
+ XException.NotFound.Throw();
+ }
+
+ //
+ // Reading Messages ...
+ var messages = await dataProvider.LoadMessages(
+ conversationId: conversationId,
cancellationToken: cancellationToken
);
//
+ // TODO: Parse Files ...
+ // for Attached them into Prompt Message ...
+
+ //
+ // Handle Memory ...
+ IList history = await PrepareMemory(
+ project: project,
+ messages: messages,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ // Prepare and Add Prompt Message ...
+ var promptMessage = new XAiMessageDto
+ {
+ Content = prompt,
+ OwnerId = ownerId,
+ Role = XAiChatRole.User,
+ CreatedOn = DateTime.UtcNow,
+ ConversationId = conversationId,
+ };
+ promptMessage = await dataProvider.AddMessage(
+ item: promptMessage,
+ connectionId: connectionId,
+ conversationId: conversationId,
+ cancellationToken: cancellationToken
+ );
+ promptMessage = await dataProvider.Enrich(
+ source: promptMessage,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ // Attach Uploaded Files ...
+ var promptChatMessage = promptMessage
+ .ToChatMessages();
+ history.Add(promptChatMessage);
+
+ //
+ // Ask Questions From LLM ...
+ using var client = Descriptor.GetClient();
+ var enumerable = client.GetStreamingResponseAsync(
+ options: null,
+ messages: history
+ );
+
+ //
+ long sequence = 1;
+ var answer = string.Empty;
await foreach (var res in enumerable)
{
//
+ // Cancellation Token ...
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
//
- yield return res.Text;
+ var resp = new XAiResonseMessage
+ {
+ OwnerId = ownerId,
+ Content = res.Text,
+ Sequence = sequence,
+ Role = XAiChatRole.System,
+ RespondTo = promptMessage.Id,
+ RespondedOn = DateTime.UtcNow,
+ };
+
+ //
+ sequence++;
+ answer += res.Text;
+
+ //
+ yield return resp;
}
- }
- ///
- /// Build Chat History for RAG:
- /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ...
- ///
- ///
- ///
- ///
- protected virtual IList GetContextHistory(
- string prompt,
- IEnumerable context
- )
- {
//
- var introductionPrompt = configuration.GetPrompt();
- var ragPrompt = configuration.GetPrompt(configuration.RAGDescriptor.PromptName);
- if (ragPrompt.IsNullOrEmpty())
+ // Prepare Answer AI Message ...
+ var result = new XAiMessageDto
{
- XException.InvalidConfiguration.Throw();
- }
-
- //
- var contextBlock = BuildContextBlock(context);
- var systemText =
- $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" +
- $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
- $"Context:{Environment.NewLine}{contextBlock}";
-
- //
- List result =
- [
- new ChatMessage(ChatRole.System, systemText),
- new ChatMessage(ChatRole.User, prompt),
- ];
-
- //
- return result;
+ Content = answer,
+ OwnerId = ownerId,
+ Role = XAiChatRole.System,
+ CreatedOn = DateTime.UtcNow,
+ ConversationId = conversationId
+ };
+ result = await dataProvider.AddMessage(
+ item: result,
+ connectionId: connectionId,
+ conversationId: conversationId,
+ cancellationToken: cancellationToken
+ );
}
#endregion
@@ -806,406 +994,6 @@ namespace xAiApi.Providers
}
#endregion
- //
- #region Data Actions ...
- ///
- /// Ask a Question as Prompt and Retrieve Response ...
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public virtual async Task AskAsync(
- string prompt,
- string ownerId,
- Guid? projectId,
- Guid? conversationId,
- string connectionId = null,
- IFormFileCollection files = null,
- XUserClaimsInfoDto userInfo = null,
- CancellationToken cancellationToken = default
- )
- {
- //
- // Validate Args ...
- validationProvider
- .GroupValidationBuilder()
- .AddNotEmpty(prompt)
- .AddNotEmpty(ownerId)
- .ValidateGroup();
-
- //
- // Check Project ...
- XAiProjectDto project = null;
- if (!projectId.HasValue || projectId.Value.IsDefaultGuid())
- {
- //
- project = await dataProvider.GetDefaultProject(
- ownerId: ownerId,
- 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 ...
- XAiConversationDto conversation = null;
- if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid())
- {
- //
- conversation = await dataProvider.GetDefaultConversation(
- ownerId: ownerId,
- 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 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
- {
- Prompt = prompt,
- IncludeUser = true,
- IncludeGlobal = true,
- ProjectId = projectId,
- ConversationId = conversationId
- };
- var context = await ragProvider.RetrieveAsync(
- userInfo: userInfo,
- request: knowledgeRequest,
- cancellationToken: cancellationToken
- );
-
- //
- // Reading Messages ...
- var messages = await dataProvider.LoadMessages(
- conversationId: conversationId.Value,
- cancellationToken: cancellationToken
- );
-
- //
- // Handle Memory ...
- IList history = await PrepareMemory(
- project: project,
- context: context,
- messages: messages,
- cancellationToken: cancellationToken
- );
-
- //
- // Prepare and Add Prompt Message ...
- var promptMessage = new XAiMessageDto
- {
- Content = prompt,
- OwnerId = ownerId,
- Role = XAiChatRole.User,
- CreatedOn = DateTime.UtcNow,
- ConversationId = conversationId.Value,
- ConversationTitle = conversation.Title
- };
-
- //
- // Save Prompt Message ...
- promptMessage = await dataProvider.AddMessage(
- item: promptMessage,
- connectionId: connectionId,
- conversationId: conversationId.Value,
- cancellationToken: cancellationToken
- );
-
- //
- // Converts to ChatMessage ...
- var promptChatMessage = promptMessage
- .ToChatMessages(additionalContents: []);
-
- //
- // Ask Questions From LLM ...
- var answer = await AskLLMAsync(
- history: history,
- prompt: promptChatMessage,
- cancellationToken: cancellationToken
- );
-
- //
- // Prepare Answer AI Message ...
- var result = new XAiMessageDto
- {
- Content = answer,
- OwnerId = ownerId,
- CreatedOn = DateTime.UtcNow,
- Role = XAiChatRole.Assistant,
- ConversationId = conversationId.Value,
- ConversationTitle = conversation.Title
- };
- result = await dataProvider.AddMessage(
- item: result,
- connectionId: connectionId,
- conversationId: conversationId.Value,
- cancellationToken: cancellationToken
- );
-
- //
- return result;
- }
-
- ///
- /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public virtual async IAsyncEnumerable AskAsEnumerable(
- string prompt,
- string ownerId,
- Guid projectId,
- Guid conversationId,
- string connectionId = null,
- IFormFileCollection files = null,
- [EnumeratorCancellation]
- CancellationToken cancellationToken = default
- )
- {
- //
- // Validate Args ...
- validationProvider
- .GroupValidationBuilder()
- .AddNotEmpty(prompt)
- .AddNotEmpty(ownerId)
- .ValidateGroup();
-
- //
- // Check Project ...
- XAiProjectDto project = null;
- if (projectId.IsDefaultGuid())
- {
- //
- project = await dataProvider.GetDefaultProject(
- ownerId: ownerId,
- connectionId: connectionId,
- cancellationToken: cancellationToken
- );
-
- //
- projectId = project.Id;
- }
- else
- {
- //
- project = await dataProvider.GetProject(
- id: projectId,
- fillConversations: false,
- fillConversationMessages: false,
- cancellationToken: cancellationToken
- );
- }
- if (project.IsNullOrDefault())
- {
- XException.NotFound.Throw();
- }
-
- //
- // Check Conversation ...
- XAiConversationDto conversation = null;
- if (conversationId.IsDefaultGuid())
- {
- //
- conversation = await dataProvider.GetDefaultConversation(
- ownerId: ownerId,
- projectId: projectId,
- connectionId: connectionId,
- cancellationToken: cancellationToken
- );
-
- //
- conversationId = conversation.Id;
- }
- else
- {
- //
- conversation = await dataProvider.GetConversation(
- id: conversationId,
- fillMessages: false,
- cancellationToken: cancellationToken
- );
- }
- if (conversation.IsNullOrDefault())
- {
- XException.NotFound.Throw();
- }
-
- //
- // Reading Messages ...
- var messages = await dataProvider.LoadMessages(
- conversationId: conversationId,
- cancellationToken: cancellationToken
- );
-
- //
- // TODO: Parse Files ...
- // for Attached them into Prompt Message ...
-
- //
- // Handle Memory ...
- IList history = await PrepareMemory(
- project: project,
- messages: messages,
- cancellationToken: cancellationToken
- );
-
- //
- // Prepare and Add Prompt Message ...
- var promptMessage = new XAiMessageDto
- {
- Content = prompt,
- OwnerId = ownerId,
- Role = XAiChatRole.User,
- CreatedOn = DateTime.UtcNow,
- ConversationId = conversationId,
- };
- promptMessage = await dataProvider.AddMessage(
- item: promptMessage,
- connectionId: connectionId,
- conversationId: conversationId,
- cancellationToken: cancellationToken
- );
- promptMessage = await dataProvider.Enrich(
- source: promptMessage,
- cancellationToken: cancellationToken
- );
-
- //
- // Attach Uploaded Files ...
- var promptChatMessage = promptMessage
- .ToChatMessages();
- history.Add(promptChatMessage);
-
- //
- // Ask Questions From LLM ...
- using var client = Descriptor.GetClient();
- var enumerable = client.GetStreamingResponseAsync(
- options: null,
- messages: history
- );
-
- //
- long sequence = 1;
- var answer = string.Empty;
- await foreach (var res in enumerable)
- {
- //
- // Cancellation Token ...
- if (cancellationToken.IsCancellationRequested)
- {
- yield break;
- }
-
- //
- var resp = new XAiResonseMessage
- {
- OwnerId = ownerId,
- Content = res.Text,
- Sequence = sequence,
- Role = XAiChatRole.System,
- RespondTo = promptMessage.Id,
- RespondedOn = DateTime.UtcNow,
- };
-
- //
- sequence++;
- answer += res.Text;
-
- //
- yield return resp;
- }
-
- //
- // Prepare Answer AI Message ...
- var result = new XAiMessageDto
- {
- Content = answer,
- OwnerId = ownerId,
- Role = XAiChatRole.System,
- CreatedOn = DateTime.UtcNow,
- ConversationId = conversationId
- };
- result = await dataProvider.AddMessage(
- item: result,
- connectionId: connectionId,
- conversationId: conversationId,
- cancellationToken: cancellationToken
- );
- }
- #endregion
-
///
/// Base Dispose Action ...
///
@@ -1215,6 +1003,87 @@ namespace xAiApi.Providers
//
#region Private ...
+ ///
+ /// Prepare a Message History List for LLM Communication based on Prompt ...
+ ///
+ ///
+ ///
+ ///
+ private IList 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 result =
+ [
+ introductionPrompt,
+ ];
+ if (forcePrompt &&
+ prompt is not null &&
+ !string.IsNullOrWhiteSpace(prompt))
+ {
+ result.Add(promptMessage);
+ }
+
+ //
+ return result;
+ }
+
+ ///
+ /// Prepare a Message History List for LLM Communication based on Prompt ...
+ ///
+ ///
+ ///
+ ///
+ private IList GetHistory(
+ ChatMessage message = null,
+ bool forceMessage = true
+ )
+ {
+ //
+ // Preparing Introduction Prompt ...
+ var introductionPrompt = new ChatMessage(
+ ChatRole.System,
+ configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName)
+ );
+
+ //
+ List result =
+ [
+ introductionPrompt,
+ ];
+ if (forceMessage &&
+ !message.IsNullOrDefault())
+ {
+ result.Add(message);
+ }
+
+ //
+ return result;
+ }
+
///
/// Implementing Memory Strategy here ...
///
diff --git a/Providers/XDefaultAiService.cs b/Providers/XAiService.cs
similarity index 82%
rename from Providers/XDefaultAiService.cs
rename to Providers/XAiService.cs
index 1961cea..2fc8ea7 100644
--- a/Providers/XDefaultAiService.cs
+++ b/Providers/XAiService.cs
@@ -8,12 +8,12 @@ using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers
{
- public class XDefaultAiService : XAIServiceBase, IXDefaultAiService
+ public class XAiService : XAIServiceBase, IXAiService
{
- public XDefaultAiService(
+ public XAiService(
IXAiRAGService ragProvider,
IXAiDataProvider dataProvider,
- ILogger logger,
+ ILogger logger,
XAiApiConfiguration configuration,
XValidationProvider validationProvider,
IXFileContentExtractor fileContentExtractor