BxDolAiAgent.php 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. use NeuronAI\RAG\RAG;
  10. use NeuronAI\Observability\InspectorObserver;
  11. use NeuronAI\Observability\LogObserver;
  12. class BxDolAiAgent extends RAG
  13. {
  14. public function __construct(protected array $aAgent, protected array $aParams = [])
  15. {
  16. parent::__construct();
  17. $sKey = getParam('sys_agents_inspector_key');
  18. if ($sKey) {
  19. $logger = InspectorObserver::instance(
  20. key: $sKey,
  21. autoFlush: true,
  22. );
  23. $this->observe($logger);
  24. }
  25. else {
  26. $logger = new BxDolLoggerDb('sys_agents_' . $this->aAgent['id']);
  27. $this->observe(new LogObserver($logger));
  28. }
  29. }
  30. protected function provider(): NeuronAI\Providers\AIProviderInterface
  31. {
  32. $aOverrides = [];
  33. if ((int)($this->aAgent['max_tokens'] ?? 0) > 0)
  34. $aOverrides['max_tokens'] = (int)$this->aAgent['max_tokens'];
  35. return BxDolAIModelFactory::getModelInstance((int)$this->aAgent['model_id'], $aOverrides);
  36. }
  37. protected function instructions(): string
  38. {
  39. $aPromptSystem = !empty($this->aAgent['prompt_system']) ? [$this->aAgent['prompt_system']] : [];
  40. $aPromptSteps = !empty($this->aAgent['prompt_steps']) ? [$this->aAgent['prompt_steps']] : [];
  41. $aPromptTools = !empty($this->aAgent['prompt_tools']) ? [$this->aAgent['prompt_tools']] : [];
  42. $aPromptOutput = !empty($this->aAgent['prompt_output']) ? [$this->aAgent['prompt_output']] : [];
  43. $aPromptTools[] = "Always use agent profile id = {$this->aAgent['profile_id']} as author ('profile_id' or 'author_profile_id' tool parameter), unless explicitly specified in the user instructions, no other variants strictly.";
  44. if ('alert' == $this->aAgent['trigger']) {
  45. if (!$this->aAgent['async']) {
  46. $aPromptTools[] = "Return array only, modified version of 'extra' array. Modifyable keys: " . $this->getAlertTriggerModifyableKeys() . ".";
  47. }
  48. $sDesc = trim(BxDolAiQuery::getAlertDesc($this->aAgent['alert']));
  49. if ('.' != mb_substr($sDesc, -1))
  50. $sDesc .= '.';
  51. $aPromptSystem[] = $sDesc;
  52. }
  53. $oPrompt = new NeuronAI\Agent\SystemPrompt(
  54. background: $aPromptSystem,
  55. steps: $aPromptSteps,
  56. output: $aPromptOutput,
  57. toolsUsage: $aPromptTools
  58. );
  59. return (string) $oPrompt;
  60. }
  61. /**
  62. * @return \NeuronAI\Tools\ToolInterface[]
  63. */
  64. protected function tools(): array
  65. {
  66. if ($this->aAgent['tools']) {
  67. $aTools = explode(',', $this->aAgent['tools']);
  68. $aToolInstances = [];
  69. foreach ($aTools as $sToolId) {
  70. $iToolId = (int)trim($sToolId);
  71. if ($iToolId <= 0)
  72. continue;
  73. $aToolInstances[] = BxDolAIToolFactory::getToolInstance($iToolId);
  74. }
  75. return $aToolInstances;
  76. }
  77. else {
  78. return [];
  79. }
  80. }
  81. protected function vectorStore(): NeuronAI\RAG\VectorStore\VectorStoreInterface
  82. {
  83. if ($this->aAgent['vector_store_id'])
  84. return BxDolAIVectorStoreFactory::getVectorStoreInstance($this->aAgent['vector_store_id']);
  85. else
  86. return new NeuronAI\RAG\VectorStore\MemoryVectorStore();
  87. }
  88. protected function chatHistory(): NeuronAI\Chat\History\ChatHistoryInterface
  89. {
  90. if ($this->aAgent['chat_history_context']) {
  91. return new BxDolAiChatHistory(
  92. thread_id: $this->getСhatHistoryThreadId(),
  93. pdo: BxDolDb::getInstance()->getLink(),
  94. table: 'sys_agents_chat_history',
  95. contextWindow: $this->aAgent['chat_history_context']
  96. );
  97. }
  98. else {
  99. return new NeuronAI\Chat\History\InMemoryChatHistory(
  100. contextWindow: 50000
  101. );
  102. }
  103. }
  104. /**
  105. * Turn tool exceptions into a tool result so chat history stays a valid sequence.
  106. *
  107. * @return callable|null fn(\Throwable $e, \NeuronAI\Tools\ToolInterface $tool): string
  108. */
  109. protected function resolveToolErrorHandler(): ?callable
  110. {
  111. return function (\Throwable $e, NeuronAI\Tools\ToolInterface $tool): string {
  112. return 'Tool "' . $tool->getName() . '" failed: ' . $e->getMessage();
  113. };
  114. }
  115. protected function getСhatHistoryThreadId(): string
  116. {
  117. return BxDolAiChat::threadId($this->aAgent, $this->aParams);
  118. }
  119. protected function getAlertTriggerModifyableKeys(): string
  120. {
  121. if ('alert' != $this->aAgent['trigger'])
  122. return 'none';
  123. $aAlert = BxDolAiQuery::getAlert($this->aAgent['alert']);
  124. if (!$aAlert)
  125. return 'none';
  126. $aKeys = json_decode($aAlert['extra_refs']);
  127. if (!$aKeys)
  128. return 'none';
  129. return implode(',', $aKeys);
  130. }
  131. }