AiTranslateService.php 25 KB

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