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)); }
如果遇到什么不懂的地方直接关注公众号留言(本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。)
作者:newmiracle
出处:https://www.cnblogs.com/newmiracle/