为blog添加AI文章总结
📝 AI文章总结
点击下方按钮生成AI总结
使用AI总结文章,可能需要几秒钟
AI正在分析文章内容...
<br>
## 为什么要搞AI总结?
<br>因为之前AI刚刚起来的时候大家都在玩AI,我没有跟上大部队现在搞个来弥补一下.
<br>
## 怎么实现?
<br>我按照我的博客文件配置,详细如下
<br>需要修改config.php中的AI配置部分,以及ai.php中的API调用部分。
<br>ai.php文件
```php
<?php
include 'functions.php';
$config = load_config();
// 检查功能是否启用
if (!$config['enable_ai_summary']) {
header('HTTP/1.1 403 Forbidden');
echo json_encode(['error' => 'AI总结功能未启用']);
exit;
}
// 只允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['error' => '只支持POST请求']);
exit;
}
// 获取请求数据
$input = json_decode(file_get_contents('php://input'), true);
$content = $input['content'] ?? '';
$slug = $input['slug'] ?? '';
if (empty($content) || empty($slug)) {
echo json_encode(['error' => '内容或文章标识不能为空']);
exit;
}
// 检查API密钥
if (empty($config['ai_api_key'])) {
echo json_encode(['error' => '请先配置API密钥']);
exit;
}
try {
$summary = get_silicon_flow_summary($content, $config);
echo json_encode([
'success' => true,
'summary' => $summary,
'provider' => 'silicon_flow',
'model' => $config['ai_model']
]);
} catch (Exception $e) {
echo json_encode(['error' => 'AI总结失败: ' . $e->getMessage()]);
}
function get_silicon_flow_summary($content, $config) {
$clean_content = strip_tags($content);
$clean_content = preg_replace('/\s+/', ' ', $clean_content);
$clean_content = substr($clean_content, 0, 6000);
$prompt = "请用简洁的中文总结以下文章内容,要求:
1. 提取核心观点和关键信息
2. 总结长度控制在200字以内
3. 语言流畅自然,突出重点
4. 避免技术术语,用通俗易懂的语言表达
文章内容:
" . $clean_content;
$data = [
'model' => $config['ai_model'],
'messages' => [
[
'role' => 'user',
'content' => $prompt
]
],
'max_tokens' => $config['ai_max_tokens'],
'temperature' => $config['ai_temperature'],
'stream' => false
];
// 调用API
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $config['ai_api_url'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $config['ai_api_key'],
'Accept: application/json'
],
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_FOLLOWLOCATION => true
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
error_log("API请求: " . $config['ai_api_url']);
error_log("API响应状态: " . $http_code);
if ($curl_error) {
throw new Exception('API请求失败: ' . $curl_error);
}
if ($http_code !== 200) {
$error_data = json_decode($response, true);
$error_msg = 'HTTP错误: ' . $http_code;
if (isset($error_data['error']['message'])) {
$error_msg .= ' - ' . $error_data['error']['message'];
} elseif (isset($error_data['message'])) {
$error_msg .= ' - ' . $error_data['message'];
} else {
$error_msg .= ' - 响应: ' . substr($response, 0, 200);
}
throw new Exception($error_msg);
}
$result = json_decode($response, true);
if (!isset($result['choices'][0]['message']['content'])) {
error_log("完整的API响应: " . $response);
throw new Exception('API返回数据格式异常');
}
$summary_content = trim($result['choices'][0]['message']['content']);
if (empty($summary_content)) {
throw new Exception('AI返回了空内容');
}
return $summary_content;
}
?>
```
<br>config.php(AI配置,提一句这是我博客的总配置文件)
```php
'enable_ai_summary' => true,
'ai_api_provider' => ' API提供商',
'ai_api_key' => 'API密钥',
'ai_api_url' => 'API地址',
'ai_model' => '模型',
'ai_max_tokens' => 500,
'ai_temperature' => 0.7,
```
<br>下面的添加到文章详情页合适位置(AI总结显示位置)
```php
<!-- AI文章总结功能 -->
<?php if ($config['enable_ai_summary']): ?>
<div class="ai-summary-section" style="margin-top: 40px; padding: 20px; background: #f8f9fa; border-radius: var(--radius); border: 1px solid var(--border-color);">
<div class="ai-summary-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0; color: var(--text-color); font-size: 1.1rem;">🤖 AI文章总结</h3>
<button id="ai-summary-toggle" style="padding: 6px 12px; background: var(--text-color); color: white; border: none; border-radius: var(--radius); cursor: pointer; font-size: 0.9rem; transition: all 0.3s;">
展开总结
</button>
</div>
<div id="ai-summary-content" style="display: none;">
<div id="ai-summary-placeholder" style="text-align: center; padding: 20px; color: var(--light-text-color);">
<p>点击下方按钮生成AI总结</p>
<button id="ai-summary-generate" style="padding: 10px 20px; background: #4CAF50; color: white; border: none; border-radius: var(--radius); cursor: pointer; margin: 10px 0; transition: all 0.3s;">
开始AI总结
</button>
<p style="font-size: 0.8rem; margin-top: 10px;">使用AI总结文章,可能需要几秒钟</p>
</div>
<div id="ai-summary-result" style="display: none; padding: 15px; background: white; border-radius: var(--radius); border: 1px solid var(--border-color); line-height: 1.6;"></div>
<div id="ai-summary-error" style="display: none; padding: 15px; background: #ffebee; border-radius: var(--radius); border: 1px solid #f44336; color: #c62828;"></div>
<div id="ai-summary-loading" style="display: none; text-align: center; padding: 20px;">
<div style="display: inline-block; width: 20px; height: 20px; border: 2px solid #f3f3f3; border-top: 2px solid var(--text-color); border-radius: 50%; animation: spin 1s linear infinite;"></div>
<p style="margin: 10px 0 0 0; color: var(--light-text-color);">AI正在分析文章内容...</p>
</div>
</div>
</div>
<style>
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.ai-summary-section {
transition: all 0.3s ease;
}
#ai-summary-generate:hover {
background: #45a049 !important;
transform: translateY(-1px);
}
#ai-summary-toggle:hover {
opacity: 0.9;
transform: translateY(-1px);
}
#ai-summary-result {
animation: fadeIn 0.5s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
const toggleBtn = document.getElementById('ai-summary-toggle');
const contentDiv = document.getElementById('ai-summary-content');
const generateBtn = document.getElementById('ai-summary-generate');
const placeholderDiv = document.getElementById('ai-summary-placeholder');
const resultDiv = document.getElementById('ai-summary-result');
const errorDiv = document.getElementById('ai-summary-error');
const loadingDiv = document.getElementById('ai-summary-loading');
let isExpanded = false;
// 切换显示/隐藏
toggleBtn.addEventListener('click', function() {
isExpanded = !isExpanded;
contentDiv.style.display = isExpanded ? 'block' : 'none';
toggleBtn.textContent = isExpanded ? '收起总结' : '展开总结';
});
// 生成AI总结
generateBtn.addEventListener('click', function() {
// 获取文章内容
const articleContent = document.querySelector('.post-content').innerText;
const articleSlug = '<?php echo $post["slug"]; ?>';
// 显示加载中
placeholderDiv.style.display = 'none';
loadingDiv.style.display = 'block';
errorDiv.style.display = 'none';
resultDiv.style.display = 'none';
// 调用AI API - 修改为ai.php
fetch('<?php echo $config["site_url"]; ?>/ai.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: articleContent,
slug: articleSlug
})
})
.then(response => response.json())
.then(data => {
loadingDiv.style.display = 'none';
if (data.success) {
resultDiv.innerHTML = '<h4 style="margin-top: 0; color: var(--text-color); border-bottom: 1px solid var(--border-color); padding-bottom: 8px;">📝 总结内容</h4><div style="font-size: 0.95rem; line-height: 1.6;">' + data.summary + '</div>';
resultDiv.style.display = 'block';
placeholderDiv.style.display = 'none';
} else {
errorDiv.textContent = '总结失败: ' + (data.error || '未知错误');
errorDiv.style.display = 'block';
placeholderDiv.style.display = 'block';
}
})
.catch(error => {
loadingDiv.style.display = 'none';
errorDiv.textContent = '请求失败: ' + error;
errorDiv.style.display = 'block';
placeholderDiv.style.display = 'block';
});
});
});
</script>
<?php endif; ?>
```
## 结语
<br>就这样我的博客就支持了AI总结,如果你也想添加一个AI总结功能,或许我这篇文章能帮助到你.