GPT 问答

GPT 问答







<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $key = $_POST["key"];
    $question = $_POST["question"];

    function get_ai_answer($question, $key) {
        $post_data = array(
            'model' => 'gpt-3.5-turbo',
            'messages' => array(
                array(
                    'role' => 'system',
                    'content' => 'You are a helpful assistant that answers questions.',
                ),
                array(
                    'role' => 'user',
                    'content' => $question,
                ),
            ),
        );

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

        $headers = array();
        $headers[] = 'Authorization: Bearer ' . $key;
        $headers[] = 'Content-Type: application/json';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);

        $data_ret = json_decode($result, true);

        if (isset($data_ret['choices'])) {
            $answer = $data_ret['choices'][0]['message']['content'];
        } else {
            if ($data_ret['error']["message"]) {
                $answer = $data_ret['error']["message"];
            } else {
                $answer = 'An error occurred in the AI model.';
            }
        }

        return $answer;
    }

    $answer = get_ai_answer($question, $key);
    echo "<h3>Answer:</h3>";
    echo "<textarea rows='10' cols='50'>$answer</textarea>";
}
?>
GPT 问答工具 - 使用 OpenAI API 实现问答功能

原文地址: https://www.cveoy.top/t/topic/pUcb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录