|
|
需要假设在海外能够访问chatgpt接口的服务器上才可以,国内不可以
- <?php
- function chat()
- {
- $apiKey = 'CHATGPT-KEY放在这里';
- $endpoint = 'https://api.openai.com/v1/chat/completions';
- // 构建请求的数据
- $data = array(
- "messages" => array(
- array("role" => "system", "content" => "你是一个智能助手"),
- array("role" => "user", "content" => "写一篇关于春天的文章,125字!")
- ),
- "model" => "gpt-3.5-turbo" // 添加模型参数
- );
- // 设置请求头
- $headers = array(
- 'Content-Type: application/json',
- 'Authorization: Bearer ' . $apiKey
- );
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $endpoint);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HEADER, false);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE));
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- $response = curl_exec($ch);
- curl_close($ch);
- var_dump($response);die;
- // 处理响应数据
- if ($response) {
- $decodedResponse = json_decode($response, true);
- // 输出生成的回复
- echo "Generated reply: " . $decodedResponse['choices'][0]['message']['content'];
- } else {
- echo "请求失败。";
- }
- }
- chat();
复制代码
|
|