PHP接入openai sdk
PHP可以通过第三方库或直接调用API的方式对接OpenAI接口。以下是具体方案:
一、推荐方案:使用社区维护的PHP SDK
推荐库:openai-php/client
官方地址:https://github.com/openai-php/client
安装方式:
BASH
composer require openai-php/client
代码示例:
PHP
use OpenAI\Client;
$client = OpenAI::client('your-api-key');
$response = $client->chat()->create([
'model' => 'gpt-4',
'messages' => [['role' => 'user', 'content' => 'Hello!']]
]);
二、替代方案:直接调用API
PHP
// 使用GuzzleHTTP发送请求示例
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.openai.com/v1/chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . 'your-api-key',
'Content-Type' => 'application/json',
],
'json' => [
'model' => 'gpt-4',
'messages' => [['role' => 'user', 'content' => 'Hello!']]
]
]);
三、注意事项
API密钥需从OpenAI平台获取
需要处理HTTPS请求和JSON数据解析
建议添加频率限制和异常处理[2]