SendMessage.php 3.6 KB
<?php
/**
 * +--------------------------------------------------------------------------------------------------------------------
 * 观察者层:调用 OpenAI 接口发送消息 处理业务逻辑
 * +--------------------------------------------------------------------------------------------------------------------
 *
 * PHP version 7
 *
 * @category  App\Jobs
 * @package   App\Jobs
 * @author    Richer <yangzi1028@163.com>
 * @date      2023年4月24日10:37:49
 * @copyright 2020-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
namespace App\Jobs;

use App\Models\Chat\ChatRecordItem;
use App\Models\Traits\SendMessageTrait;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Tectalic\OpenAi\Authentication;
use Tectalic\OpenAi\Manager;

/**
 * Class SendMessage
 * @package App\Jobs
 */
class SendMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    use SendMessageTrait;

    protected $desc =  '发送通知';
    protected $channel =  'openai';
    protected $model;
    protected $content =  '';
    protected $ai_model =  '';

    /**
     * Create a new job instance.
     *
     * @param $model
     * @param $content
     * @param $ai_model
     */
    public function __construct($model, $content, $ai_model)
    {
        $this->model = $model;
        $this->content = $content;
        $this->ai_model = $ai_model;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        record_log($this->channel, $this->desc, 'begin');

        if ($this->attempts() > 3) {
            record_log($this->channel, '尝试次数过多');
        } else {
            // 获取模型
            $model  = $this->model;
            $content = $this->content;
            record_log($this->channel, 'content:' . $content);

            $open_api_key = config('openai.api_key') ;// '你的Open Ai key';
            record_log($this->channel, 'open_api_key:' . $open_api_key);

            $openaiClient = Manager::build(
                new \GuzzleHttp\Client([
//                'proxy' => 'http://127.0.0.1:10809',
                    'verify' =>false
                ]),
                new Authentication($open_api_key)
            );

            // 代理地址 https://open2.aiproxy.xyz/
            $response = $openaiClient->completions()->create(
                new \Tectalic\OpenAi\Models\Completions\CreateRequest([
                    'model'     =>  $this->ai_model,
                    'prompt'    => $content,     // 设置问题
                    'max_tokens' => 2000,   // 设置答案长度 不设置只显示部分字符
                ])
            )->toModel();
            record_log($this->channel, 'response:' . json_encode($response));
            $answer = $response->choices[0]->text;
            record_log($this->channel, 'answer:' . $answer);

            // 写入回答创建AI的聊天记录
            $item = [
                'user_id'   => $model->user_id,
                'user_type' => ChatRecordItem::AI,
                'body'      => $answer,
                'ai_model'  => $this->ai_model
            ];
            $result = $model->items()->create($item);
        }
        record_log($this->channel, $this->desc, 'end');

        Log::channel('queue')->info('====================================== '.$this->desc.' end ======================================');
    }
}