最近chatGPT和百度文心一言火的不得了,今天藤设计也整好在使用ChatGPT开发应用项目,给大家分享一段PHP请求api的代码,希望对开发人员有用。
注:该php文件需部署在海外空间或服务器上使用,不能在国内服务器上运行。
方案一
<?php define('OPENAI_API_KEY', '这里输入您的key秘钥'); $prompt = $_GET['prompt']; $response = sendPostRequest($prompt); echo $response; function sendPostRequest($prompt) { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.openai.com/v1/completions", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode(array( "prompt" => $prompt, "max_tokens" => 2048, "model" => "text-davinci-003" )), CURLOPT_HTTPHEADER => array( "Content-Type: application/json", "Authorization: Bearer " . OPENAI_API_KEY ), )); $response = curl_exec($curl); curl_close($curl); return $response; } ?>
以上代码保存为index.php存放到您海外空间或服务器里即可运行
在浏览器里输入index.php?prompt=请问有外星人吗?
你就可以看到openai回答的内容了!
方案二
<?php set_time_limit(0); // ChatGPT API endpoint // $url = 'https://api.openai.com/v1/engines/davinci-codex/completions'; $url = 'https://api.openai.com/v1/chat/completions'; //聊天接口 // $url = 'https://api.openai.com/v1/completions'; // Your API key $api_key = '这里输入您的key秘钥'; // Request headers $headers = array( 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key, ); // Request data $data = array( // 'model' => 'text-davinci-003', 'model' => 'gpt-3.5-turbo', //聊天模型 // 'model' => 'text-curie-001', 'temperature' => 0.8, // 'prompt' => '如何用php使用chatgpt的聊天接口', //聊天不用 'max_tokens' => 3000, 'messages' => [ ["role" => "user", "content" => "Hello!"], ["role" => "assistant","content" => "\n\n您好!有什么可以帮助您的今天?"], ["role" => "user", "content" => "历史上的今天发生过什么事情?"], ] ); // Send request $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $response = curl_exec($ch); curl_close($ch); // Print response echo $response; ?>