如何在PHP中对接openAI接口,PHP创建AI会话思路以及代码讲解【附源码】

1、 PHP调用OpenAI API的方法

1.如何注册 openAI 以及使用

https://platform.openai.com/account/api-keys 在这个地址进行注册,但是需要翻墙,可自己查找国内的试用地址。就不多赘述…

2.php 调用接口 (symfony框架)

php端代码:

思路:前端通过一个图标入口,点击后 发送请求,创建一个会话(也就是聊天室),并且把创建的这个会话 入库。并且后端返回一个入库生成的uuid,和默认的消息会话返回给前端,前端暂时存放在 input 隐藏域中,以备后续使用。此时完成一个会话的连接和创建。
ps:前端发送请求前,需要做一些校验,$this->verifySend(); 验证是否登录,和发送请求的频率
直接上代码如下:

<?php
namespace LdWxappPlugin\Api\Resource\Chatapi;
use ApiBundle\Api\ApiRequest;
use ApiBundle\Api\Resource\AbstractResource;
use ApiBundle\Api\Annotation\ApiConf;
use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class Chatapi extends AbstractResource
{
   
    public function add(ApiRequest $request): array
    {
   
        $uuid = $request->request->get('conversationId');
        // 没有 uuid 就要新建会话,入库,有uuid 就直接打开
        // 这里在页面上做了一个 显示隐藏效果 不刷新页面的情况下,关闭侧边窗口,元素移除屏幕
        // 再次打开,有uuid ,直接让元素 移回原来的尺寸 'right','-1000px' 'right','0px'
        if(empty($uuid)){
   
        	// 这里用它来区分是 右侧侧边栏 还是 独立网页版
            $display = $request->request->get('display',0);
            // 入库的会话名字 从侧边栏进来的是 默认对话,从网页进来的是 新建对话
            $conversationName = $request->request->get('conversationName','默认对话');
            // 课程 ID 和 课程类型 这里可根据自己的需求传递不同参数,这个课程ID 是为了跟踪 根据哪一个课程,点击聊天窗口的
            $sourceId = $request->request->get('sourceId');
            $sourceType = $request->request->get('sourceType');
    
            if (empty($sourceId) || empty($sourceType)){
   
                throw new BadRequestHttpException('sourceId或sourceType不能为空');
            }
            $currentUser = $this->getCurrentUser();
            // 生成 uuid ,uuid 是后端生成好,返回给前端,前端卸载 隐藏域里面,每次请求,用隐藏域里面的去做判断。
            $random = 'lingdai'.microtime(true).rand(1000,9999);
            $conversationId = Uuid::uuid5(Uuid::NAMESPACE_OID,$random)->toString();
            $goods = $this->findGoodsByTargetIdAndType($sourceId,$sourceType);
            $conversationData = [
                'conversationId' => $conversationId,
                'conversationName' => $conversationName,
                'userId' => $currentUser->getId(),
                'display' => $display,
                'goodsId' => $goods['id'],
                'createdTime' => time()
            ]; 
            $insertResult = $this->getChatApiService()->createConversation($conversationData);
            if ($insertResult){
   
            // role : 返回给前端的默认对话 可根据情况自行设置
                return [
                    'status'=> 'success',
                    'message'=> '创建成功',
                    'code'=> 1,
                    'data'=> [
                        'conversationId'=> $conversationId,
                        'conversationName'=> $conversationName,
                        'aiDocId'=>$goods['aiDocId'],
                        'id'=>$insertResult['id'],
                        'display'=>$insertResult['display'],
                        'goodsId'=>$insertResult['goodsId'],
                        'role' => [
                           [
                            'role' => 'AI',
                            'content' => "Hi:你好,哈哈哈哈哈".'</br>'.'123123123'
                           ]
                        ],
                    ]
                ];
            } else {
   
                return ['status'=> 'fail','message'=> '创建失败','code'=> 0,'data'=> []];
            }
        }else{
   
            return [];
        }
    }

// 根据 传过来的 课程ID 和 课程type 查询数据库,查到对应的商品ID 数据
    public function findGoodsByTargetIdAndType($sourceId,$sourceType)
    {
   
        if ($sourceType == "goods"){
   
            $goods = $this->getGoodsService()->getGoods($sourceId);
            return $goods;
        }
        $product = $this->getProductService()->getProductByTargetIdAndType($sourceId, $sourceType);

        $goods = $this->getGoodsService()->getGoodsByProductId($product['id']);
        return $goods;
    }
// 新建对话的 入库完成!


//http://www.lingdaipc.win/lddev.php/chat/pcAI/index?chatId=684&uuid=3b9aad06-356e-5534-a8bf-4a98a95a7497&goodsId=3021
// 独立的 PC 网页版 查询方法 根据上面 url中 传递的参数 ,查询对应的 chatId的 的对话
    public function search(ApiRequest $request)
    {
   
        // 判断 ID 是否存在,不存在 是独立出来的窗口 存在是跳转过来的
        $params = $request->query->all();
        $conditions = $this->filterParams($params);
        $conditions['display'] = 1;
        $currentUser = $this->getCurrentUser();
        $conditions['userIds'] = $currentUser['id'];
        list($offset, $limit) = $this->getOffsetAndLimit($request);
        $conversationTotal = $this->getChatApiService()->count($conditions);
        $searchResult = $this->getChatApiService()->search($conditions, ['createdTime' => 'DESC'], $o
  • 36
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

付煜晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值