PHP chatgpt api使用方法

PHP chatgpt api使用方法

<?php

function generate_chatbot_response($prompt) {
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, "https://api.openai.com/v1/chat/completions");
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array(
        "messages" => [
        ["role" => "user", "content" => $prompt]
        ],
        "stream"=>false,
        "model" => "gpt-3.5-turbo"
    )));
    $OPENAI_API_KEY='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';
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer ".$OPENAI_API_KEY));
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);

    $response = curl_exec($curl);
  
    curl_close($curl);

    $json = json_decode($response, true);
      print_r($json["choices"][0]["message"]['content']);
    exit();
    return $json["choices"][0]["message"]['content'];
}




header("Content-Type: application/json");

if(empty($_GET["shuru"])){
    echo '你没有输入字符';
    exit();
}
if ($_GET["shuru"]) {
    $prompt = $_GET["shuru"];
    $response = generate_chatbot_response($prompt);
    echo json_encode(array("response" => $response));
}

 

posted @ 2023-04-21 15:43  newmiracle宇宙  阅读(156)  评论(0编辑  收藏  举报