【开源推荐】今天给大家推荐一个基于ChatGPT-API的PHP开发库 openai-php-api

ChatGPT 2023年6月14日 1.41K

有了这个库大家就可以愉快的使用PHP对接chatGPT的官方接口了,至于对接了官方接口想要做什么就看你自己的啦

环境要求

PHP7.4或以上

composer 1.6.5以上

支持框架 Laravel、Symfony、Yii2、Cake PHP 或任何 PHP 框架,完全开源,支持OpenAI GPT-3 API接口。

支持功能

聊天 – 聊天GPT API

模型 – 列出模型,检索模型

创建 – 创建完成

编辑 – 创建编辑

图片 – 创建图像,编辑图像

嵌入 – 创建嵌入

声音 – 创建转录,创建翻译

文件 – 列出文件,上传文件,删除文件,检索文件,检索内容

安装使用

composer require orhanerday/open-ai
<?php

use Orhanerday\OpenAi\OpenAi;

$open_ai_key = ""; #openAI的key
$open_ai = new OpenAi($open_ai_key); //类的实例化

$chat = $open_ai->chat([
'model' => 'gpt-3.5-turbo', //定义模型
'messages' => [
[
"role" => "system", //角色系统
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who won the world series in 2020?"
],
[
"role" => "assistant", //角色助理
"content" => "The Los Angeles Dodgers won the World Series in 2020."
],
[
"role" => "user",
"content" => "Where was it played?"
],
],
'temperature' => 1.0,
'max_tokens' => 4000, //最大token
'frequency_penalty' => 0,
'presence_penalty' => 0,
]);


var_dump($chat);
echo "<br>";
echo "<br>";
echo "<br>";
// 解码响应
$d = json_decode($chat);
// 获取内容
echo($d->choices[0]->message->content);

基本网址

使用 setBaseURL() 方法指定Origin URL;

$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key,$originURL);
$open_ai->setBaseURL("https://ai.example.com/");

使用代理服务器

$open_ai->setProxy("http://127.0.0.1:1086");

设置标题

$open_ai->setHeader(["Connection"=>"keep-alive"]);

基于ChatGPT API 的聊天

$complete = $open_ai->chat([
'model' => 'gpt-3.5-turbo',
'messages' => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who won the world series in 2020?"
],
[
"role" => "assistant",
"content" => "The Los Angeles Dodgers won the World Series in 2020."
],
[
"role" => "user",
"content" => "Where was it played?"
],
],
'temperature' => 1.0,
'max_tokens' => 4000,
'frequency_penalty' => 0,
'presence_penalty' => 0,
]);

访问元素

<?php
// Dummy Response For Chat API
$j = '
{
"id":"chatcmpl-*****",
"object":"chat.completion",
"created":1679748856,
"model":"gpt-3.5-turbo-0301",
"usage":{
"prompt_tokens":9,
"completion_tokens":10,
"total_tokens":19
},
"choices":[
{
"message":{
"role":"assistant",
"content":"This is a test of the AI language model."
},
"finish_reason":"length",
"index":0
}
]
}
';

// decode response
$d = json_decode($j);

// Get Content
echo($d->choices[0]->message->content);

还有其余的用法,大家可以根据文档好好研究,我这里就不一一列举了。

资源下载
PHP学习网
公众号回复“PHPER6884”获取下载!
请打开微信扫描右边的二维码回复关键字“PHPER6884”也可以微信直接搜索“PHP学习网”关注微信公众号获取。


关注微信公众号『PHP学习网

第一时间了解最新网络动态
关注博主不迷路~

PHP学习网:站内收集的部分资源来源于网络,若侵犯了您的合法权益,请联系我们删除!
分享到:
赞(0)

文章评论

您需要之后才可以评论
0点赞 0评论 收藏 QQ分享 微博分享

PHP学习网

PHP学习网