下面是我之前用的代码:
第一个代码:
<?php
$question = $_POST['question'];
$model = "text-davinci-003";
$prompt = "What is your question?";
$data = array("model" => $model, "prompt" => $prompt, "temperature" => 0.7, "max_tokens" => 100, "top_p" => 1, "n" => 1, "stop" => "");
$data_string = json_encode($data);
$ch = curl_init('https://api.openai.com/v1/engines/davinci/jobs');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Bearer <API_KEY>'
)
);
$result = curl_exec($ch);
$result = json_decode($result, true);
$answer = $result['choices'][0]['text'];
echo $answer;
?>
第二个代码:
<?php
// 定义API密钥和请求URL
$api_key = "your_api_key";
$request_url = "https://api.openai.com/v1/engines/davinci/jobs";
// 定义问题文本
$prompt = "What is the capital of France?";
// 创建请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer " . $api_key,
"Content-Type: application/json"
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"prompt": "'.$prompt.'"}');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// 解析响应
$response_data = json_decode($response, true);
// 输出回答
echo $response_data["choices"][0]["text"];
?>
使用说明:
填写上在官网的sk_开头的秘钥就行(需要注意的是,找一个干净的美国IPvps,将程序放在上面就行了。)
具体如何请求这个api那就依靠自己去操作了,反正不难。
我之前就在chat gpt 刚出来的时候写了一个api接口代码,卖出去了十几份。
使用方法:
将上面代码中的 <API_KEY> 换成你申请的秘钥。
要是不会操作可以看一下我这一篇文章,php版本的对接到ChatGPT代码,封装为独立api,这个代码是我现在还在使用的。
里面有演示网站,大家可以去试试,觉得好用再支持。
当然还有更多的好东西,可以去本博客的另一个分类:好东西 里面去看看。
正文结束