Skip to content

示例代码

php版:

php
<?php
header('Content-Type: application/json; charset=utf-8');
// 获取请求参数的函数
/**
 * 本示例程序是以 gpt 为示例的
 * 您可以自行按照需求自定义其他平台,接口返回形式按照标准返回即可
 */

function jsonResponse($code,$msg,$answer=null){
    /*
     * 统一数据返回格式
     *
     * 不管是您使用gpt还是其他自定义实现的功能,只要符合这个数据格式,平台语音机器人就可识别
     * 注意: code 为1 为正常响应,其他均视为失败,这点在自定义实现的过程中,需要严格注意
     *
     */
    $responseFormatData = [
        "code" => $code,
        "msg" => $msg,
        "answer" => $answer
    ];
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($responseFormatData, JSON_UNESCAPED_UNICODE);
    exit();
}

$post_json = file_get_contents("php://input");

$parse_data = json_decode($post_json, true);
// 这里是获取参数的,如果您填写的接口地址里携带了其他的参数,请自行在这里获取
// $apikey = $parse_data["apikey"];    //开启此行需注释下面一行,获取后台填写的apikey
$apikey = "sk-xxxx";

// 固定的格式,与平台交互的固定参数格式,请勿修改
$content_list = $parse_data["content_list"];

if(empty($content_list)) {
    jsonResponse(400,"必填参数[content_list]不能为空");
}


// 以下是以 chatgpt 模型为例

$url = 'https://api.openai.com/v1/chat/completions';
$model = 'gpt-4.0';
$post_content =[["role" => "system", "content" => "You are GPT, a large language model. Follow the user's instructions carefully. "]];
$post_content=array_merge($post_content,$content_list);
$params = [
    'model' => $model,
    'messages' =>$post_content,
];
$payload = json_encode($params);

$OPENAI_API_KEY = trim($apikey); // 去除前后空格
$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $OPENAI_API_KEY
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);

if(curl_errno($ch)) {
    // 处理cURL请求异常
    jsonResponse(500,"Server error",curl_error($ch));
} else {
    curl_close($ch);
    $response = json_decode($result, true);
    if(isset($response["error"])){
        // 处理OpenAI API返回的错误响应
        jsonResponse(300,$response["error"]["message"],curl_error($ch));
    }
    else{
        $generated_text = $response['choices'][0]['message']['content'];
        if(empty($generated_text) ||!isset($generated_text)){
            jsonResponse(500,"获取答案失败");
        }
        // 返回成功响应
        jsonResponse(1,"Success",$generated_text);
    }
}
?>

GPT.ba