Write a simple Chatgpt mirror source code in PHP

First, use PHP's curl library to send data to the OpenAI API and receive responses from the chatbot. Use the curl_setopt function to set options such as CURLOPT_URL, CURLOPT_POST, CURLOPT_POSTFIELDS, CURLOPT_RETURNTRANSFER, CURLOPT_HTTPHEADER, and CURLOPT_CONNECTTIMEOUT.

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

    curl_setopt($curl, CURLOPT_URL, "https://api.openai.com/v1/completions");
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array(
        "prompt" => $prompt,
        "temperature" => 0.5,
        "max_tokens" => 1024,
        "n" => 1,
        "stop" => "\n"
    )));
    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);
    return $json["choices"][0]["text"];
}

Next, the API is used to process the request from the client and return the chatbot's answer. In this file, use $_POST to access the POST data, include user input in it, and then use json_encode to convert the response data to JSON format and send it back to the client.

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

if ($_POST["prompt"]) {
    
    
    $prompt = $_POST["prompt"];
    $response = generate_chatbot_response($prompt);
    echo json_encode(array("response" => $response));
}

Integrate this API file with other libraries and functions to create a chatbot that easily responds to user input. The server can be communicated using AJAX or WebSocket for real-time response.

Guess you like

Origin blog.csdn.net/u010436243/article/details/129939712