找回密码
 立即注册
搜索
查看: 817|回复: 1

[基础语法] chatgpt PHP接口demo

[复制链接]

581

主题

110

回帖

4066

积分

管理员

积分
4066

众神之神

发表于 2023-11-1 17:41:20 | 显示全部楼层 |阅读模式
需要假设在海外能够访问chatgpt接口的服务器上才可以,国内不可以
  1. <?php


  2. function chat()
  3. {
  4.     $apiKey = 'CHATGPT-KEY放在这里';

  5.     $endpoint  = 'https://api.openai.com/v1/chat/completions';

  6.     // 构建请求的数据
  7.     $data = array(
  8.         "messages" => array(
  9.             array("role" => "system", "content" => "你是一个智能助手"),
  10.             array("role" => "user", "content" => "写一篇关于春天的文章,125字!")
  11.         ),
  12.         "model" => "gpt-3.5-turbo" // 添加模型参数
  13.     );

  14.     // 设置请求头
  15.     $headers = array(
  16.         'Content-Type: application/json',
  17.         'Authorization: Bearer ' . $apiKey
  18.     );

  19.     $ch = curl_init();

  20.     curl_setopt($ch, CURLOPT_URL, $endpoint);
  21.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  22.     curl_setopt($ch, CURLOPT_HEADER, false);
  23.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  24.     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  25.     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  26.     curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  27.     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE));
  28.     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  29.     $response = curl_exec($ch);

  30.     curl_close($ch);
  31.     var_dump($response);die;
  32.     // 处理响应数据
  33.     if ($response) {
  34.         $decodedResponse = json_decode($response, true);
  35.         // 输出生成的回复
  36.         echo "Generated reply: " . $decodedResponse['choices'][0]['message']['content'];
  37.     } else {
  38.         echo "请求失败。";
  39.     }

  40. }
  41. chat();
复制代码


581

主题

110

回帖

4066

积分

管理员

积分
4066

众神之神

 楼主| 发表于 2023-11-2 11:21:10 | 显示全部楼层
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|十三博客 ( 鲁ICP备2023000528号 )

GMT+8, 2026-6-1 18:31 , Processed in 0.051101 second(s), 21 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表