BxAiProxyKnowledge.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 BxAiProxyKnowledge
  12. {
  13. /**
  14. * Studio knowledge store for this search. The request body cannot choose a store.
  15. *
  16. * @param callable(int): array|false $fStore
  17. * @param callable(int): object $fEmbedder
  18. * @param callable(int): object $fVectorStore
  19. * @return array{documents: list<array{content:string, sourceType:string, sourceName:string, score:float}>}
  20. */
  21. public function run(array $aBody, int $iConfiguredId, callable $fStore, callable $fEmbedder, callable $fVectorStore): array
  22. {
  23. $sQuery = trim((string)($aBody['query'] ?? ''));
  24. if ($sQuery === '')
  25. throw new BxAiProxyException(400, 'Bad request');
  26. $aStore = $fStore($iConfiguredId);
  27. if (!$this->usableStore($aStore)) {
  28. bx_log('sys_agents', 'AI proxy knowledge store is not available', BX_LOG_ERR);
  29. return ['documents' => []];
  30. }
  31. try {
  32. $oEmbedder = $fEmbedder((int)$aStore['embedding_provider_id']);
  33. $oStore = $fVectorStore($iConfiguredId);
  34. $aEmbedding = $oEmbedder->embedText($sQuery);
  35. if (!is_array($aEmbedding))
  36. throw new BxAiProxyException(503, 'The proxy knowledge is not available');
  37. $aDocuments = [];
  38. foreach ($oStore->similaritySearch($aEmbedding) as $oDocument) {
  39. if (!$oDocument instanceof NeuronAI\RAG\Document)
  40. continue;
  41. $sContent = $oDocument->getContent();
  42. if ($sContent === '')
  43. continue;
  44. $aDocuments[] = [
  45. 'content' => $sContent,
  46. 'sourceType' => $oDocument->getSourceType(),
  47. 'sourceName' => $oDocument->getSourceName(),
  48. 'score' => $oDocument->getScore(),
  49. ];
  50. }
  51. return ['documents' => $aDocuments];
  52. }
  53. catch (BxAiProxyException $oException) {
  54. throw $oException;
  55. }
  56. catch (Throwable $oException) {
  57. bx_log('sys_agents', 'AI proxy knowledge failed: ' . $oException->getMessage(), BX_LOG_ERR);
  58. throw new BxAiProxyException(503, 'The proxy knowledge is not available');
  59. }
  60. }
  61. protected function usableStore(mixed $aStore): bool
  62. {
  63. if (!is_array($aStore) || empty($aStore['active']))
  64. return false;
  65. if ((int)($aStore['embedding_provider_id'] ?? 0) <= 0)
  66. return false;
  67. if ((string)($aStore['type'] ?? '') === 'una-proxy')
  68. return false;
  69. return true;
  70. }
  71. }
  72. /** @} */