BxDolAiTriggerChat.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. class BxDolAiTriggerChat extends BxDolAiTrigger
  10. {
  11. protected $_sType = 'manual';
  12. protected function appliesChatLimits()
  13. {
  14. return true;
  15. }
  16. /**
  17. * HTTP/SSE only. GET hydrates transcript; POST streams (or falls back to call()).
  18. */
  19. public function handle($mixed = null)
  20. {
  21. $iAgentId = (int)$mixed;
  22. $sMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '';
  23. if ('GET' === $sMethod)
  24. return $this->hydrate($iAgentId);
  25. if ('POST' !== $sMethod)
  26. return echoJson(['code' => 405, 'msg' => _t('_error occured')]);
  27. $aAgent = $this->loadAgent($iAgentId);
  28. if (!$aAgent)
  29. return echoJson(['code' => $iAgentId ? 404 : 400, 'msg' => _t('_sys_agents_agent_not_found')]);
  30. $oAi = $this->getAi();
  31. if (!$oAi)
  32. return echoJson(['code' => 503, 'msg' => _t('_sys_agents_exception')]);
  33. if (!$oAi->canChatDirectly($aAgent))
  34. return echoJson(['code' => 403, 'msg' => _t('_sys_agents_unauthorized')]);
  35. $sJson = file_get_contents('php://input');
  36. $aData = json_decode($sJson, true);
  37. if (json_last_error() !== JSON_ERROR_NONE)
  38. return echoJson(['code' => 400, 'msg' => _t('_sys_agents_json_field_err')]);
  39. $sPrompt = $this->extractPromptFromRequest($aData);
  40. if (!$sPrompt)
  41. return echoJson(['code' => 400, 'msg' => _t('_sys_agents_json_field_err')]);
  42. $aParams = $this->historyParams($aAgent);
  43. if (!$aParams)
  44. return echoJson(['code' => 403, 'msg' => _t('_sys_agents_unauthorized')]);
  45. $aParams['request_user_turns'] = BxDolAiChatLimits::getInstance()->countChatUserTurns($aData['messages'] ?? []);
  46. $sThreadId = !empty($aData['threadId']) ? $aData['threadId'] : null;
  47. if (class_exists('NeuronAI\Chat\Messages\Stream\Adapters\AGUIAdapter')) {
  48. $this->stream($aAgent['id'], $sPrompt, $aParams, $sThreadId);
  49. return;
  50. }
  51. try {
  52. $sReply = $this->call($aAgent, $sPrompt);
  53. } catch (Throwable $o) {
  54. return echoJson(['code' => 500, 'msg' => $o->getMessage(), 'messages' => []]);
  55. }
  56. return echoJson(['code' => 200, 'msg' => $sReply, 'text' => $sReply]);
  57. }
  58. public function extractPromptFromRequest($aData)
  59. {
  60. if (!is_array($aData))
  61. return '';
  62. if (!empty($aData['prompt']) && is_string($aData['prompt']))
  63. return trim($aData['prompt']);
  64. if (empty($aData['messages']) || !is_array($aData['messages']))
  65. return '';
  66. for ($i = count($aData['messages']) - 1; $i >= 0; $i--) {
  67. $aMessage = $aData['messages'][$i];
  68. if (!is_array($aMessage))
  69. continue;
  70. if (($aMessage['role'] ?? '') !== 'user')
  71. continue;
  72. if (isset($aMessage['content']) && is_string($aMessage['content']))
  73. return trim($aMessage['content']);
  74. if (!empty($aMessage['parts']) && is_array($aMessage['parts'])) {
  75. $aText = [];
  76. foreach ($aMessage['parts'] as $aPart) {
  77. if (is_array($aPart) && ($aPart['type'] ?? '') === 'text' && isset($aPart['content']))
  78. $aText[] = $aPart['content'];
  79. }
  80. $s = trim(implode("\n", $aText));
  81. if ($s !== '')
  82. return $s;
  83. }
  84. }
  85. return '';
  86. }
  87. public function stream($iAgentId, $sPrompt, $aParams = [], $sThreadId = null)
  88. {
  89. $oChat = BxDolAiChat::getInstance();
  90. $oLimits = BxDolAiChatLimits::getInstance();
  91. if (!isset($aParams['chat_history_subindex']))
  92. $aParams = array_merge($oChat->resolveChatHistoryParams($iAgentId), $aParams);
  93. // Staging header.inc.php dumps HTML on fatals and warns on null error_get_last().
  94. // Any HTML after SSE is parsed by TanStack as "unterminated trailing data".
  95. @ini_set('display_errors', '0');
  96. @ini_set('zlib.output_compression', '0');
  97. @ini_set('implicit_flush', '1');
  98. if (function_exists('apache_setenv'))
  99. @apache_setenv('no-gzip', '1');
  100. while (ob_get_level())
  101. ob_end_clean();
  102. // UNA BxDolDb::pdoExceptionHandler dumps HTML 503 on uncaught PDOException.
  103. restore_exception_handler();
  104. $oAdapter = new NeuronAI\Chat\Messages\Stream\Adapters\AGUIAdapter($sThreadId);
  105. http_response_code(200);
  106. foreach ($oAdapter->getHeaders() as $sName => $sValue)
  107. header($sName . ': ' . $sValue);
  108. $fEmit = function ($sEvent) {
  109. echo $sEvent;
  110. if (ob_get_level())
  111. ob_flush();
  112. flush();
  113. };
  114. $aAgent = BxDolAiQuery::getAgentObject((int)$iAgentId);
  115. if ($aAgent)
  116. $oChat->setChatContext($aAgent, $aParams);
  117. if ($aAgent && $oLimits->isChatSessionRateLimited($aAgent, $aParams)) {
  118. $this->emitErrorSse($oAdapter, $fEmit, $oLimits->getChatSessionRateLimitError());
  119. error_clear_last();
  120. @ini_set('display_errors', '0');
  121. exit;
  122. }
  123. $iRequestTurns = (int)($aParams['request_user_turns'] ?? 0);
  124. if ($aAgent && $oLimits->isChatTurnLimitReached($aAgent, $oLimits->getChatUserTurnCount((int)$iAgentId, $aParams), $iRequestTurns)) {
  125. $oChat->emitConversationClosed('limit', '', $aAgent, $aParams);
  126. $this->emitLimitSse($oAdapter, $fEmit, $oLimits->getChatLimitMessage($aAgent));
  127. error_clear_last();
  128. @ini_set('display_errors', '0');
  129. exit;
  130. }
  131. $sPrompt = $oLimits->applyChatInputLimit((string)$sPrompt, $aAgent ?: []);
  132. $bStarted = false;
  133. $aSseState = $this->resetActionsSseState();
  134. $o = null;
  135. try {
  136. $o = BxDolAi::getAgentInstance((int)$iAgentId, $aParams);
  137. $oHandler = $o->stream(new NeuronAI\Chat\Messages\UserMessage($sPrompt));
  138. foreach ($oHandler->events($oAdapter) as $sEvent) {
  139. $bStarted = true;
  140. $this->processActionsSseEvent($sEvent, $aSseState, $fEmit);
  141. }
  142. $this->flushActionsSseState($aSseState, $fEmit);
  143. $this->persistAssistantActions($o);
  144. if ($aAgent && $oLimits->isChatTurnLimitReached($aAgent, $oLimits->getChatUserTurnCount((int)$iAgentId, $aParams)))
  145. $oChat->emitConversationClosed('limit', '', $aAgent, $aParams);
  146. } catch (Throwable $oException) {
  147. bx_log('sys_agents', "Stream exception for agent {$iAgentId}: " . $oException->getMessage() . " INPUT:" . $sPrompt);
  148. $this->flushActionsSseState($aSseState, $fEmit);
  149. if (!$bStarted) {
  150. foreach ($oAdapter->start() as $sEvent)
  151. $fEmit($sEvent);
  152. }
  153. $sMsg = $oException->getMessage();
  154. $fEmit('data: ' . json_encode(['type' => 'RUN_ERROR', 'message' => $sMsg !== '' ? $sMsg : _t('_sys_agents_exception')]) . "\n\n");
  155. foreach ($oAdapter->end() as $sEvent)
  156. $fEmit($sEvent);
  157. }
  158. error_clear_last();
  159. @ini_set('display_errors', '0');
  160. exit;
  161. }
  162. protected function hydrate($iAgentId)
  163. {
  164. if (false !== bx_get('offset'))
  165. return echoJson(['code' => 405, 'msg' => _t('_error occured'), 'messages' => [], 'activeRun' => null, 'interrupts' => null]);
  166. $aAgent = $this->loadAgent($iAgentId);
  167. if (!$aAgent)
  168. return echoJson(['code' => (int)$iAgentId ? 404 : 400, 'msg' => _t('_sys_agents_agent_not_found'), 'messages' => [], 'activeRun' => null, 'interrupts' => null]);
  169. $oAi = $this->getAi();
  170. if (!$oAi)
  171. return echoJson(['code' => 503, 'msg' => _t('_sys_agents_exception'), 'messages' => [], 'activeRun' => null, 'interrupts' => null]);
  172. if (!$oAi->canChatDirectly($aAgent))
  173. return echoJson(['code' => 403, 'msg' => _t('_sys_agents_unauthorized'), 'messages' => [], 'activeRun' => null, 'interrupts' => null]);
  174. $aParams = $this->historyParams($aAgent);
  175. if (!$aParams)
  176. return echoJson(['code' => 403, 'msg' => _t('_sys_agents_unauthorized'), 'messages' => [], 'activeRun' => null, 'interrupts' => null]);
  177. try {
  178. $aMessages = BxDolAiChat::getInstance()->getChatHistoryUiMessages($aAgent['id'], $aParams);
  179. } catch (Throwable $o) {
  180. $aMessages = [];
  181. }
  182. if (!is_array($aMessages))
  183. $aMessages = [];
  184. return echoJson([
  185. 'messages' => $aMessages,
  186. 'activeRun' => null,
  187. 'interrupts' => null,
  188. ]);
  189. }
  190. /**
  191. * Member/guest subindex + optional `?context=` (group/org profile id).
  192. * Invalid context is 403 — never fall back to the site-wide thread.
  193. */
  194. protected function historyParams($aAgent)
  195. {
  196. $oChat = BxDolAiChat::getInstance();
  197. $mixedContext = $oChat->resolveChatHistoryContextPid();
  198. if ($mixedContext === false)
  199. return false;
  200. $aParams = $oChat->resolveChatHistoryParams((int)$aAgent['id']);
  201. $aParams['chat_history_context_pid'] = (int)$mixedContext;
  202. return $aParams;
  203. }
  204. protected function loadAgent($iAgentId)
  205. {
  206. $iAgentId = (int)$iAgentId;
  207. if (!$iAgentId)
  208. return false;
  209. $aAgent = BxDolAiQuery::getAgentObject($iAgentId);
  210. if (!$aAgent || empty($aAgent['active']))
  211. return false;
  212. return $aAgent;
  213. }
  214. protected function sseEvent($aPayload)
  215. {
  216. return 'data: ' . json_encode($aPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n";
  217. }
  218. protected function parseSseEvent($sEvent)
  219. {
  220. $s = trim((string)$sEvent);
  221. if (!preg_match('/^data:\s*(.+)$/s', $s, $aM))
  222. return null;
  223. $a = json_decode($aM[1], true);
  224. return is_array($a) ? $a : null;
  225. }
  226. protected function resetActionsSseState()
  227. {
  228. return [
  229. 'mode' => 'undecided',
  230. 'buf' => '',
  231. 'messageId' => '',
  232. 'held' => [],
  233. ];
  234. }
  235. protected function emitHeldActionsSse(&$aState, $fEmit)
  236. {
  237. foreach ($aState['held'] as $sHeld)
  238. $fEmit($sHeld);
  239. $aState['held'] = [];
  240. }
  241. protected function emitParsedActionsSse(&$aState, $fEmit, $aParsed)
  242. {
  243. $sId = $aState['messageId'] !== '' ? $aState['messageId'] : ('msg_' . uniqid());
  244. $fEmit($this->sseEvent([
  245. 'type' => 'TEXT_MESSAGE_START',
  246. 'messageId' => $sId,
  247. 'role' => 'assistant',
  248. ]));
  249. if ($aParsed['content'] !== '') {
  250. $fEmit($this->sseEvent([
  251. 'type' => 'TEXT_MESSAGE_CONTENT',
  252. 'messageId' => $sId,
  253. 'delta' => $aParsed['content'],
  254. ]));
  255. }
  256. $fEmit($this->sseEvent([
  257. 'type' => 'TEXT_MESSAGE_END',
  258. 'messageId' => $sId,
  259. ]));
  260. if (!empty($aParsed['actions'])) {
  261. $fEmit($this->sseEvent([
  262. 'type' => 'CUSTOM',
  263. 'name' => 'chat_actions',
  264. 'value' => [
  265. 'messageId' => $sId,
  266. 'actions' => $aParsed['actions'],
  267. ],
  268. ]));
  269. }
  270. $aState = $this->resetActionsSseState();
  271. }
  272. protected function processActionsSseEvent($sEvent, &$aState, $fEmit)
  273. {
  274. $oUi = BxDolAiChatUi::getInstance();
  275. $aPayload = $this->parseSseEvent($sEvent);
  276. $sType = is_array($aPayload) ? (string)($aPayload['type'] ?? '') : '';
  277. if ($sType === 'TEXT_MESSAGE_START') {
  278. if ($aState['held'] || $aState['buf'] !== '')
  279. $this->flushActionsSseState($aState, $fEmit);
  280. $aState['messageId'] = (string)($aPayload['messageId'] ?? '');
  281. $aState['held'][] = $sEvent;
  282. return;
  283. }
  284. if ($sType === 'TEXT_MESSAGE_CONTENT') {
  285. $sDelta = (string)($aPayload['delta'] ?? '');
  286. $aState['buf'] .= $sDelta;
  287. if ($aState['mode'] === 'text') {
  288. $fEmit($sEvent);
  289. return;
  290. }
  291. if ($aState['mode'] === 'undecided') {
  292. $mixed = $this->actionsStreamLooksLikeJson($aState['buf']);
  293. if ($mixed === false) {
  294. $aState['mode'] = 'text';
  295. $this->emitHeldActionsSse($aState, $fEmit);
  296. $fEmit($sEvent);
  297. return;
  298. }
  299. if ($mixed === true)
  300. $aState['mode'] = 'json';
  301. }
  302. $aState['held'][] = $sEvent;
  303. return;
  304. }
  305. if ($sType === 'TEXT_MESSAGE_END') {
  306. $aParsed = $oUi->parseAssistantChatPayload($aState['buf']);
  307. if ($aParsed && ($aState['mode'] === 'json' || $aState['mode'] === 'undecided')) {
  308. $this->emitParsedActionsSse($aState, $fEmit, $aParsed);
  309. return;
  310. }
  311. $this->emitHeldActionsSse($aState, $fEmit);
  312. $fEmit($sEvent);
  313. $aState = $this->resetActionsSseState();
  314. return;
  315. }
  316. if ($sType === 'RUN_ERROR' || $sType === 'RUN_FINISHED') {
  317. $this->flushActionsSseState($aState, $fEmit);
  318. $fEmit($sEvent);
  319. return;
  320. }
  321. if ($aState['mode'] === 'json' || $aState['held'])
  322. $this->flushActionsSseState($aState, $fEmit);
  323. $fEmit($sEvent);
  324. }
  325. protected function actionsStreamLooksLikeJson($sBuf)
  326. {
  327. $s = ltrim((string)$sBuf);
  328. if ($s === '')
  329. return null;
  330. $sFirst = $s[0];
  331. if ($sFirst === '{' || $sFirst === '`')
  332. return true;
  333. return false;
  334. }
  335. protected function flushActionsSseState(&$aState, $fEmit)
  336. {
  337. $oUi = BxDolAiChatUi::getInstance();
  338. if ($aState['buf'] === '' && !$aState['held'])
  339. return;
  340. $aParsed = $oUi->parseAssistantChatPayload($aState['buf']);
  341. if ($aParsed && $aState['mode'] !== 'text') {
  342. $this->emitParsedActionsSse($aState, $fEmit, $aParsed);
  343. return;
  344. }
  345. $this->emitHeldActionsSse($aState, $fEmit);
  346. $aState = $this->resetActionsSseState();
  347. }
  348. protected function persistAssistantActions($oAgent)
  349. {
  350. $oUi = BxDolAiChatUi::getInstance();
  351. if (!is_object($oAgent) || !method_exists($oAgent, 'getChatHistory'))
  352. return;
  353. $oHistory = $oAgent->getChatHistory();
  354. if (!($oHistory instanceof BxDolAiChatHistory) || !method_exists($oHistory, 'persistMessages'))
  355. return;
  356. $aMessages = $oHistory->getMessages();
  357. for ($i = count($aMessages) - 1; $i >= 0; $i--) {
  358. $oMessage = $aMessages[$i];
  359. if (
  360. $oMessage instanceof NeuronAI\Chat\Messages\ToolCallMessage
  361. || $oMessage instanceof NeuronAI\Chat\Messages\ToolResultMessage
  362. ) {
  363. continue;
  364. }
  365. $sRole = $oMessage->getRole();
  366. if ($sRole === 'model')
  367. $sRole = 'assistant';
  368. if ($sRole !== 'assistant')
  369. return;
  370. $aParsed = $oUi->parseAssistantChatPayload((string)$oMessage->getContent());
  371. if (!$aParsed)
  372. return;
  373. $oMessage->setContents($aParsed['content']);
  374. $oMessage->addMetadata('actions', $aParsed['actions']);
  375. $oHistory->persistMessages();
  376. return;
  377. }
  378. }
  379. /**
  380. * SSE assistant reply without calling the model. Used when max_turns is hit.
  381. */
  382. protected function emitLimitSse($oAdapter, $fEmit, $sMessage)
  383. {
  384. foreach ($oAdapter->start() as $sEvent)
  385. $fEmit($sEvent);
  386. $oChunk = new NeuronAI\Chat\Messages\Stream\Chunks\TextChunk('msg_limit', (string)$sMessage);
  387. foreach ($oAdapter->transform($oChunk) as $sEvent)
  388. $fEmit($sEvent);
  389. foreach ($oAdapter->end() as $sEvent)
  390. $fEmit($sEvent);
  391. }
  392. /**
  393. * SSE error without an assistant bubble. Used when a new session is rate-limited.
  394. */
  395. protected function emitErrorSse($oAdapter, $fEmit, $sMessage)
  396. {
  397. foreach ($oAdapter->start() as $sEvent)
  398. $fEmit($sEvent);
  399. $sMsg = trim((string)$sMessage);
  400. $fEmit('data: ' . json_encode([
  401. 'type' => 'RUN_ERROR',
  402. 'message' => $sMsg !== '' ? $sMsg : _t('_sys_agents_exception'),
  403. ]) . "\n\n");
  404. foreach ($oAdapter->end() as $sEvent)
  405. $fEmit($sEvent);
  406. }
  407. }
  408. /** @} */