对接ChatGPT接口需要进行以下步骤:
-
安装Swoole扩展和PHP cURL扩展。
-
在项目中引入
composer require guzzlehttp/guzzle
来安装 Guzzle HTTP客户端。 -
编写HTTP请求代码调用ChatGPT接口,示例代码如下:
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://api.openai.com/v1/engines/davinci-codex/completions', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $your_api_key,
],
'json' => [
'prompt' => 'Hello,',
'temperature' => 0.5,
'max_tokens' => 60,
'n' => 1,
'stop' => '.',
],
]);
if ($res->getStatusCode() == 200) {
$response = json_decode($res->getBody(), true);
echo $response['choices'][0]['text'];
}
在此示例代码中,我们使用 Guzzle HTTP客户端库来发送HTTP请求。请求的头部包括内容类型(Content-Type)和您的API密钥。请求主体包括指定的提示(prompt)和其他参数,如温度(temperature),最大标记数(max tokens)和停止标记(stop tokens)。我们可以使用返回的响应获取生成的文本。
- 将以上代码集成到Swoole项目中,以触发ChatGPT生成文本的HTTP请求,并将响应发送回客户端。
示例代码如下:
$server = new Swoole\HTTP\Server("127.0.0.1", 9501);
$server->on("request", function ($req, $res) {
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://api.openai.com/v1/engines/davinci-codex/completions', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $your_api_key,
],
'json' => [
'prompt' => 'Hello,',
'temperature' => 0.5,
'max_tokens' => 60,
'n' => 1,
'stop' => '.',
],
]);
if ($res->getStatusCode() == 200) {
$response = json_decode($res->getBody(), true);
$generated_text = $response['choices'][0]['text'];
$res->end($generated_text);
} else {
$res->end("Error: " . $res->getStatusCode());
}
});
$server->start();
在此示例代码中,我们创建了一个Swoole HTTP服务器,并在“request”事件处理程序中发送了HTTP请求。我们从响应中获取生成的文本,并将文本发送回客户端。如果请求失败,则向客户端发送错误消息。
以上就是在PHP中使用Swoole和ChatGPT接口集成的步骤。