为你,千千万万遍
NLP接口调用记录

又遇到一个项目需要调用gpt,这里就作为一个调用大模型api代码的合集吧,目前只有php代码,真的很喜欢php真的很方便。

已有模型示例

  • GPT 3.5
  • GPT 4
  • 科大讯飞星火
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
//gpt3.5
$modelApiKey = 'sk-yaoshulanianshunianderenxiangshu';
$apiEndpoint = 'https://api.openai.com/v1/completions';// 准备要发送的数据
$data = array(
'prompt' => '尽可能详细告诉我是谁,回复长一点',
'max_tokens' => 1024,
'temperature' => 0.6,
'n' => 1,
'model' => 'gpt-3.5-turbo-instruct'
);
// 实例CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiEndpoint);
//使用本地的梯子服务器中转,我的php没有配置翻墙,大概就是windows会把php的翻墙行为拦下来,所以只能通过这种方式伪翻墙
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:7890');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
// 禁用证书验证,ssl之前配https协议的时候做过,这里不关闭验证就会报错,maven的springboot好像可以完成这个验证,等之后有空尝试一下。
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer ' . $modelApiKey
));
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
echo '请求错误:' . $error;
exit;
}
// 关闭cURL
curl_close($ch);
$result = json_decode($response, true);
$answer = $result['choices'][0]['text'];
echo $response;
// 输出结果
echo $answer;
?>

GPT 4.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
$modelApiKey = 'sk-yaoxiaolushitouzhunishuoduibudui';
// 设置API端点
$apiEndpoint = 'https://api.openai.com/v1/chat/completions';// 准备要发送的数据
$text = "内容";
$data = array(
'messages' => array(
array('role' => 'system', 'content' => $text)
),
'model' => 'gpt-4',
'max_tokens' => 1024,
'temperature' => 0.6,
'n' => 1
);
// 实例
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $apiEndpoint);
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:7890');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
// 禁用证书验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer ' . $modelApiKey
));
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
echo '请求错误:' . $error;
exit;
}
// 关闭cURL
curl_close($ch);
$result = json_decode($response, true);
$answer = $result['choices'][0]['text'];
echo $response;
// 输出结果
echo $answer;
?>

讯飞星火大模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
<?php

namespace App\Http\Controllers\Api;

require('/home/gina/my_laravel/vendor/autoload.php');
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use WebSocket\Client;
use DB;
class UserController extends Controller
{
public function index()
{
$addr = "wss://spark-api.xf-yun.com/v3.5/chat";
// 密钥信息,在开放平台-控制台中获取:https://console.xfyun.cn/services/cbm
$Appid = "我不知道";
$Apikey = "不要问我";
$ApiSecret = "去找讯飞";
$authUrl = $this->assembleAuthUrl("GET", $addr, $Apikey, $ApiSecret);
// 创建ws连接对象
$client = new Client($authUrl);
// 连接到 WebSocket 服务器
if ($client) {
// 发送数据到 WebSocket 服务器
$text = DB::table("conversation")
->where("id", "=", 1)
->orderByDesc("op_id")
->value("text");
$data = $this->getBody($Appid, $text);

$client->send($data);
// 从 WebSocket 服务器接收数据
$answer = "";
while (true) {
$response = $client->receive();
$resp = json_decode($response, true);
$code = $resp["header"]["code"];
// echo "从服务器接收到的数据: " . $response;
if (0 == $code) {
$status = $resp["header"]["status"];
if ($status != 2) {
$content = $resp['payload']['choices']['text'][0]['content'];
$answer .= $content;
} else {
$content = $resp['payload']['choices']['text'][0]['content'];
$answer .= $content;
$total_tokens = $resp['payload']['usage']['text']['total_tokens'];
break;
}
} else {
echo "服务返回报错" . $response;
break;
}
}
print("\n返回结果为:\n");
print($answer);
$maxOpId = DB::table("conversation")->max("op_id");
$newOpId = $maxOpId + 1;
// 创建新记录并存储answer到text字段
DB::table("conversation")->insert([
"id" => 0,
"op_id" => $newOpId,
"text" => $answer
]);
} else {
echo "无法连接到 WebSocket 服务器";
}
}
/**
* 发送post请求
* @param string $url 请求地址
* @param array $post_data post键值对数据
* @return string
*/
function http_request($url, $post_data, $headers)
{
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => $headers,
'content' => $postdata,
'timeout' => 15 * 60 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

// echo $result;

return "success";
}

//构造参数体
function getBody($appid, $question)
{
$header = array(
"app_id" => $appid,
"uid" => "12345"
);

$parameter = array(
"chat" => array(
"domain" => "generalv3.5",
"temperature" => 0.5,
"max_tokens" => 1024
)
);

// 从数据库中获取对话数据
$conversation = DB::table('conversation')
->orderBy('op_id', 'asc')
->get();
$messages = [];
foreach ($conversation as $row) {
if ($row->id == 0) {
$role = "assistant";
} else {
$role = "user";
}
$messages[] = array("role" => $role, "content" => $row->text);
}
// 添加新的用户对话到对话历史中
$messages[] = array("role" => "user", "content" => $question);
$payload = array(
"message" => array(
"text" => $messages
)
);

$json_string = json_encode(
array(
"header" => $header,
"parameter" => $parameter,
"payload" => $payload
)
);

return $json_string;

}
//鉴权方法
function assembleAuthUrl($method, $addr, $apiKey, $apiSecret)
{
if ($apiKey == "" && $apiSecret == "") { // 不鉴权
return $addr;
}

$ul = parse_url($addr); // 解析地址
if ($ul === false) { // 地址不对,也不鉴权
return $addr;
}

$timestamp = time();
$rfc1123_format = gmdate("D, d M Y H:i:s \G\M\T", $timestamp);
$signString = array("host: " . $ul["host"], "date: " . $rfc1123_format, $method . " " . $ul["path"] . " HTTP/1.1");
$sgin = implode("\n", $signString);
// print( $sgin);

$sha = hash_hmac('sha256', $sgin, $apiSecret, true);
//print("signature_sha:\n");
//print($sha);
$signature_sha_base64 = base64_encode($sha);

// 将API密钥、算法、头部信息和签名结果拼接成一个授权URL
$authUrl = "api_key=\"$apiKey\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"$signature_sha_base64\"";

// 对授权URL进行Base64编码,并添加到原始地址后面作为查询参数
$authAddr = $addr . '?' . http_build_query(
array(
'host' => $ul['host'],
'date' => $rfc1123_format,
'authorization' => base64_encode($authUrl),
)
);

return $authAddr;
}
}



NLP PHP api gpt 讯飞星火大模型
基于ID3算法和后剪枝的决策树实验
本地llama.cpp搭建中文llama-alpaca-13B模型记录
© 2020 Gina
Powered by hexo | Theme is blank
Title - Artist
0:00