ChatGPT官方API文档和对接示例

  1. ChatGPT官方API文档:https://beta.openai.com/docs/api-reference/introduction
  2. PHP调用API的方法:

 

//设置请求URL和参数
$url = 'https://api.openai.com/v1/engines/davinci-codex/completions';
$headers = array(
    'Content-Type: application/json',
    'Authorization: Bearer your_api_key'
);
$data = array(
    'prompt' => 'Hello',
    'max_tokens' => 5,
    'temperature' => 0.5,
);

//初始化curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//执行请求
$result = curl_exec($ch);
curl_close($ch);

//处理响应结果
$response = json_decode($result, true);
if ($response['object'] == 'error') {
    echo 'API Error: ' . $response['error']['message'];
} else {
    echo 'API Response: ' . $response['choices'][0]['text'];
}

注意事项:

1.需要先在ChatGPT官网注册并获取API Key;

2.需要在请求头中添加Authorization头,值为”Bearer your_api_key”,其中your_api_key为您的API Key;

3.需要将请求参数转换为JSON格式,并在请求头中添加Content-Type头,值为”application/json”;

4.响应结果也是JSON格式,需要进行解析。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片