BxAiProxyCompletion.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 AIProxy AI Proxy
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. class BxAiProxyException extends Exception
  12. {
  13. public function __construct(protected int $iHttpCode, string $sMessage)
  14. {
  15. parent::__construct($sMessage);
  16. }
  17. public function httpCode(): int
  18. {
  19. return $this->iHttpCode;
  20. }
  21. }
  22. class BxAiProxyCompletion
  23. {
  24. /**
  25. * Operator instructions. Placed ahead of the system prompt from the request.
  26. */
  27. public function __construct(protected string $sPrompt = '')
  28. {
  29. $this->sPrompt = trim($sPrompt);
  30. }
  31. /**
  32. * Studio model id for this turn. The request body model is ignored.
  33. */
  34. public function providerId(array $aBody, int $iConfiguredId): int
  35. {
  36. if ($iConfiguredId <= 0)
  37. throw new BxAiProxyException(503, 'The proxy model is not available');
  38. return $iConfiguredId;
  39. }
  40. /**
  41. * @param callable(int): NeuronAI\Providers\AIProviderInterface $fFactory
  42. * @param callable(string): void|null $fEmit
  43. */
  44. public function run(array $aBody, int $iConfiguredId, callable $fFactory, ?callable $fEmit = null): ?string
  45. {
  46. [$oProvider, $aMessages] = $this->prepare($aBody, $iConfiguredId, $fFactory);
  47. $sId = 'chatcmpl-' . bin2hex(random_bytes(8));
  48. if (!empty($aBody['stream'])) {
  49. $this->streamTo($oProvider, $aMessages, $sId, $fEmit ?? static function (string $sEvent) {
  50. });
  51. return null;
  52. }
  53. try {
  54. $oMessage = $oProvider->chat(...$aMessages);
  55. }
  56. catch (BxAiProxyException $oException) {
  57. throw $oException;
  58. }
  59. catch (Throwable $oException) {
  60. $this->logProvider($oException);
  61. throw new BxAiProxyException(503, 'The proxy model is not available');
  62. }
  63. if (!$oMessage instanceof NeuronAI\Chat\Messages\Message)
  64. throw new BxAiProxyException(503, 'The proxy model is not available');
  65. return json_encode($this->completionArray($sId, $oMessage), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  66. }
  67. /**
  68. * @param callable(int): NeuronAI\Providers\AIProviderInterface $fFactory
  69. * @return array{0: NeuronAI\Providers\AIProviderInterface, 1: list<NeuronAI\Chat\Messages\Message>}
  70. */
  71. protected function prepare(array $aBody, int $iConfiguredId, callable $fFactory): array
  72. {
  73. $iId = $this->providerId($aBody, $iConfiguredId);
  74. try {
  75. $oProvider = $fFactory($iId);
  76. }
  77. catch (BxAiProxyException $oException) {
  78. throw $oException;
  79. }
  80. catch (Throwable $oException) {
  81. $this->logProvider($oException);
  82. throw new BxAiProxyException(503, 'The proxy model is not available');
  83. }
  84. if (!$oProvider instanceof NeuronAI\Providers\AIProviderInterface)
  85. throw new BxAiProxyException(503, 'The proxy model is not available');
  86. $aMapped = $this->mapBody($aBody);
  87. if ($aMapped['system'] !== '')
  88. $oProvider->systemPrompt($aMapped['system']);
  89. if ($aMapped['tools'] !== [])
  90. $oProvider->setTools($aMapped['tools']);
  91. if ($aMapped['messages'] === [])
  92. throw new BxAiProxyException(400, 'Bad request');
  93. return [$oProvider, $aMapped['messages']];
  94. }
  95. /**
  96. * @return array{system: string, messages: list<NeuronAI\Chat\Messages\Message>, tools: list<NeuronAI\Tools\Tool>}
  97. */
  98. protected function mapBody(array $aBody): array
  99. {
  100. if (!isset($aBody['messages']) || !is_array($aBody['messages']))
  101. throw new BxAiProxyException(400, 'Bad request');
  102. $aSystem = [];
  103. $aMessages = [];
  104. $aCallNames = [];
  105. foreach ($aBody['messages'] as $aMessage) {
  106. if (!is_array($aMessage))
  107. continue;
  108. $sRole = (string)($aMessage['role'] ?? '');
  109. if ($sRole === 'system' || $sRole === 'developer') {
  110. $sText = $this->textOf($aMessage['content'] ?? '');
  111. if ($sText !== '')
  112. $aSystem[] = $sText;
  113. continue;
  114. }
  115. if ($sRole === 'tool') {
  116. $sCallId = (string)($aMessage['tool_call_id'] ?? '');
  117. $sName = (string)($aMessage['name'] ?? ($aCallNames[$sCallId] ?? 'tool'));
  118. if ($sName === '')
  119. $sName = 'tool';
  120. $oTool = NeuronAI\Tools\Tool::make($sName, '');
  121. if ($sCallId !== '')
  122. $oTool->setCallId($sCallId);
  123. $oTool->setResult($this->textOf($aMessage['content'] ?? ''));
  124. $aMessages[] = new NeuronAI\Chat\Messages\ToolResultMessage([$oTool]);
  125. continue;
  126. }
  127. if ($sRole === 'assistant' && !empty($aMessage['tool_calls']) && is_array($aMessage['tool_calls'])) {
  128. $aCalls = [];
  129. foreach ($aMessage['tool_calls'] as $aCall) {
  130. if (!is_array($aCall))
  131. continue;
  132. $oTool = $this->callTool($aCall);
  133. $sCallId = (string)($oTool->getCallId() ?? '');
  134. if ($sCallId !== '')
  135. $aCallNames[$sCallId] = $oTool->getName();
  136. $aCalls[] = $oTool;
  137. }
  138. if ($aCalls === [])
  139. continue;
  140. $aMessages[] = new NeuronAI\Chat\Messages\ToolCallMessage($this->contentBlocks($aMessage['content'] ?? null), $aCalls);
  141. continue;
  142. }
  143. if ($sRole === 'assistant') {
  144. $aMessages[] = new NeuronAI\Chat\Messages\AssistantMessage($this->contentBlocks($aMessage['content'] ?? ''));
  145. continue;
  146. }
  147. if ($sRole === 'user')
  148. $aMessages[] = new NeuronAI\Chat\Messages\UserMessage($this->contentBlocks($aMessage['content'] ?? ''));
  149. }
  150. return [
  151. 'system' => $this->systemPrompt($aSystem),
  152. 'messages' => $aMessages,
  153. 'tools' => $this->definedTools($aBody),
  154. ];
  155. }
  156. /**
  157. * Operator text is first so it outranks the system prompt sent by the client.
  158. *
  159. * @param list<string> $aSystem
  160. */
  161. protected function systemPrompt(array $aSystem): string
  162. {
  163. if ($this->sPrompt !== '')
  164. array_unshift($aSystem, $this->sPrompt);
  165. return implode("\n\n", $aSystem);
  166. }
  167. /**
  168. * @return list<NeuronAI\Tools\Tool>
  169. */
  170. protected function definedTools(array $aBody): array
  171. {
  172. if (empty($aBody['tools']) || !is_array($aBody['tools']))
  173. return [];
  174. $aTools = [];
  175. foreach ($aBody['tools'] as $aTool) {
  176. if (!is_array($aTool))
  177. continue;
  178. $aFunction = isset($aTool['function']) && is_array($aTool['function']) ? $aTool['function'] : $aTool;
  179. $sName = (string)($aFunction['name'] ?? '');
  180. if ($sName === '')
  181. continue;
  182. $aParameters = isset($aFunction['parameters']) && is_array($aFunction['parameters']) ? $aFunction['parameters'] : [];
  183. $aTools[] = $this->stubTool($sName, (string)($aFunction['description'] ?? ''), $aParameters);
  184. }
  185. return $aTools;
  186. }
  187. protected function stubTool(string $sName, string $sDescription, array $aParameters): NeuronAI\Tools\Tool
  188. {
  189. $oTool = NeuronAI\Tools\Tool::make($sName, $sDescription);
  190. foreach ($this->schemaProperties($aParameters) as $oProperty)
  191. $oTool->addProperty($oProperty);
  192. return $oTool;
  193. }
  194. /**
  195. * @return list<NeuronAI\Tools\ToolPropertyInterface>
  196. */
  197. protected function schemaProperties(array $aSchema): array
  198. {
  199. $aProperties = isset($aSchema['properties']) && is_array($aSchema['properties']) ? $aSchema['properties'] : [];
  200. $aRequired = isset($aSchema['required']) && is_array($aSchema['required']) ? $aSchema['required'] : [];
  201. $aBuilt = [];
  202. foreach ($aProperties as $sProp => $aProperty) {
  203. if (!is_string($sProp) || !is_array($aProperty))
  204. continue;
  205. $aBuilt[] = $this->schemaProperty($sProp, $aProperty, in_array($sProp, $aRequired, true));
  206. }
  207. return $aBuilt;
  208. }
  209. protected function schemaProperty(string $sName, array $aSchema, bool $bRequired): NeuronAI\Tools\ToolPropertyInterface
  210. {
  211. $sType = $aSchema['type'] ?? 'string';
  212. try {
  213. $oType = NeuronAI\Tools\PropertyType::fromSchema(is_array($sType) ? $sType : (string)$sType);
  214. }
  215. catch (Throwable $oException) {
  216. $oType = NeuronAI\Tools\PropertyType::STRING;
  217. }
  218. $sDescription = isset($aSchema['description']) ? (string)$aSchema['description'] : null;
  219. if ($oType === NeuronAI\Tools\PropertyType::ARRAY)
  220. return $this->arrayProperty($sName, $aSchema, $bRequired, $sDescription);
  221. if ($oType === NeuronAI\Tools\PropertyType::OBJECT)
  222. return $this->objectProperty($sName, $aSchema, $bRequired, $sDescription);
  223. $aEnum = isset($aSchema['enum']) && is_array($aSchema['enum']) ? array_values($aSchema['enum']) : [];
  224. return new NeuronAI\Tools\ToolProperty($sName, $oType, $sDescription, $bRequired, $aEnum);
  225. }
  226. protected function arrayProperty(string $sName, array $aSchema, bool $bRequired, ?string $sDescription): NeuronAI\Tools\ArrayProperty
  227. {
  228. $oItems = null;
  229. if (isset($aSchema['items']) && is_array($aSchema['items']) && !array_is_list($aSchema['items']))
  230. $oItems = $this->schemaProperty($sName . '_item', $aSchema['items'], false);
  231. $iMin = isset($aSchema['minItems']) && is_int($aSchema['minItems']) && $aSchema['minItems'] >= 0 ? $aSchema['minItems'] : null;
  232. $iMax = isset($aSchema['maxItems']) && is_int($aSchema['maxItems']) && $aSchema['maxItems'] >= 0 ? $aSchema['maxItems'] : null;
  233. if ($iMin !== null && $iMax !== null && $iMin > $iMax) {
  234. $iMin = null;
  235. $iMax = null;
  236. }
  237. return new NeuronAI\Tools\ArrayProperty($sName, $sDescription, $bRequired, $oItems, $iMin, $iMax);
  238. }
  239. protected function objectProperty(string $sName, array $aSchema, bool $bRequired, ?string $sDescription): NeuronAI\Tools\ObjectProperty
  240. {
  241. return new NeuronAI\Tools\ObjectProperty($sName, $sDescription, $bRequired, null, $this->schemaProperties($aSchema));
  242. }
  243. protected function callTool(array $aCall): NeuronAI\Tools\Tool
  244. {
  245. $aFunction = isset($aCall['function']) && is_array($aCall['function']) ? $aCall['function'] : [];
  246. $sName = (string)($aFunction['name'] ?? 'tool');
  247. if ($sName === '')
  248. $sName = 'tool';
  249. $oTool = NeuronAI\Tools\Tool::make($sName, '');
  250. $sId = (string)($aCall['id'] ?? '');
  251. if ($sId !== '')
  252. $oTool->setCallId($sId);
  253. $mixedArgs = $aFunction['arguments'] ?? [];
  254. if (is_string($mixedArgs)) {
  255. $mixedDecoded = json_decode($mixedArgs, true);
  256. $mixedArgs = is_array($mixedDecoded) ? $mixedDecoded : [];
  257. }
  258. elseif (!is_array($mixedArgs))
  259. $mixedArgs = [];
  260. $oTool->setInputs($mixedArgs);
  261. return $oTool;
  262. }
  263. protected function contentBlocks(mixed $mixed): string|array|null
  264. {
  265. if (is_string($mixed) || $mixed === null)
  266. return $mixed;
  267. if (!is_array($mixed) || $mixed === [])
  268. return '';
  269. if (!array_is_list($mixed))
  270. $mixed = [$mixed];
  271. $aBlocks = [];
  272. foreach ($mixed as $aBlock) {
  273. if (!is_array($aBlock))
  274. continue;
  275. $oBlock = $this->contentBlock($aBlock);
  276. if ($oBlock)
  277. $aBlocks[] = $oBlock;
  278. }
  279. return $aBlocks === [] ? '' : $aBlocks;
  280. }
  281. protected function contentBlock(array $aBlock): ?NeuronAI\Chat\Messages\ContentBlocks\ContentBlockInterface
  282. {
  283. $sType = (string)($aBlock['type'] ?? '');
  284. if ($sType === 'text' || ($sType === '' && isset($aBlock['text'])))
  285. return new NeuronAI\Chat\Messages\ContentBlocks\TextContent((string)($aBlock['text'] ?? ''));
  286. if ($sType !== 'image_url')
  287. return null;
  288. $sUrl = '';
  289. if (isset($aBlock['image_url']) && is_array($aBlock['image_url']))
  290. $sUrl = (string)($aBlock['image_url']['url'] ?? '');
  291. elseif (isset($aBlock['image_url']))
  292. $sUrl = (string)$aBlock['image_url'];
  293. if ($sUrl === '')
  294. return null;
  295. if (preg_match('#^data:([^;]+);base64,(.+)$#s', $sUrl, $aMatch))
  296. return new NeuronAI\Chat\Messages\ContentBlocks\ImageContent($aMatch[2], NeuronAI\Chat\Enums\SourceType::BASE64, $aMatch[1]);
  297. return new NeuronAI\Chat\Messages\ContentBlocks\ImageContent($sUrl, NeuronAI\Chat\Enums\SourceType::URL);
  298. }
  299. protected function textOf(mixed $mixed): string
  300. {
  301. if (is_string($mixed))
  302. return $mixed;
  303. if (!is_array($mixed))
  304. return '';
  305. if (!array_is_list($mixed))
  306. $mixed = [$mixed];
  307. $aParts = [];
  308. foreach ($mixed as $aBlock) {
  309. if (is_string($aBlock))
  310. $aParts[] = $aBlock;
  311. elseif (is_array($aBlock))
  312. $aParts[] = (string)($aBlock['text'] ?? '');
  313. }
  314. return implode('', $aParts);
  315. }
  316. /**
  317. * @param list<NeuronAI\Chat\Messages\Message> $aMessages
  318. */
  319. protected function streamTo(NeuronAI\Providers\AIProviderInterface $oProvider, array $aMessages, string $sId, callable $fEmit): void
  320. {
  321. $bText = false;
  322. try {
  323. $oGen = $oProvider->stream(...$aMessages);
  324. foreach ($oGen as $oChunk) {
  325. if ($oChunk instanceof NeuronAI\Chat\Messages\Stream\Chunks\TextChunk && $oChunk->content !== '') {
  326. $bText = true;
  327. $fEmit($this->contentDelta($sId, $oChunk->content));
  328. }
  329. }
  330. $oMessage = $oGen->getReturn();
  331. }
  332. catch (BxAiProxyException $oException) {
  333. throw $oException;
  334. }
  335. catch (Throwable $oException) {
  336. $this->logProvider($oException);
  337. throw new BxAiProxyException(503, 'The proxy model is not available');
  338. }
  339. if (!$oMessage instanceof NeuronAI\Chat\Messages\Message)
  340. throw new BxAiProxyException(503, 'The proxy model is not available');
  341. if ($oMessage instanceof NeuronAI\Chat\Messages\ToolCallMessage) {
  342. $this->emitToolCalls($sId, $oMessage, $fEmit);
  343. }
  344. else {
  345. if (!$bText) {
  346. $sContent = (string)$oMessage->getContent();
  347. if ($sContent !== '')
  348. $fEmit($this->contentDelta($sId, $sContent));
  349. }
  350. $fEmit($this->sse([
  351. 'id' => $sId,
  352. 'object' => 'chat.completion.chunk',
  353. 'choices' => [[
  354. 'index' => 0,
  355. 'delta' => new stdClass(),
  356. 'finish_reason' => 'stop',
  357. ]],
  358. ]));
  359. }
  360. $fEmit("data: [DONE]\n\n");
  361. }
  362. protected function emitToolCalls(string $sId, NeuronAI\Chat\Messages\ToolCallMessage $oMessage, callable $fEmit): void
  363. {
  364. $iIndex = 0;
  365. foreach ($oMessage->getTools() as $oTool) {
  366. $sCallId = (string)($oTool->getCallId() ?? ('call_' . $iIndex));
  367. $aInputs = $oTool->getInputs();
  368. $sArgs = json_encode($aInputs === [] ? new stdClass() : $aInputs, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  369. $fEmit($this->sse([
  370. 'id' => $sId,
  371. 'object' => 'chat.completion.chunk',
  372. 'choices' => [[
  373. 'index' => 0,
  374. 'delta' => [
  375. 'tool_calls' => [[
  376. 'index' => $iIndex,
  377. 'id' => $sCallId,
  378. 'type' => 'function',
  379. 'function' => [
  380. 'name' => $oTool->getName(),
  381. 'arguments' => '',
  382. ],
  383. ]],
  384. ],
  385. 'finish_reason' => null,
  386. ]],
  387. ]));
  388. $fEmit($this->sse([
  389. 'id' => $sId,
  390. 'object' => 'chat.completion.chunk',
  391. 'choices' => [[
  392. 'index' => 0,
  393. 'delta' => [
  394. 'tool_calls' => [[
  395. 'index' => $iIndex,
  396. 'function' => [
  397. 'arguments' => $sArgs,
  398. ],
  399. ]],
  400. ],
  401. 'finish_reason' => null,
  402. ]],
  403. ]));
  404. $iIndex++;
  405. }
  406. $fEmit($this->sse([
  407. 'id' => $sId,
  408. 'object' => 'chat.completion.chunk',
  409. 'choices' => [[
  410. 'index' => 0,
  411. 'delta' => new stdClass(),
  412. 'finish_reason' => 'tool_calls',
  413. ]],
  414. ]));
  415. }
  416. protected function completionArray(string $sId, NeuronAI\Chat\Messages\Message $oMessage): array
  417. {
  418. $aMessage = [
  419. 'role' => 'assistant',
  420. 'content' => $oMessage->getContent(),
  421. ];
  422. $sFinish = 'stop';
  423. if ($oMessage instanceof NeuronAI\Chat\Messages\ToolCallMessage) {
  424. $sFinish = 'tool_calls';
  425. $aCalls = [];
  426. foreach ($oMessage->getTools() as $oTool) {
  427. $aInputs = $oTool->getInputs();
  428. $aCalls[] = [
  429. 'id' => (string)($oTool->getCallId() ?? ''),
  430. 'type' => 'function',
  431. 'function' => [
  432. 'name' => $oTool->getName(),
  433. 'arguments' => json_encode($aInputs === [] ? new stdClass() : $aInputs, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
  434. ],
  435. ];
  436. }
  437. $aMessage['tool_calls'] = $aCalls;
  438. if ($aMessage['content'] === null || $aMessage['content'] === '')
  439. $aMessage['content'] = null;
  440. }
  441. return [
  442. 'id' => $sId,
  443. 'object' => 'chat.completion',
  444. 'choices' => [[
  445. 'index' => 0,
  446. 'message' => $aMessage,
  447. 'finish_reason' => $sFinish,
  448. ]],
  449. ];
  450. }
  451. protected function contentDelta(string $sId, string $sContent): string
  452. {
  453. return $this->sse([
  454. 'id' => $sId,
  455. 'object' => 'chat.completion.chunk',
  456. 'choices' => [[
  457. 'index' => 0,
  458. 'delta' => ['content' => $sContent],
  459. 'finish_reason' => null,
  460. ]],
  461. ]);
  462. }
  463. protected function sse(array $aPayload): string
  464. {
  465. return 'data: ' . json_encode($aPayload, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n\n";
  466. }
  467. protected function logProvider(Throwable $oException): void
  468. {
  469. bx_log('sys_agents', 'AI proxy provider failed: ' . $oException->getMessage(), BX_LOG_ERR);
  470. }
  471. }
  472. /** @} */