前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ChatGPT之GPT 3.5 Turbo的API调用接口的方法

ChatGPT之GPT 3.5 Turbo的API调用接口的方法

作者头像
目的地-Destination
发布2023-03-18 16:21:49
3.9K0
发布2023-03-18 16:21:49
举报
文章被收录于专栏:目的地-Destination

代码非常简单; 保存为.php文件,然后浏览器访问该文件,并在地址后面拼接?text=你要问的问题即可 例如:https://blog.chrison.cn/chatgpt.php?text=写一份女士的自我介绍

代码语言:javascript
复制
<?php
/* 
OpenAI chat with a short-term memory
uses the gpt-3.5-turbo language model
from - Chrison Leon - https://blog.chrison.cn
*/

$openai_api_key = 'sk-'; //这里填写你申请的key
$number_of_interactions_to_remember = 10;

$forget = isset($_GET['forget']) ? $_GET['forget'] : null;
$text = isset($_GET['text']) ? $_GET['text'] : null;


if($forget){
    $_SESSION['conversations'] = null;
}
if($text){
  if (!isset($_SESSION['conversations'])) {
    $_SESSION['conversations'] = array();
  }

  if (count($_SESSION['conversations']) >= $number_of_interactions_to_remember) {
    array_shift($_SESSION['conversations']);
  }


  $data = array(
    'model' => 'gpt-3.5-turbo',
    'messages' => array(
      array(
        'role' => 'system',
        'content' => 'You are a helpful assistant called Frank that gives short, friendly reponses.'
      )
      
    )
  );

  foreach ($_SESSION['conversations'] as $conversation) {
    foreach ($conversation as $message) {
      array_push($data['messages'], array(
        'role' => $message['role'],
        'content' => $message['content']
      ));
    }
  }

  array_push($data['messages'], array(
    'role' => 'user',
    'content' => $text
  ));

  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_HTTPHEADER => array(
      'Authorization: Bearer ' . $openai_api_key,
      'Content-Type: application/json'
    ),
  ));

  $response = curl_exec($curl);
  $response = json_decode($response, true);
  curl_close($curl);
  $content = $response['choices'][0]['message']['content'];

  $new_conversation = array(
    array(
      'role' => 'user',
      'content' => $text
    ),
    array(
      'role' => 'assistant',
      'content' => $content
    )
  );

  array_push($_SESSION['conversations'], $new_conversation);
  echo $content;
}
?>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023年03月17日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档