本文目录导读:

在PHP项目中集成GPT(如OpenAI的GPT-3.5或GPT-4)主要有以下几种方式,以下是完整的实现指南:
使用OpenAI官方API(最推荐)
安装依赖
composer require openai-php/client
基本实现代码
<?php
require 'vendor/autoload.php';
use OpenAI\Client;
class GPTIntegration {
private $client;
public function __construct(string $apiKey) {
$this->client = OpenAI::client($apiKey);
}
/**
* 发送聊天请求
*/
public function chat(array $messages, array $options = []): string {
try {
$response = $this->client->chat()->create([
'model' => $options['model'] ?? 'gpt-3.5-turbo',
'messages' => $messages,
'temperature' => $options['temperature'] ?? 0.7,
'max_tokens' => $options['max_tokens'] ?? 1500,
'top_p' => $options['top_p'] ?? 1.0,
'frequency_penalty' => $options['frequency_penalty'] ?? 0.0,
'presence_penalty' => $options['presence_penalty'] ?? 0.0,
]);
return $response->choices[0]->message->content;
} catch (Exception $e) {
return "错误: " . $e->getMessage();
}
}
/**
* 简单的问答
*/
public function ask(string $prompt): string {
return $this->chat([
['role' => 'user', 'content' => $prompt]
]);
}
/**
* 流式响应(实时输出)
*/
public function streamChat(array $messages, callable $callback): void {
$stream = $this->client->chat()->createStreamed([
'model' => 'gpt-3.5-turbo',
'messages' => $messages,
]);
foreach ($stream as $response) {
$text = $response->choices[0]->delta->content ?? '';
if ($text) {
call_user_func($callback, $text);
}
}
}
}
使用示例
// 初始化
$gpt = new GPTIntegration('你的OpenAI API密钥');
// 简单问答
$answer = $gpt->ask("什么是PHP?");
echo $answer;
// 多轮对话
$messages = [
['role' => 'system', 'content' => '你是一个PHP专家助手'],
['role' => 'user', 'content' => '如何在PHP中处理文件上传?'],
['role' => 'assistant', 'content' => '使用$_FILES超全局变量...'],
['role' => 'user', 'content' => '请给出具体代码示例']
];
$response = $gpt->chat($messages, [
'model' => 'gpt-4',
'temperature' => 0.3
]);
// 流式输出
echo "思考过程:";
$gpt->streamChat($messages, function($text) {
echo $text;
ob_flush();
flush();
});
使用cURL直接调用API
<?php
class DirectGPTClient {
private $apiKey;
private $apiUrl = 'https://api.openai.com/v1/chat/completions';
public function __construct(string $apiKey) {
$this->apiKey = $apiKey;
}
public function ask(string $prompt, array $options = []): string {
$data = [
'model' => $options['model'] ?? 'gpt-3.5-turbo',
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'temperature' => $options['temperature'] ?? 0.7,
'max_tokens' => $options['max_tokens'] ?? 1500
];
$ch = curl_init($this->apiUrl);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey
],
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_TIMEOUT => 60
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("API请求失败: HTTP $httpCode");
}
$result = json_decode($response, true);
return $result['choices'][0]['message']['content'] ?? '';
}
}
安全性最佳实践
<?php
class SecureGPTIntegration {
private $apiKey;
private $rateLimiter;
public function __construct() {
// 从环境变量获取API密钥
$this->apiKey = getenv('OPENAI_API_KEY');
// 初始化速率限制器(需要先安装)
// composer require predis/predis
$this->rateLimiter = new \Predis\Client();
}
/**
* 安全地发送请求
*/
public function safeChat(string $userInput): string {
// 1. 输入验证和清理
$cleanedInput = $this->sanitizeInput($userInput);
// 2. 速率限制检查
if (!$this->checkRateLimit()) {
return "请求过于频繁,请稍后再试。";
}
// 3. 内容过滤
if ($this->containsSensitiveContent($cleanedInput)) {
return "输入包含不允许的内容。";
}
// 4. Token预算控制
if (strlen($cleanedInput) > 4000) {
return "输入太长了,请缩短。";
}
// 5. 构建安全的消息
$messages = [
[
'role' => 'system',
'content' => '你是一个安全的AI助手,不能回答任何违法、有害或不道德的问题。'
],
[
'role' => 'user',
'content' => $cleanedInput
]
];
return $this->callAPI($messages);
}
private function sanitizeInput(string $input): string {
// 移除危险字符
$input = strip_tags($input);
$input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
// 限制长度
return mb_substr($input, 0, 5000);
}
private function checkRateLimit(): bool {
$ip = $_SERVER['REMOTE_ADDR'];
$key = "gpt_rate_limit:$ip";
$current = $this->rateLimiter->incr($key);
if ($current === 1) {
$this->rateLimiter->expire($key, 60); // 60秒过期
}
return $current <= 20; // 每分钟最多20次请求
}
private function containsSensitiveContent(string $input): bool {
$blockedPatterns = [
'/黑客/i',
'/攻击方法/i',
'/制造武器/i',
'/违法/i'
];
foreach ($blockedPatterns as $pattern) {
if (preg_match($pattern, $input)) {
return true;
}
}
return false;
}
private function callAPI(array $messages): string {
// 实际API调用代码...
return "API响应";
}
}
Laravel项目集成示例
创建服务提供者
// app/Providers/OpenAIServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use OpenAI\Client;
class OpenAIServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(Client::class, function ($app) {
return OpenAI::client(config('services.openai.api_key'));
});
}
}
创建Facade
// app/Facades/GPT.php
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class GPT extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'gpt';
}
}
控制器中使用
<?php
namespace App\Http\Controllers;
use OpenAI\Client;
use Illuminate\Http\Request;
class ChatController extends Controller
{
private $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function chat(Request $request)
{
$request->validate([
'message' => 'required|string|max:1000'
]);
$response = $this->client->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'user', 'content' => $request->message]
]
]);
return response()->json([
'reply' => $response->choices[0]->message->content,
'usage' => $response->usage->toArray()
]);
}
}
配置文件示例
// config/services.php
return [
'openai' => [
'api_key' => env('OPENAI_API_KEY'),
'organization' => env('OPENAI_ORGANIZATION'), // 可选
'default_model' => env('OPENAI_MODEL', 'gpt-3.5-turbo'),
'max_tokens' => env('OPENAI_MAX_TOKENS', 1500),
'temperature' => env('OPENAI_TEMPERATURE', 0.7),
]
];
环境变量配置
OPENAI_API_KEY=sk-your-api-key-here OPENAI_ORGANIZATION=org-your-org-id OPENAI_MODEL=gpt-3.5-turbo OPENAI_MAX_TOKENS=2000 OPENAI_TEMPERATURE=0.7
注意事项
- API密钥安全:永远不要将API密钥硬编码到代码中,使用环境变量
- 成本控制:设置合适的token限制和速率限制
- 错误处理:实现完善的异常捕获和回退机制
- 缓存策略:对常见问题实现缓存以减少API调用
- 隐私合规:不要将用户敏感数据发送到外部API
集成GPT到PHP项目时,建议先从小功能开始,逐步扩展,并密切监控API使用成本。
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播