chatgpt.php

mail@pastecode.io avatar
unknown
php
a year ago
2.1 kB
3
Indexable
Never
<?php
include 'db_config.php';

$openai_api_key = "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"; // Înlocuiți cu cheia dvs. API OpenAI

function addMessage($name, $message) {
    global $conn;
    $stmt = $conn->prepare("INSERT INTO chat_messages (name, message) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $message);
    $stmt->execute();
    $stmt->close();
}

function getMessages() {
    global $conn;
    $result = $conn->query("SELECT * FROM chat_messages ORDER BY timestamp ASC");
    $messages = array();
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }
    return $messages;
}

function fetchGPTResponse($message) {
    global $openai_api_key;

    $url = "https://api.openai.com/v1/engines/text-davinci-002/completions";
    $data = array(
        "prompt" => $message,
        "max_tokens" => 150,
        "n" => 1,
        "stop" => null,
        "temperature" => 0.8
    );
    $headers = array(
        "Content-Type: application/json",
        "Authorization: Bearer " . $openai_api_key
    );

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

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

    if ($err) {
        echo "Error: " . $err;
    } else {
        $decoded_response = json_decode($response, true);
        return $decoded_response['choices'][0]['text'];
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($_GET['action'] === 'getMessages') {
        $messages = getMessages();
        echo json_encode($messages);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_POST['action'] === 'addMessage') {
        $name = $_POST['name'];
        $message = $_POST['message'];
        addMessage($name, $message);
    } elseif ($_POST['action'] === 'fetchGPTResponse') {
        $response = fetchGPTResponse($_POST['message']);
        echo json_encode(['response' => $response]);
    }
}
?>