通义千问大模型已经开放了端口对接,这几天刚好想做个功能,使用PHP对接通义千问 web接口,就单纯分享下刚写得简单的对接接口,纯当做借鉴使用。


具体代码:

function ask_aigc($kw)
{
//$kw 是提问关键词
        $data = [
            "model" => "qwen-v1",
            "input" => [
                "messages" => [
                    "0" => [
                        "role" => "system",
                        "content" => "你是某某角色。"
                    ],
                    "1" => [
                        "role" => "user",
                        "content" => "你好,".$kw
                    ]
                ]
            ],
            // "parameters" => []
        ];
        
        $paramss = json_encode($data);
        
        $headers = array(
            "Content-Type: application/json",
            // "Content-Length: ". strlen($data). "",
            "Accept: application/json",
            "Authorization: Bearer 自己的通义千问秘钥",
        );
        
        $url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        
        $return = $this->AI_HttpRequest($url, $paramss, 1, $headers);
        $result = json_decode($return  , true);
                if(isset($result['output'])){
                    $result_text = str_replace("\n","", $result['output']['text']);//返回结果
                }
                //这里的处理代码自己根据情况填写
        return $result;
}

/**
     * 通义千问发起网络请求函数
     * @param $url 请求的URL
     * @param bool $params 请求的参数内容
     * @param int $ispost 是否POST请求
     * @return bool|string 返回内容
     */
    private function AI_HttpRequest($url, $params = false, $ispost = 0, $header = null)
    {
        $httpInfo = array();
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_TIMEOUT, 12);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url.'?'.$params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        
        if(!empty($header)){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            // echo "cURL Error: ".curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }


点赞(1)

评论列表 共有 0 条评论

暂无评论
发表
评论
返回
顶部