在当今AI技术快速发展的背景下,将AI能力集成到PHP项目中已成为提升开发效率和产品智能化的关键。OpenAI兼容API因其标准化接口和广泛支持度,成为PHP开发者首选的AI集成方案。本文将详细介绍如何在PHP环境中使用兼容OpenAI规范的API服务。
OpenAI兼容API为PHP开发者提供了三大核心价值:
提示:选择兼容API时,务必验证其是否完整实现了/v1/chat/completions等核心端点。
国内PHP项目集成AI服务时需特别注意:
| 服务特性 | 官方OpenAI | dkapi | 其他兼容服务 |
|---|---|---|---|
| 接口兼容性 | 100% | 95%+ | 80%-90% |
| 国内访问速度 | 不稳定 | 稳定 | 一般 |
| PHP SDK支持度 | 完善 | 兼容 | 部分兼容 |
| 注册难度 | 高 | 低 | 中等 |
php复制// 模拟注册流程
$apiKey = 'sk-xxxxxxxx'; // 从控制台获取的实际Key
$baseUrl = 'https://new.ch-at.pw';
bash复制composer require openai-php/client
php复制use OpenAI\Client;
$client = new Client([
'api_key' => $apiKey,
'base_uri' => $baseUrl
]);
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'user', 'content' => '用PHP写个冒泡排序']
]
]);
php复制// app/Providers/AiServiceProvider.php
public function register()
{
$this->app->singleton('openai', function($app) {
return new Client([
'api_key' => config('services.openai.key'),
'base_uri' => config('services.openai.url')
]);
});
}
env复制OPENAI_KEY=your_api_key
OPENAI_URL=https://new.ch-at.pw
php复制public function askAi(Request $request)
{
$response = app('openai')->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'user', 'content' => $request->input('question')]
]
]);
return response()->json([
'answer' => $response['choices'][0]['message']['content']
]);
}
php复制class ChatbotService
{
private $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function respondTo($message, $context = [])
{
$messages = [
['role' => 'system', 'content' => '你是一个专业的客服助手'],
['role' => 'user', 'content' => $message]
];
if (!empty($context)) {
$messages = array_merge($messages, $context);
}
$response = $this->client->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => $messages,
'temperature' => 0.7
]);
return $response['choices'][0]['message']['content'];
}
}
php复制function generateSeoContent($keywords, $wordCount = 800)
{
$prompt = "根据以下关键词生成一篇{$wordCount}字左右的SEO优化文章:\n";
$prompt .= implode(', ', $keywords);
$response = $client->chat()->create([
'model' => 'gpt-4',
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'max_tokens' => 2000
]);
return [
'title' => extractTitle($response),
'content' => $response['choices'][0]['message']['content'],
'keywords' => extractKeywords($response)
];
}
php复制$retry = 0;
$maxRetries = 3;
$response = null;
while ($retry < $maxRetries) {
try {
$response = $client->chat()->create([
// 参数配置
], [
'timeout' => 30,
'connect_timeout' => 10
]);
break;
} catch (RequestException $e) {
$retry++;
if ($retry >= $maxRetries) {
throw $e;
}
sleep(pow(2, $retry)); // 指数退避
}
}
php复制class AiCache
{
private $cache;
private $client;
public function __construct(CacheInterface $cache, Client $client)
{
$this->cache = $cache;
$this->client = $client;
}
public function getCachedResponse($prompt, $expire = 3600)
{
$key = 'ai_response_'.md5($prompt);
if ($this->cache->has($key)) {
return $this->cache->get($key);
}
$response = $this->client->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'user', 'content' => $prompt]
]
]);
$this->cache->set($key, $response, $expire);
return $response;
}
}
php复制function sanitizeInput($input)
{
$input = htmlspecialchars($input, ENT_QUOTES);
// 移除敏感关键词
$blacklist = ['密码', '信用卡', 'admin'];
foreach ($blacklist as $word) {
$input = str_ireplace($word, '[REDACTED]', $input);
}
// 限制长度
return mb_substr($input, 0, 1000);
}
php复制class AiLogger
{
public function logRequest($request, $response, $context = [])
{
$logEntry = [
'timestamp' => date('Y-m-d H:i:s'),
'request' => [
'model' => $request['model'] ?? null,
'prompt' => substr($request['messages'][0]['content'] ?? '', 0, 200),
'tokens' => $request['max_tokens'] ?? null
],
'response' => [
'tokens_used' => $response['usage']['total_tokens'] ?? null,
'response_time' => $context['response_time'] ?? null
],
'metadata' => $context
];
file_put_contents('ai_requests.log', json_encode($logEntry)."\n", FILE_APPEND);
}
}
建议监控以下关键指标:
php复制class RateLimiter
{
private $maxRequestsPerMinute = 30;
public function checkLimit()
{
$count = Cache::increment('ai_request_count');
if ($count === 1) {
Cache::put('ai_request_count', 1, now()->addMinute());
}
return $count <= $this->maxRequestsPerMinute;
}
}
code复制├── app/
│ ├── Services/
│ │ ├── AiService.php
│ │ ├── CacheService.php
│ ├── Http/
│ │ ├── Controllers/
│ │ │ ├── AiController.php
├── config/
│ ├── ai.php
├── resources/
│ ├── views/
│ │ ├── ai/
│ │ │ ├── chat.blade.php
AiService.php:
php复制class AiService
{
private $client;
private $cache;
public function __construct(Client $client, CacheInterface $cache)
{
$this->client = $client;
$this->cache = $cache;
}
public function chat($messages, $model = 'gpt-3.5-turbo')
{
$cacheKey = 'ai_chat_'.md5(json_encode($messages));
if ($this->cache->has($cacheKey)) {
return $this->cache->get($cacheKey);
}
$response = $this->client->chat()->create([
'model' => $model,
'messages' => $messages,
'temperature' => 0.7,
'max_tokens' => 1000
]);
$this->cache->put($cacheKey, $response, now()->addHours(1));
return $response;
}
}
php复制try {
$response = $client->chat()->create([...]);
} catch (RequestException $e) {
if ($e->getCode() === 0) {
// 网络连接问题
Log::error('AI服务网络连接失败: '.$e->getMessage());
return back()->withError('服务暂时不可用,请稍后重试');
}
throw $e;
}
php复制function filterContent($content)
{
$bannedPatterns = [
'/暴力内容/iu',
'/仇恨言论/iu',
'/敏感政治词汇/iu'
];
foreach ($bannedPatterns as $pattern) {
$content = preg_replace($pattern, '[内容已过滤]', $content);
}
return $content;
}
在实际PHP项目开发中,合理使用OpenAI兼容API可以显著提升开发效率和产品智能化水平。关键在于选择稳定的服务提供商、实现良好的架构设计,并建立完善的错误处理和监控机制。