BxDolAiAgent.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. // what the agent did (comments, content, SQL) — shown as activity history
  30. $this->observe(new BxDolAiActivityObserver($this->aAgent, $this->aParams));
  31. }
  32. protected function provider(): NeuronAI\Providers\AIProviderInterface
  33. {
  34. $aOverrides = [];
  35. if ((int)($this->aAgent['max_tokens'] ?? 0) > 0)
  36. $aOverrides['max_tokens'] = (int)$this->aAgent['max_tokens'];
  37. return BxDolAIModelFactory::getModelInstance((int)$this->aAgent['model_id'], $aOverrides);
  38. }
  39. protected function instructions(): string
  40. {
  41. $aPromptSystem = !empty($this->aAgent['prompt_system']) ? [$this->aAgent['prompt_system']] : [];
  42. $aPromptSteps = !empty($this->aAgent['prompt_steps']) ? [$this->aAgent['prompt_steps']] : [];
  43. $aPromptTools = !empty($this->aAgent['prompt_tools']) ? [$this->aAgent['prompt_tools']] : [];
  44. $aPromptOutput = !empty($this->aAgent['prompt_output']) ? [$this->aAgent['prompt_output']] : [];
  45. $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.";
  46. if ('alert' == $this->aAgent['trigger']) {
  47. if (!$this->aAgent['async']) {
  48. $aPromptTools[] = "Return array only, modified version of 'extra' array. Modifyable keys: " . $this->getAlertTriggerModifyableKeys() . ".";
  49. }
  50. $sDesc = trim(BxDolAiQuery::getAlertDesc($this->aAgent['alert']));
  51. if ('.' != mb_substr($sDesc, -1))
  52. $sDesc .= '.';
  53. $aPromptSystem[] = $sDesc;
  54. }
  55. $oPrompt = new NeuronAI\Agent\SystemPrompt(
  56. background: $aPromptSystem,
  57. steps: $aPromptSteps,
  58. output: $aPromptOutput,
  59. toolsUsage: $aPromptTools
  60. );
  61. return (string) $oPrompt;
  62. }
  63. /**
  64. * @return \NeuronAI\Tools\ToolInterface[]
  65. */
  66. protected function tools(): array
  67. {
  68. if ($this->aAgent['tools']) {
  69. $aTools = explode(',', $this->aAgent['tools']);
  70. $aToolInstances = [];
  71. foreach ($aTools as $sToolId) {
  72. $iToolId = (int)trim($sToolId);
  73. if ($iToolId <= 0)
  74. continue;
  75. $aToolInstances[] = BxDolAIToolFactory::getToolInstance($iToolId);
  76. }
  77. return $aToolInstances;
  78. }
  79. else {
  80. return [];
  81. }
  82. }
  83. protected function vectorStore(): NeuronAI\RAG\VectorStore\VectorStoreInterface
  84. {
  85. if ($this->aAgent['vector_store_id'])
  86. return BxDolAIVectorStoreFactory::getVectorStoreInstance($this->aAgent['vector_store_id']);
  87. else
  88. return new NeuronAI\RAG\VectorStore\MemoryVectorStore();
  89. }
  90. protected function chatHistory(): NeuronAI\Chat\History\ChatHistoryInterface
  91. {
  92. if ($this->aAgent['chat_history_context']) {
  93. return new BxDolAiChatHistory(
  94. thread_id: $this->getChatHistoryThreadId(),
  95. pdo: BxDolDb::getInstance()->getLink(),
  96. table: 'sys_agents_chat_history',
  97. contextWindow: $this->aAgent['chat_history_context']
  98. );
  99. }
  100. else {
  101. return new NeuronAI\Chat\History\InMemoryChatHistory(
  102. contextWindow: 50000
  103. );
  104. }
  105. }
  106. /**
  107. * Turn tool exceptions into a tool result so chat history stays a valid sequence.
  108. *
  109. * @return callable|null fn(\Throwable $e, \NeuronAI\Tools\ToolInterface $tool): string
  110. */
  111. protected function resolveToolErrorHandler(): ?callable
  112. {
  113. return function (\Throwable $e, NeuronAI\Tools\ToolInterface $tool): string {
  114. return 'Tool "' . $tool->getName() . '" failed: ' . $e->getMessage();
  115. };
  116. }
  117. protected function getChatHistoryThreadId(): string
  118. {
  119. return BxDolAiChat::threadId($this->aAgent, $this->aParams);
  120. }
  121. protected function getAlertTriggerModifyableKeys(): string
  122. {
  123. if ('alert' != $this->aAgent['trigger'])
  124. return 'none';
  125. $aAlert = BxDolAiQuery::getAlert($this->aAgent['alert']);
  126. if (!$aAlert)
  127. return 'none';
  128. $aKeys = json_decode($aAlert['extra_refs']);
  129. if (!$aKeys)
  130. return 'none';
  131. return implode(',', $aKeys);
  132. }
  133. }