Просмотр исходного кода

5406 AI Agents revamp: agent chat history

Aleksandr Trofimov 7 месяцев назад
Родитель
Сommit
9ebe2e2fcd

+ 9 - 3
inc/classes/BxDolAI.php

@@ -70,7 +70,7 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    public static function getAgentInstance(int $iId): NeuronAI\Agent\Agent
+    public static function getAgentInstance(int $iId, array $aParams = []): NeuronAI\Agent\Agent
     {
         if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId]))
             return $GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId];
@@ -92,7 +92,7 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
             throw new Exception($s);
         }
 
-        $o = BxDolAiAgent::make($a);
+        $o = BxDolAiAgent::make($a, $aParams);
 
         if ($a['vector_store_id']) {
             $aVectorStore = BxDolAIQuery::getVectorStoreObject($a['vector_store_id']);
@@ -384,8 +384,14 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
             $this->updateAgentField($aAgent['id'], $a[$sType], $sParams);
         }
 
+        // set additional params
+        $aParams = [];
+        if ('message' == $sType) {
+            $aParams = ['chat_history_subindex' => $mixedParams['sender_profile_id']];
+        }
+
         // call agent
-        $o = self::getAgentInstance($aAgent['id']);
+        $o = self::getAgentInstance($aAgent['id'], $aParams);
         if (!$o)
             return false;
 

+ 27 - 1
inc/classes/BxDolAiAgent.php

@@ -11,7 +11,7 @@ use NeuronAI\RAG\RAG;
 
 class BxDolAiAgent extends RAG
 {
-    public function __construct(protected array $aAgent)
+    public function __construct(protected array $aAgent, protected array $aParams = [])
     {
         parent::__construct();
     }
@@ -58,4 +58,30 @@ class BxDolAiAgent extends RAG
         else
             return new NeuronAI\RAG\VectorStore\MemoryVectorStore();
     }
+
+    protected function chatHistory(): NeuronAI\Chat\History\ChatHistoryInterface
+    {
+        if ($this->aAgent['chat_history_context']) {
+            return new NeuronAI\Chat\History\SQLChatHistory(
+                thread_id: $this->getСhatHistoryThreadId(),
+                pdo: BxDolDb::getInstance()->getLink(),
+                table: 'sys_agents_chat_history',
+                contextWindow: $this->aAgent['chat_history_context']
+            );
+        }
+        else {
+            return new NeuronAI\Chat\History\InMemoryChatHistory(
+                contextWindow: 50000
+            );
+        }
+    }
+
+    protected function getСhatHistoryThreadId(): string
+    {
+        echoDbgLog($this->aParams);
+        $s = $this->aAgent['trigger'] . ':' . $this->aAgent['id'];
+        if (isset($this->aParams['chat_history_subindex']))
+            $s .=  ':' . $this->aParams['chat_history_subindex'];
+        return $s;
+    }
 }

+ 11 - 0
install/sql/system.sql

@@ -7125,6 +7125,7 @@ CREATE TABLE `sys_agents_agents` (
   `prompt_output` text NOT NULL,
   `prompt_tools` text NOT NULL,
   `tools` varchar(255) NOT NULL DEFAULT '',
+  `chat_history_context` int(11) NOT NULL DEFAULT 50000,
   `vector_store_id` int(11) NOT NULL,
   `trigger` enum('alert','scheduler','webhook','manual','agent','message') NOT NULL DEFAULT 'message',
   `alert_unit` varchar(128) NOT NULL DEFAULT '',
@@ -7266,6 +7267,16 @@ CREATE TABLE IF NOT EXISTS `sys_agents_tools` (
   PRIMARY KEY (`id`)
 );
 
+CREATE TABLE IF NOT EXISTS `sys_agents_chat_history` (
+  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
+  `thread_id` VARCHAR(255) NOT NULL,
+  `messages` LONGTEXT NOT NULL,
+  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_thread_id` (`thread_id`)
+);
+
 -- --------------------------------------------------------
 
 --

+ 2 - 0
modules/boonex/english/data/langs/system/en.xml

@@ -2312,6 +2312,8 @@
     <string name="_sys_agents_field_title"><![CDATA[Title]]></string>
     <string name="_sys_agents_tools_field_params"><![CDATA[Parameters]]></string>
     <string name="_sys_agents_tools_field_params_info"><![CDATA[Parameters for configuring the tool, specific to each tool]]></string>
+    <string name="_sys_agents_field_chat_history_context"><![CDATA[Chat history context window]]></string>
+    <string name="_sys_agents_field_chat_history_context_info"><![CDATA[Automatically cut the conversation history based on the size of the context window, set to '0' to disable chat history]]></string>
     <string name="_sys_agents_automators_field_providers"><![CDATA[Providers]]></string>
     <string name="_sys_agents_automators_field_providers_add"><![CDATA[Add]]></string>
     <string name="_sys_agents_automators_field_helpers"><![CDATA[Helpers]]></string>

+ 2 - 0
modules/boonex/russian/data/langs/system/ru.xml

@@ -2287,6 +2287,8 @@
         <string name="_sys_agents_field_title"><![CDATA[Название]]></string>
         <string name="_sys_agents_tools_field_params"><![CDATA[Параметры]]></string>
         <string name="_sys_agents_tools_field_params_info"><![CDATA[Параметры для конфигурации этого инструмента, свои для каждого инструмента]]></string>
+        <string name="_sys_agents_field_chat_history_context"><![CDATA[Размер контекста истории чата]]></string>
+        <string name="_sys_agents_field_chat_history_context_info"><![CDATA[Автоматически обрезать историю диалога на основе размера контекста, 0 - отключить историю чата]]></string>
         <string name="_sys_agents_automators_field_providers"><![CDATA[Поставщики]]></string>
         <string name="_sys_agents_automators_field_providers_add"><![CDATA[Добавить]]></string>
         <string name="_sys_agents_automators_field_helpers"><![CDATA[Помощники]]></string>

+ 10 - 0
studio/template/scripts/BxBaseStudioAgentsAgents.php

@@ -396,6 +396,16 @@ class BxBaseStudioAgentsAgents extends BxDolStudioAgentsAgents
                         'pass' => 'Xss',
                     ],
                 ],
+                'chat_history_context' => [
+                    'type' => 'text',
+                    'name' => 'chat_history_context',
+                    'caption' => _t('_sys_agents_field_chat_history_context'),
+                    'info' => _t('_sys_agents_field_chat_history_context_info'),
+                    'value' => isset($aAgent['chat_history_context']) ? $aAgent['chat_history_context'] : 50000,
+                    'db' => [
+                        'pass' => 'Int',
+                    ],
+                ],
                 'tools' => [
                     'type' => 'custom',
                     'name' => 'tools',