MqAiTranslate.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Http\Api\Mq;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Facades\Http;
  7. use Illuminate\Support\Str;
  8. use App\Http\Controllers\AuthController;
  9. use App\Models\Sentence;
  10. use App\Models\ModelLog;
  11. class MqAiTranslate extends Command
  12. {
  13. /**
  14. * The name and signature of the console command.
  15. * php artisan mq:ai.translate
  16. * @var string
  17. */
  18. protected $signature = 'mq:ai.translate';
  19. /**
  20. * The console command description.
  21. *
  22. * @var string
  23. */
  24. protected $description = 'Command description';
  25. /**
  26. * Create a new command instance.
  27. *
  28. * @return void
  29. */
  30. public function __construct()
  31. {
  32. parent::__construct();
  33. }
  34. /**
  35. * Execute the console command.
  36. *
  37. * @return int
  38. */
  39. public function handle()
  40. {
  41. if (\App\Tools\Tools::isStop()) {
  42. return 0;
  43. }
  44. $exchange = 'router';
  45. $queue = 'ai_translate';
  46. $this->info(" [*] Waiting for {$queue}. To exit press CTRL+C");
  47. Log::debug("mq:progress start.");
  48. Mq::worker($exchange, $queue, function ($message) {
  49. Log::debug('start', ['message' => $message]);
  50. //写入 model log
  51. $modelLog = new ModelLog();
  52. $modelLog->uid = Str::uuid();
  53. $param = [
  54. "model" => $message->model->model,
  55. "messages" => [
  56. ["role" => "system", "content" => $message->model->system_prompt],
  57. ["role" => "user", "content" => $message->prompt],
  58. ],
  59. 'prompt' => $message->prompt,
  60. "temperature" => 0.7,
  61. "stream" => false
  62. ];
  63. $this->info('ai request' . $message->model->url);
  64. $this->info('model:' . $param['model']);
  65. Log::debug('ai api request', [
  66. 'url' => $message->model->url,
  67. 'data' => $param
  68. ]);
  69. $modelLog->model_id = $message->model->uid;
  70. $modelLog->request_at = now();
  71. $modelLog->request_data = json_encode($param, JSON_UNESCAPED_UNICODE);
  72. $response = Http::withToken($message->model->key)
  73. ->retry(2, 120000)
  74. ->post($message->model->url, $param);
  75. $modelLog->request_headers = json_encode($response->handlerStats(), JSON_UNESCAPED_UNICODE);
  76. $modelLog->response_headers = json_encode($response->headers(), JSON_UNESCAPED_UNICODE);
  77. $modelLog->status = $response->status();
  78. $modelLog->response_data = json_encode($response->json(), JSON_UNESCAPED_UNICODE);
  79. if ($response->failed()) {
  80. $modelLog->success = false;
  81. $modelLog->save();
  82. $this->error('http response error' . $response->json('message'));
  83. Log::error('http response error', ['data' => $response->json()]);
  84. return 1;
  85. }
  86. $modelLog->save();
  87. $this->info('log saved');
  88. $aiData = $response->json();
  89. Log::debug('http response', ['data' => $response->json()]);
  90. $responseContent = $aiData['choices'][0]['message']['content'];
  91. if (isset($aiData['choices'][0]['message']['reasoning_content'])) {
  92. $reasoningContent = $aiData['choices'][0]['message']['reasoning_content'];
  93. }
  94. $this->info('ai content=' . $responseContent);
  95. if (empty($reasoningContent)) {
  96. $this->info('no reasoningContent');
  97. } else {
  98. $this->info('reasoning=' . $reasoningContent);
  99. }
  100. //获取model token
  101. Log::debug('ai assistant token', ['user' => $message->model->uid]);
  102. $token = AuthController::getUserToken($message->model->uid);
  103. Log::debug('ai assistant token', ['token' => $token]);
  104. if ($message->task->info->category === 'translate') {
  105. //写入句子库
  106. $url = config('app.url') . '/api/v2/sentence';
  107. $sentData = [];
  108. $message->sentence->content = $responseContent;
  109. $sentData[] = $message->sentence;
  110. $this->info("upload to {$url}");
  111. Log::debug('sentence update http request', ['data' => $sentData]);
  112. $response = Http::withToken($token)->post($url, [
  113. 'sentences' => $sentData,
  114. ]);
  115. Log::debug('sentence update http response', ['data' => $response->json()]);
  116. if ($response->failed()) {
  117. $this->error('upload error' . $response->json('message'));
  118. Log::error('upload error', ['data' => $response->json()]);
  119. } else {
  120. $this->info('upload successful');
  121. }
  122. }
  123. //写入discussion
  124. #获取句子id
  125. $sUid = Sentence::where('book_id', $message->sentence->book_id)
  126. ->where('paragraph', $message->sentence->paragraph)
  127. ->where('word_start', $message->sentence->word_start)
  128. ->where('word_end', $message->sentence->word_end)
  129. ->where('channel_uid', $message->sentence->channel_uid)
  130. ->value('uid');
  131. $url = config('app.url') . '/api/v2/discussion';
  132. $data = [
  133. 'res_id' => $sUid,
  134. 'res_type' => 'sentence',
  135. 'title' => 'AI ' . $message->task->info->title,
  136. 'content' => 'AI ' . $message->task->info->category,
  137. 'content_type' => 'markdown',
  138. 'type' => 'discussion',
  139. ];
  140. $response = Http::withToken($token)->post($url, $data);
  141. if ($response->failed()) {
  142. $this->error('discussion error' . $response->json('message'));
  143. Log::error('discussion error', ['data' => $response->json()]);
  144. } else {
  145. $this->info('discussion topic successful');
  146. }
  147. $data['parent'] = $response->json()['data']['id'];
  148. unset($data['title']);
  149. $topicChildren = [];
  150. //提示词
  151. $topicChildren[] = $message->prompt;
  152. //任务结果
  153. $topicChildren[] = $responseContent;
  154. //推理过程写入discussion
  155. if (isset($reasoningContent) && !empty($reasoningContent)) {
  156. $topicChildren[] = $reasoningContent;
  157. }
  158. foreach ($topicChildren as $content) {
  159. $data['content'] = $content;
  160. Log::debug('discussion child request', ['url' => $url, 'data' => $data]);
  161. $response = Http::withToken($token)->post($url, $data);
  162. if ($response->failed()) {
  163. $this->error('discussion error' . $response->json('message'));
  164. Log::error('discussion error', ['data' => $response->json()]);
  165. } else {
  166. $this->info('discussion child successful');
  167. }
  168. }
  169. //修改task 完成度
  170. $taskProgress = $message->task->progress;
  171. $progress = (int)($taskProgress->current * 100 / $taskProgress->total);
  172. $url = config('app.url') . '/api/v2/task/' . $message->task->info->id;
  173. $data = [
  174. 'progress' => $progress,
  175. ];
  176. Log::debug('task progress request', ['url' => $url, 'data' => $data]);
  177. $response = Http::withToken($token)->patch($url, $data);
  178. if ($response->failed()) {
  179. $this->error('task progress error' . $response->json('message'));
  180. Log::error('task progress error', ['data' => $response->json()]);
  181. } else {
  182. $this->info('task progress successful progress=' . $response->json()['data']['progress']);
  183. }
  184. //完成 修改状态
  185. if ($taskProgress->current === $taskProgress->total) {
  186. $url = config('app.url') . '/api/v2/task-status/' . $message->task->info->id;
  187. $data = [
  188. 'status' => 'done',
  189. ];
  190. Log::debug('task status request', ['url' => $url, 'data' => $data]);
  191. $response = Http::withToken($token)->patch($url, $data);
  192. //判断状态码
  193. if ($response->failed()) {
  194. $this->error('task status error' . $response->json('message'));
  195. Log::error('task status error', ['data' => $response->json()]);
  196. } else {
  197. $this->info('task status successful ');
  198. }
  199. }
  200. return 0;
  201. });
  202. return 0;
  203. }
  204. }