AiTranslateService.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Log;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Http\Client\RequestException;
  6. use Illuminate\Support\Facades\Cache;
  7. use App\Models\Task;
  8. use App\Models\PaliText;
  9. use App\Models\PaliSentence;
  10. use App\Models\AiModel;
  11. use App\Models\Sentence;
  12. use App\Http\Api\ChannelApi;
  13. use App\Services\AuthService;
  14. use App\Http\Api\MdRender;
  15. use App\Exceptions\SectionTimeoutException;
  16. use App\Exceptions\TaskFailException;
  17. class DatabaseException extends \Exception {}
  18. class AiTranslateService
  19. {
  20. private $queue = 'ai_translate_v2';
  21. private $modelToken = null;
  22. private $task = null;
  23. protected $mq;
  24. private $apiTimeout = 30;
  25. private $llmTimeout = 300;
  26. private $taskTopicId;
  27. private $stop = false;
  28. private $maxProcessTime = 15 * 60; //一个句子的最大处理时间
  29. private $mqTimeout = 60;
  30. private $openaiProxy = null;
  31. public function __construct() {}
  32. public function setProxy(string $proxy): self
  33. {
  34. $this->openaiProxy = $proxy;
  35. return $this;
  36. }
  37. /**
  38. * @param string $messageId
  39. * @param array $translateData
  40. */
  41. public function processTranslate(string $messageId, array $messages): bool
  42. {
  43. $start = time();
  44. if (!is_array($messages) || count($messages) === 0) {
  45. Log::error('message is not array');
  46. return false;
  47. }
  48. $first = $messages[0];
  49. $this->task = $first->task->info;
  50. $taskId = $this->task->id;
  51. Cache::put("/task/{$taskId}/message_id", $messageId);
  52. $pointerKey = "/task/{$taskId}/pointer";
  53. $pointer = 0;
  54. if (Cache::has($pointerKey)) {
  55. //回到上次中断的点
  56. $pointer = Cache::get($pointerKey);
  57. Log::info("last break point {$pointer}");
  58. }
  59. //获取model token
  60. $this->modelToken = $first->model->token;
  61. Log::debug($this->queue . ' ai assistant token', ['token' => $this->modelToken]);
  62. $this->setTaskStatus($this->task->id, 'running');
  63. // 设置task discussion topic
  64. $this->taskTopicId = $this->taskDiscussion(
  65. $this->task->id,
  66. 'task',
  67. $this->task->title,
  68. $this->task->category,
  69. null
  70. );
  71. $time = [$this->maxProcessTime];
  72. for ($i = $pointer; $i < count($messages); $i++) {
  73. // 获取当前内存使用量
  74. Log::debug("memory usage: " . memory_get_usage(true) / 1024 / 1024 . " MB");
  75. // 获取峰值内存使用量
  76. Log::debug("memory peak usage: " . memory_get_peak_usage(true) / 1024 / 1024 . " MB");
  77. if ($this->stop) {
  78. Log::info("收到退出信号 pointer={$i}");
  79. return false;
  80. }
  81. if (\App\Tools\Tools::isStop()) {
  82. //检测到停止标记
  83. return false;
  84. }
  85. Cache::put($pointerKey, $i);
  86. $message = $messages[$i];
  87. $taskDiscussionContent = [];
  88. //推理
  89. $responseLLM = $this->requestLLM($message);
  90. $taskDiscussionContent[] = '- LLM request successful';
  91. if ($this->task->category === 'translate') {
  92. //写入句子库
  93. $message->sentence->content = $responseLLM['content'];
  94. try {
  95. $this->saveSentence($message->sentence);
  96. } catch (\Exception $e) {
  97. Log::error('sentence', ['message' => $e]);
  98. continue;
  99. }
  100. }
  101. if ($this->task->category === 'suggest') {
  102. //写入pr
  103. try {
  104. $this->savePr($message->sentence, $responseLLM['content']);
  105. } catch (\Exception $e) {
  106. Log::error('sentence', ['message' => $e]);
  107. continue;
  108. }
  109. }
  110. #获取句子id
  111. $sUid = $this->getSentenceId($message->sentence);
  112. //写入句子 discussion
  113. $topicId = $this->taskDiscussion(
  114. $sUid,
  115. 'sentence',
  116. $this->task->title,
  117. $this->task->category,
  118. null
  119. );
  120. if ($topicId) {
  121. Log::info($this->queue . ' discussion create topic successful');
  122. $data['parent'] = $topicId;
  123. unset($data['title']);
  124. $topicChildren = [];
  125. //提示词
  126. $topicChildren[] = $message->prompt;
  127. //任务结果
  128. $topicChildren[] = $responseLLM['content'];
  129. //推理过程写入discussion
  130. if (
  131. isset($responseLLM['reasoningContent']) &&
  132. !empty($responseLLM['reasoningContent'])
  133. ) {
  134. $topicChildren[] = $responseLLM['reasoningContent'];
  135. }
  136. foreach ($topicChildren as $content) {
  137. Log::debug($this->queue . ' discussion child request', ['data' => $data]);
  138. $dId = $this->taskDiscussion($sUid, 'sentence', $this->task->title, $content, $topicId);
  139. if ($dId) {
  140. Log::info($this->queue . ' discussion child successful');
  141. }
  142. }
  143. } else {
  144. Log::error($this->queue . ' discussion create topic response is null');
  145. }
  146. //修改task 完成度
  147. $progress = $this->setTaskProgress($message->task->progress);
  148. $taskDiscussionContent[] = "- progress=" . $progress;
  149. //写入task discussion
  150. if ($this->taskTopicId) {
  151. $content = implode("\n", $taskDiscussionContent);
  152. $dId = $this->taskDiscussion(
  153. $this->task->id,
  154. 'task',
  155. $this->task->title,
  156. $content,
  157. $this->taskTopicId
  158. );
  159. } else {
  160. Log::error('no task discussion root');
  161. }
  162. //计算剩余时间是否足够再做一次
  163. $time[] = time() - $start;
  164. rsort($time);
  165. $remain = $this->mqTimeout - (time() - $start);
  166. if ($remain < $time[0]) {
  167. throw new SectionTimeoutException;
  168. }
  169. }
  170. //任务完成 修改任务状态为 done
  171. if ($i === count($messages)) {
  172. $this->setTaskStatus($this->task->id, 'done');
  173. Cache::forget($pointerKey);
  174. Log::info('ai translate task complete');
  175. }
  176. return true;
  177. }
  178. private function setTaskStatus($taskId, $status)
  179. {
  180. $url = config('app.url') . '/api/v2/task-status/' . $taskId;
  181. $data = [
  182. 'status' => $status,
  183. ];
  184. Log::debug('ai_translate task status request', ['url' => $url, 'data' => $data]);
  185. $response = Http::timeout($this->apiTimeout)->withToken($this->modelToken)->patch($url, $data);
  186. //判断状态码
  187. if ($response->failed()) {
  188. Log::error('ai_translate task status error', ['data' => $response->json()]);
  189. } else {
  190. Log::info('ai_translate task status done');
  191. }
  192. }
  193. private function saveModelLog($token, $data)
  194. {
  195. $url = config('app.url') . '/api/v2/model-log';
  196. $response = Http::timeout($this->apiTimeout)->withToken($token)->post($url, $data);
  197. if ($response->failed()) {
  198. Log::error('ai-translate model log create failed', ['data' => $response->json()]);
  199. return false;
  200. }
  201. return true;
  202. }
  203. private function taskDiscussion($resId, $resType, $title, $content, $parentId = null)
  204. {
  205. $url = config('app.url') . '/api/v2/discussion';
  206. $taskDiscussionData = [
  207. 'res_id' => $resId,
  208. 'res_type' => $resType,
  209. 'content' => $content,
  210. 'content_type' => 'markdown',
  211. 'type' => 'discussion',
  212. 'notification' => false,
  213. ];
  214. if ($parentId) {
  215. $taskDiscussionData['parent'] = $parentId;
  216. } else {
  217. $taskDiscussionData['title'] = $title;
  218. }
  219. Log::debug($this->queue . ' discussion create', ['url' => $url, 'data' => json_encode($taskDiscussionData)]);
  220. $response = Http::timeout($this->apiTimeout)
  221. ->withToken($this->modelToken)
  222. ->post($url, $taskDiscussionData);
  223. if ($response->failed()) {
  224. Log::error($this->queue . ' discussion create error', ['data' => $response->json()]);
  225. return false;
  226. }
  227. Log::debug($this->queue . ' discussion create', ['data' => json_encode($response->json())]);
  228. if (isset($response->json()['data']['id'])) {
  229. return $response->json()['data']['id'];
  230. }
  231. return false;
  232. }
  233. private function requestLLM($message)
  234. {
  235. $param = [
  236. "model" => $message->model->model,
  237. "messages" => [
  238. ["role" => "system", "content" => $message->model->system_prompt ?? ''],
  239. ["role" => "user", "content" => $message->prompt],
  240. ],
  241. "temperature" => 0.3, # 低随机性,确保准确
  242. "top_k" => 20, # 限制候选词范围
  243. "stream" => false
  244. ];
  245. if ($this->openaiProxy) {
  246. $requestUrl = $this->openaiProxy;
  247. $body = [
  248. 'open_ai_url' => $message->model->url,
  249. 'api_key' => $message->model->key,
  250. 'payload' => $param,
  251. ];
  252. } else {
  253. $requestUrl = $message->model->url;
  254. $body = $param;
  255. }
  256. Log::info($this->queue . ' LLM request ' . $message->model->url . ' model:' . $param['model']);
  257. Log::debug($this->queue . ' LLM api request', [
  258. 'url' => $message->model->url,
  259. 'data' => json_encode($param),
  260. ]);
  261. //写入 model log
  262. $modelLogData = [
  263. 'model_id' => $message->model->uid,
  264. 'request_at' => now(),
  265. 'request_data' => json_encode($param, JSON_UNESCAPED_UNICODE),
  266. ];
  267. //失败重试
  268. $maxRetries = 3;
  269. $attempt = 0;
  270. try {
  271. while ($attempt < $maxRetries) {
  272. try {
  273. $response = Http::withToken($message->model->key)
  274. ->timeout($this->llmTimeout)
  275. ->post($requestUrl, $body);
  276. // 如果状态码是 4xx 或 5xx,会自动抛出 RequestException
  277. $response->throw();
  278. Log::info($this->queue . ' LLM request successful');
  279. $modelLogData['request_headers'] = json_encode($response->handlerStats(), JSON_UNESCAPED_UNICODE);
  280. $modelLogData['response_headers'] = json_encode($response->headers(), JSON_UNESCAPED_UNICODE);
  281. $modelLogData['status'] = $response->status();
  282. $modelLogData['response_data'] = json_encode($response->json(), JSON_UNESCAPED_UNICODE);
  283. self::saveModelLog($this->modelToken, $modelLogData);
  284. break; // 跳出 while 循环
  285. } catch (RequestException $e) {
  286. Log::error($this->queue . ' LLM request exception: ' . $e->getMessage());
  287. $failResponse = $e->response;
  288. $modelLogData['request_headers'] = json_encode($failResponse->handlerStats(), JSON_UNESCAPED_UNICODE);
  289. $modelLogData['response_headers'] = json_encode($failResponse->headers(), JSON_UNESCAPED_UNICODE);
  290. $modelLogData['status'] = $failResponse->status();
  291. $modelLogData['response_data'] = $response->body();
  292. $modelLogData['success'] = false;
  293. self::saveModelLog($this->modelToken, $modelLogData);
  294. $attempt++;
  295. $status = $e->response->status();
  296. // 某些错误不需要重试
  297. if (in_array($status, [400, 401, 403, 404, 422])) {
  298. Log::warning("客户端错误,不重试: {$status}\n");
  299. throw new TaskFailException; // 重新抛出异常
  300. }
  301. // 服务器错误或网络错误可以重试
  302. if ($attempt < $maxRetries) {
  303. $delay = pow(2, $attempt); // 指数退避
  304. Log::warning("请求失败(第 {$attempt} 次),{$delay} 秒后重试...\n");
  305. sleep($delay);
  306. } else {
  307. Log::error("达到最大重试次数,请求最终失败\n");
  308. throw new TaskFailException;
  309. }
  310. } catch (\Exception $e) {
  311. throw $e;
  312. }
  313. }
  314. } catch (\Exception $e) {
  315. throw $e;
  316. }
  317. Log::info($this->queue . ' model log saved');
  318. $aiData = $response->json();
  319. Log::debug($this->queue . ' LLM http response', ['data' => $response->json()]);
  320. $responseContent = $aiData['choices'][0]['message']['content'];
  321. if (isset($aiData['choices'][0]['message']['reasoning_content'])) {
  322. $reasoningContent = $aiData['choices'][0]['message']['reasoning_content'];
  323. }
  324. $output = ['content' => $responseContent];
  325. Log::debug($this->queue . ' LLM response content=' . $responseContent);
  326. if (empty($reasoningContent)) {
  327. Log::debug($this->queue . ' no reasoningContent');
  328. } else {
  329. Log::debug($this->queue . ' reasoning=' . $reasoningContent);
  330. $output['reasoningContent'] = $reasoningContent;
  331. }
  332. return $output;
  333. }
  334. /**
  335. * 写入句子库
  336. */
  337. private function saveSentence(array $sentence, ?string $token = null)
  338. {
  339. $url = config('app.url') . '/api/v2/sentence';
  340. Log::info($this->queue . " sentence update {$url}");
  341. $response = Http::timeout($this->apiTimeout)
  342. ->withToken($token ?? $this->modelToken)
  343. ->post($url, [
  344. 'sentences' => [$sentence],
  345. ]);
  346. if ($response->failed()) {
  347. Log::error($this->queue . ' sentence update failed', [
  348. 'url' => $url,
  349. 'data' => $response->json(),
  350. ]);
  351. throw new DatabaseException("sentence 数据库写入错误");
  352. }
  353. $count = $response->json()['data']['count'];
  354. Log::info("{$this->queue} sentence update {$count} successful");
  355. }
  356. private function savePr($sentence, $content)
  357. {
  358. $url = config('app.url') . '/api/v2/sentpr';
  359. Log::info($this->queue . " sentence update {$url}");
  360. $response = Http::timeout($this->apiTimeout)->withToken($this->modelToken)->post($url, [
  361. 'book' => $sentence->book_id,
  362. 'para' => $sentence->paragraph,
  363. 'begin' => $sentence->word_start,
  364. 'end' => $sentence->word_end,
  365. 'channel' => $sentence->channel_uid,
  366. 'text' => $content,
  367. 'notification' => false,
  368. 'webhook' => false,
  369. ]);
  370. if ($response->failed()) {
  371. Log::error($this->queue . ' sentence update failed', [
  372. 'url' => $url,
  373. 'data' => $response->json(),
  374. ]);
  375. throw new DatabaseException("pr 数据库写入错误");
  376. }
  377. if ($response->json()['ok']) {
  378. Log::info("{$this->queue} sentence suggest update successful");
  379. } else {
  380. Log::error("{$this->queue} sentence suggest update failed", [
  381. 'url' => $url,
  382. 'data' => $response->json(),
  383. ]);
  384. }
  385. }
  386. private function getSentenceId($sentence)
  387. {
  388. $url = config('app.url') . '/api/v2/sentence-info/aa';
  389. Log::info('ai translate', ['url' => $url]);
  390. $response = Http::timeout($this->apiTimeout)->withToken($this->modelToken)->get($url, [
  391. 'book' => $sentence->book_id,
  392. 'par' => $sentence->paragraph,
  393. 'start' => $sentence->word_start,
  394. 'end' => $sentence->word_end,
  395. 'channel' => $sentence->channel_uid
  396. ]);
  397. if (!$response->json()['ok']) {
  398. Log::error($this->queue . ' sentence id error', ['data' => $response->json()]);
  399. return false;
  400. }
  401. $sUid = $response->json()['data']['id'];
  402. Log::debug("sentence id={$sUid}");
  403. return $sUid;
  404. }
  405. private function setTaskProgress($current)
  406. {
  407. $taskProgress = $current;
  408. if ($taskProgress->total > 0) {
  409. $progress = (int)($taskProgress->current * 100 / $taskProgress->total);
  410. } else {
  411. $progress = 100;
  412. Log::error($this->queue . ' progress total is zero', ['task_id' => $this->task->id]);
  413. }
  414. $url = config('app.url') . '/api/v2/task/' . $this->task->id;
  415. $data = [
  416. 'progress' => $progress,
  417. ];
  418. Log::debug($this->queue . ' task progress request', ['url' => $url, 'data' => $data]);
  419. $response = Http::timeout($this->apiTimeout)->withToken($this->modelToken)->patch($url, $data);
  420. if ($response->failed()) {
  421. Log::error($this->queue . ' task progress error', ['data' => $response->json()]);
  422. } else {
  423. Log::info($this->queue . ' task progress successful progress=' . $response->json()['data']['progress']);
  424. }
  425. return $progress;
  426. }
  427. public function handleFailedTranslate(string $messageId, array $translateData, \Exception $exception): void
  428. {
  429. try {
  430. // 彻底失败时的业务逻辑
  431. // 设置task为失败状态
  432. $this->setTaskStatus($this->task->id, 'stop');
  433. //将故障信息写入task discussion
  434. if ($this->taskTopicId) {
  435. $dId = $this->taskDiscussion(
  436. $this->task->id,
  437. 'task',
  438. $this->task->title,
  439. "**处理失败ai任务时出错** 请重启任务 message id={$messageId} 错误信息:" . $exception->getMessage(),
  440. $this->taskTopicId
  441. );
  442. }
  443. } catch (\Exception $e) {
  444. Log::error('处理失败ai任务时出错', ['error' => $e->getMessage()]);
  445. }
  446. }
  447. /**
  448. * 读取task信息,将任务拆解为单句小任务
  449. *
  450. * @param string $taskId 任务uuid
  451. * @return array 拆解后的提示词数组
  452. */
  453. public static function makeByTask(string $taskId, $aiAssistantId)
  454. {
  455. $task = Task::findOrFail($taskId);
  456. $description = $task->description;
  457. $rows = explode("\n", $description);
  458. $params = [];
  459. foreach ($rows as $key => $row) {
  460. if (strpos($row, '=') !== false) {
  461. $param = explode('=', trim($row, '|'));
  462. $params[$param[0]] = $param[1];
  463. }
  464. }
  465. if (!isset($params['type'])) {
  466. Log::error('no $params.type');
  467. return false;
  468. }
  469. //get sentences in article
  470. $sentences = array();
  471. $totalLen = 0;
  472. switch ($params['type']) {
  473. case 'sentence':
  474. if (!isset($params['id'])) {
  475. Log::error('no $params.id');
  476. return false;
  477. }
  478. $sentences[] = explode('-', $params['id']);
  479. break;
  480. case 'para':
  481. if (!isset($params['book']) || !isset($params['paragraphs'])) {
  482. Log::error('no $params.book or paragraphs');
  483. return false;
  484. }
  485. $sent = PaliSentence::where('book', $params['book'])
  486. ->where('paragraph', $params['paragraphs'])->orderBy('word_begin')->get();
  487. foreach ($sent as $key => $value) {
  488. $sentences[] = [
  489. 'id' => [
  490. $value->book,
  491. $value->paragraph,
  492. $value->word_begin,
  493. $value->word_end,
  494. ],
  495. 'strlen' => $value->length
  496. ];
  497. $totalLen += $value->length;
  498. }
  499. break;
  500. case 'chapter':
  501. if (!isset($params['book']) || !isset($params['paragraphs'])) {
  502. Log::error('no $params.book or paragraphs');
  503. return false;
  504. }
  505. $chapterLen = PaliText::where('book', $params['book'])
  506. ->where('paragraph', $params['paragraphs'])->value('chapter_len');
  507. $sent = PaliSentence::where('book', $params['book'])
  508. ->whereBetween('paragraph', [$params['paragraphs'], $params['paragraphs'] + $chapterLen - 1])
  509. ->orderBy('paragraph')
  510. ->orderBy('word_begin')->get();
  511. foreach ($sent as $key => $value) {
  512. $sentences[] = [
  513. 'id' => [
  514. $value->book,
  515. $value->paragraph,
  516. $value->word_begin,
  517. $value->word_end,
  518. ],
  519. 'strlen' => $value->length
  520. ];
  521. $totalLen += $value->length;
  522. }
  523. break;
  524. default:
  525. return false;
  526. break;
  527. }
  528. //render prompt
  529. $mdRender = new MdRender([
  530. 'format' => 'prompt',
  531. 'footnote' => false,
  532. 'paragraph' => false,
  533. ]);
  534. $m = new \Mustache_Engine(array(
  535. 'entity_flags' => ENT_QUOTES,
  536. 'escape' => function ($value) {
  537. return $value;
  538. }
  539. ));
  540. # ai model
  541. $aiModel = AiModel::findOrFail($aiAssistantId);
  542. $modelToken = AuthService::getUserToken($aiModel->uid);
  543. $aiModel['token'] = $modelToken;
  544. $sumLen = 0;
  545. $mqData = [];
  546. foreach ($sentences as $key => $sentence) {
  547. $sumLen += $sentence['strlen'];
  548. $sid = implode('-', $sentence['id']);
  549. Log::debug($sid);
  550. $sentChannelInfo = explode('@', $params['channel']);
  551. $channelId = $sentChannelInfo[0];
  552. $data = [];
  553. $data['origin'] = '{{' . $sid . '}}';
  554. $data['translation'] = '{{sent|id=' . $sid;
  555. $data['translation'] .= '|channel=' . $channelId;
  556. $data['translation'] .= '|text=translation}}';
  557. if (isset($params['nissaya']) && !empty($params['nissaya'])) {
  558. $nissayaChannel = explode('@', $params['nissaya']);
  559. $channelInfo = ChannelApi::getById($nissayaChannel[0]);
  560. if ($channelInfo) {
  561. //查看句子是否存在
  562. $nissayaSent = Sentence::where('book_id', $sentence['id'][0])
  563. ->where('paragraph', $sentence['id'][1])
  564. ->where('word_start', $sentence['id'][2])
  565. ->where('word_end', $sentence['id'][3])
  566. ->where('channel_uid', $nissayaChannel[0])->first();
  567. if ($nissayaSent && !empty($nissayaSent->content)) {
  568. $nissayaData = [];
  569. $nissayaData['channel'] = $channelInfo;
  570. $nissayaData['data'] = '{{sent|id=' . $sid;
  571. $nissayaData['data'] .= '|channel=' . $nissayaChannel[0];
  572. $nissayaData['data'] .= '|text=translation}}';
  573. $data['nissaya'] = $nissayaData;
  574. }
  575. }
  576. }
  577. $content = $m->render($description, $data);
  578. $prompt = $mdRender->convert($content, []);
  579. //gen mq
  580. $aiMqData = [
  581. 'model' => $aiModel,
  582. 'task' => [
  583. 'info' => $task,
  584. 'progress' => [
  585. 'current' => $sumLen,
  586. 'total' => $totalLen
  587. ],
  588. ],
  589. 'prompt' => $prompt,
  590. 'sentence' => [
  591. 'book_id' => $sentence['id'][0],
  592. 'paragraph' => $sentence['id'][1],
  593. 'word_start' => $sentence['id'][2],
  594. 'word_end' => $sentence['id'][3],
  595. 'channel_uid' => $channelId,
  596. 'content' => $prompt,
  597. 'content_type' => 'markdown',
  598. 'access_token' => $sentChannelInfo[1] ?? $params['token'],
  599. ],
  600. ];
  601. array_push($mqData, $aiMqData);
  602. }
  603. $output = [
  604. 'model' => $aiModel->toArray(),
  605. 'task' => $task,
  606. ];
  607. $us = ['openai.com', 'googleapis.com', 'x.ai', 'anthropic.com'];
  608. $found = array_filter($us, function ($value) use ($output) {
  609. return str_contains($output['model']['url'], $value);
  610. });
  611. if ($found) {
  612. $output['area'] = 'us';
  613. } else {
  614. $output['area'] = 'cn';
  615. }
  616. $output['payload'] = $mqData;
  617. return $output;
  618. }
  619. public function stop()
  620. {
  621. $this->stop = true;
  622. }
  623. }