PHP code example of ljguo-latex / openai-php
1. Go to this page and download the library: Download ljguo-latex/openai-php library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ljguo-latex / openai-php example snippets
use OpenAI\OpenAI;
$client = OpenAI::client(
apiKey: 'sk-...',
baseUrl: 'https://api.openai.com/v1', // 可选,默认值
defaultModel: 'gpt-4o', // 可选
);
$response = $client->chat()
->message('法国的首都是哪里?')
->send();
echo $response->content(); // "巴黎"
$response = $client->chat()
->model('gpt-4o')
->system('你是一个有用的助手。')
->message('PHP 是什么?')
->temperature(0.7)
->maxTokens(512)
->send();
echo $response->content();
echo $response->finishReason(); // "stop"
echo $response->usage->totalTokens;
$response = $client->chat()
->system('你是一个有用的助手。')
->user('我叫小明。')
->assistant('你好,小明!')
->user('我叫什么名字?')
->send();
echo $response->content(); // "你叫小明。"
$client->chat()
->model('gpt-4o')
->message('写一首关于春天的诗')
->stream(function (string $chunk) {
echo $chunk;
ob_flush();
flush();
});
use OpenAI\Responses\UsageResponse;
$client->chat()
->model('gpt-4o')
->message('写一首关于春天的诗')
->stream(function (string $chunk, ?UsageResponse $usage = null) {
echo $chunk;
if ($usage !== null) {
echo "\nPrompt tokens: " . $usage->promptTokens;
echo "\nCompletion tokens: " . $usage->completionTokens;
echo "\nTotal tokens: " . $usage->totalTokens;
}
});
// 普通请求
$response = $client->completions()
->model('gpt-3.5-turbo-instruct')
->prompt('从前有座山')
->temperature(0.8)
->maxTokens(100)
->send();
echo $response->text();
// 流式输出
$client->completions()
->prompt('从前有座山')
->stream(function (string $chunk, ?\OpenAI\Responses\UsageResponse $usage = null) {
echo $chunk;
if ($usage !== null) {
echo "\nTotal tokens: " . $usage->totalTokens;
}
});
// 单条输入
$response = $client->embeddings()
->model('text-embedding-3-small')
->input('你好,世界!')
->send();
$vector = $response->embedding(); // float[]
// 多条输入
$response = $client->embeddings()
->input(['Hello', 'World'])
->send();
foreach ($response->data as $item) {
echo "第 {$item->index} 条:" . count($item->embedding) . " 维\n";
}
// 列出所有可用模型
$list = $client->models()->list();
print_r($list->ids()); // ['gpt-4o', 'gpt-3.5-turbo', ...]
// 获取指定模型详情
$model = $client->models()->retrieve('gpt-4o');
echo $model->id;
echo $model->ownedBy;
$client = OpenAI::client(
apiKey: 'local-key',
baseUrl: 'http://localhost:11434/v1',
defaultModel: 'llama3',
);
use OpenAI\Exceptions\ApiException;
try {
$response = $client->chat()->message('你好')->send();
} catch (ApiException $e) {
echo $e->getMessage(); // API 错误信息
echo $e->getStatusCode(); // HTTP 状态码
if ($e->isRateLimitError()) {
// 处理 429 限流
} elseif ($e->isAuthenticationError()) {
// 处理 401 认证失败
} elseif ($e->isServerError()) {
// 处理 5xx 服务端错误
}
}
use OpenAI\Client;
$client = new Client(
apiKey: 'sk-...',
baseUrl: 'https://api.openai.com/v1',
defaultModel: 'gpt-4o',
timeout: 60,
httpOptions: [], // Guzzle 配置项
);
bash
composer