MqAiTranslate.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 App\Http\Api\UserApi;
  8. use App\Http\Controllers\AuthController;
  9. class MqAiTranslate extends Command
  10. {
  11. /**
  12. * The name and signature of the console command.
  13. * php artisan mq:ai.translate
  14. * @var string
  15. */
  16. protected $signature = 'mq:ai.translate';
  17. /**
  18. * The console command description.
  19. *
  20. * @var string
  21. */
  22. protected $description = 'Command description';
  23. /**
  24. * Create a new command instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct()
  29. {
  30. parent::__construct();
  31. }
  32. /**
  33. * Execute the console command.
  34. *
  35. * @return int
  36. */
  37. public function handle()
  38. {
  39. if (\App\Tools\Tools::isStop()) {
  40. return 0;
  41. }
  42. $exchange = 'router';
  43. $queue = 'ai_translate';
  44. $this->info(" [*] Waiting for {$queue}. To exit press CTRL+C");
  45. Log::debug("mq:progress start.");
  46. Mq::worker($exchange, $queue, function ($message) {
  47. $param = [
  48. "model" => $message->model->model,
  49. "messages" => [
  50. ["role" => "system", "content" => "你是翻译人工智能助手.bhikkhu 为专有名词,不可翻译成其他语言。"],
  51. ["role" => "user", "content" => $message->content],
  52. ],
  53. "temperature" => 0.3,
  54. "stream" => false
  55. ];
  56. $response = Http::withToken($message->model->token)
  57. ->retry(2, 1000)
  58. ->post($message->model->url, $param);
  59. if ($response->failed()) {
  60. $this->error('http response error' . $response->json('message'));
  61. Log::error('http response error', ['data' => $response->json()]);
  62. return 1;
  63. }
  64. $aiData = $response->json();
  65. Log::debug('http response', ['data' => $response->json()]);
  66. //获取ai帐号的用户token
  67. $user = UserApi::getByName(config('mint.ai.assistant'));
  68. $token = AuthController::getUserToken($user['id']);
  69. Log::debug('ai assistant token', [
  70. 'user' => $user,
  71. 'token' => $token
  72. ]);
  73. //写入句子库
  74. $url = '/v2/sentence';
  75. $sentData = [];
  76. $sentData[] = $message->sentence;
  77. $response = Http::withToken($token)->post($url, [
  78. 'sentences' => $sentData,
  79. ]);
  80. Log::debug('sentence update http response', ['data' => $response->json()]);
  81. //写入task log
  82. //修改task 完成度
  83. return 0;
  84. });
  85. return 0;
  86. }
  87. }