<?php

namespace App\Helper;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;


/**
 * Class Gpt
 * @package App\Helper
 * @author zbj
 * @date 2023/11/3
 */
class Gpt
{
    public $api = 'http://openai.waimaoq.com/';

    public $header = [];

    private static $instance;

    public static function instance(){
        if(!self::$instance){
            self::$instance = new static;
        }
        return self::$instance;
    }

    /**
     * 全球搜-文本生成接口。模型:gpt-3.5-turbo
     * @author zbj
     * @date 2023/8/25
     *
     */
    public function openai_chat_qqs($content, $system_content = '')
    {
        $url = $this->api . 'v2/openai_chat_qqs';

        $data = [
            'messages' => [],
        ];
        if ($system_content) {
            $data['messages'][] = [
                "role" => "system",
                "content" => $system_content
            ];
        }
        $data['messages'][] = [
            "role" => "user",
            "content" => $content
        ];

        $time = time();
        try {
            $result = Http::withHeaders($this->header)->withOptions(['verify' => false])->acceptJson()
                ->withBody(json_encode($data, JSON_UNESCAPED_UNICODE), 'application/json')
                ->post($url);
            $json = $result->json();
            if (!isset($json['text'])) {
                Log::error('openai_chat_qqs data:', $data);
                Log::error('openai_chat_qqs result:' . (time() - $time), $json === null ? ['null'] : $json);
            }
        } catch (\Throwable $e) {
            Log::error('openai_chat_qqs time ' . (time() - $time) . ' error:' . $e->getMessage());
            $json = [];
        }
        return $json['text'] ?? '';
    }

}