我来帮你了解PHP项目中GPT(生成式预训练Transformer)与文本生成的相关内容。

PHP中实现GPT文本生成的主要方式
使用OpenAI API(推荐)
<?php
class GPTTextGenerator {
private $apiKey;
private $apiUrl = 'https://api.openai.com/v1/chat/completions';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function generate($prompt, $options = []) {
$data = [
'model' => $options['model'] ?? 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => '你是一个有用的AI助手'],
['role' => 'user', 'content' => $prompt]
],
'temperature' => $options['temperature'] ?? 0.7,
'max_tokens' => $options['max_tokens'] ?? 1000
];
$ch = curl_init($this->apiUrl);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $this->apiKey,
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode($data)
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
$result = json_decode($response, true);
return $result['choices'][0]['message']['content'];
}
return false;
}
}
// 使用示例
$generator = new GPTTextGenerator('your-api-key-here');
$text = $generator->generate('写一首关于春天的诗');
echo $text;
使用Composer包管理
composer require openai-php/client
require 'vendor/autoload.php';
use OpenAI\Client;
$client = OpenAI::client('your-api-key');
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => '你是一个专业的写作助手'],
['role' => 'user', 'content' => '写一篇关于人工智能的短文']
]
]);
echo $response->choices[0]->message->content;
文本生成功能实现
<?php
class AdvancedTextGenerator {
private $gpt;
public function __construct($apiKey) {
$this->gpt = new GPTTextGenerator($apiKey);
}
// 文章生成
public function generateArticle($topic, $length = 'short') {
$prompts = [
'short' => "请写一篇关于{$topic}的简短介绍(200字以内)",
'medium' => "请写一篇关于{$topic}的详细文章(500字左右)",
'long' => "请写一篇关于{$topic}的深度分析文章(1000字以上)"
];
return $this->gpt->generate($prompts[$length] ?? $prompts['short']);
}
// 内容总结
public function summarize($text) {
$prompt = "请总结以下文本的核心要点:\n\n" . $text;
return $this->gpt->generate($prompt, ['temperature' => 0.3]);
}
// 创意写作
public function creativeWrite($genre, $keywords) {
$prompt = "请用{$genre}风格创作一段包含以下关键词的文字:\n";
$prompt .= implode(', ', $keywords);
return $this->gpt->generate($prompt, ['temperature' => 0.9]);
}
// 翻译功能
public function translate($text, $targetLanguage = '中文') {
$prompt = "请将以下文本翻译成{$targetLanguage}:\n\n" . $text;
return $this->gpt->generate($prompt, ['temperature' => 0.3]);
}
}
本地文本生成(不依赖API)
<?php
class LocalTextGenerator {
private $markovChain = [];
private $ngrams = [];
public function train($texts) {
foreach ($texts as $text) {
$words = preg_split('/\s+/', $text);
for ($i = 0; $i < count($words) - 1; $i++) {
$word = $words[$i];
$nextWord = $words[$i + 1];
if (!isset($this->markovChain[$word])) {
$this->markovChain[$word] = [];
}
$this->markovChain[$word][] = $nextWord;
}
}
}
public function generate($seed, $length = 50) {
$current = $seed;
$result = [$current];
for ($i = 0; $i < $length; $i++) {
if (!isset($this->markovChain[$current])) {
break;
}
$next = $this->markovChain[$current][array_rand($this->markovChain[$current])];
$result[] = $next;
$current = $next;
}
return implode(' ', $result);
}
}
最佳实践建议
<?php
trait GPTUsageOptimization {
// 缓存机制
private $cache = [];
public function getCachedOrGenerate($key, $prompt) {
if (isset($this->cache[$key])) {
return $this->cache[$key];
}
$result = $this->generate($prompt);
$this->cache[$key] = $result;
// 清理旧缓存
if (count($this->cache) > 100) {
array_shift($this->cache);
}
return $result;
}
// 重试机制
public function generateWithRetry($prompt, $maxRetries = 3) {
for ($i = 0; $i < $maxRetries; $i++) {
try {
$result = $this->generate($prompt);
if ($result !== false) {
return $result;
}
} catch (Exception $e) {
if ($i === $maxRetries - 1) {
throw $e;
}
sleep(pow(2, $i)); // 指数退避
}
}
return false;
}
// 内容过滤
public function sanitizeOutput($text) {
// 移除敏感内容
$blockedPatterns = [
'/\b(暴力|色情|赌博)\b/u',
// 添加更多过滤规则
];
foreach ($blockedPatterns as $pattern) {
$text = preg_replace($pattern, '[已过滤]', $text);
}
return strip_tags($text);
}
}
完整示例:文章生成器
<?php
class ArticleGenerator {
use GPTUsageOptimization;
private $gpt;
public function __construct($apiKey) {
$this->gpt = new GPTTextGenerator($apiKey);
}
public function createBlogPost($topic, $tone = 'informative') {
$prompt = $this->buildPrompt($topic, $tone);
$content = $this->generateWithRetry($prompt);
return [
'title' => $this->extractTitle($content),
'content' => $content,
'generated_at' => date('Y-m-d H:i:s')
];
}
private function buildPrompt($topic, $tone) {
$prompts = [
'informative' => "请写一篇关于{$topic}的知识性文章",
'persuasive' => "请写一篇关于{$topic}的说服性文章",
'entertaining' => "请写一篇关于{$topic}的趣味性文章"
];
return $prompts[$tone] ?? $prompts['informative'];
}
private function extractTitle($content) {
preg_match('/^#\s+(.+)$/m', $content, $matches);
return $matches[1] ?? '无标题文章';
}
}
使用建议:
- API密钥安全:将API密钥存储在环境变量或配置文件中
- 速率限制:注意API的调用频率限制
- 成本控制:设置max_tokens限制以避免过高费用
- 错误处理:实现完善的错误处理和日志记录
- 缓存策略:对重复请求使用缓存审核**:添加必要的内容过滤机制
需要更具体的实现方案吗?比如特定类型的文本生成或特定的应用场景?