30 行 PHP 调用硅基流动 API 实现网页客服系统
一、硅基流动平台准备
访问 https://cloud.siliconflow.cn 完成注册,实名认证后,点击左侧菜单"API 密钥"创建专属 Key,这是后续调用的唯一凭证。
在"模型广场"中选择适合客服场景的模型。经实测,以下模型性价比突出:
DeepSeek-V3:响应速度快,通用问答能力强Qwen/Qwen2.5-7B-Instruct:中文优化好,适合电商场景Pro/deepseek-ai/DeepSeek-R1:复杂问题推理能力优秀
二、极简架构设计
摒弃传统 MVC 架构,采用"单文件 PHP+ 静态 HTML"的极端简洁模式:
- 后端:30 行 PHP 负责接收请求、调用硅基流动 API、返回流式响应
- 前端:原生 HTML+JavaScript 实现聊天界面和流式输出
- 通信:AJAX POST 请求,EventSource 接收流式数据
这种设计不仅部署方便(丢到任意 PHP 空间即可运行),更避免了框架依赖和性能开销。
三、核心 PHP 代码实现
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$apiKey = 'sk-your-key-here'; // 从硅基流动控制台获取
$model = 'deepseek-ai/DeepSeek-V3'; // 根据需求调整
$message = $_POST['msg'] ?? '';
$history = $_POST['history'] ?? '[]';
$ch = curl_init('https://api.siliconflow.cn/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_WRITEFUNCTION => function($ch, $data) {
echo "data: " . base64_encode($data) . "\n\n";
ob_flush();
flush();
return strlen($data);
},
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode([
'model' => $model,
'messages' => array_merge(json_decode($history, true), [
['role' => 'user', 'content' => $message]
]),
'stream' => true,
'max_tokens' => 2048,
'temperature' => 0.7
])
]);
curl_exec($ch);
curl_close($ch);
?>
代码要点解析:
- 设置
text/event-stream头实现 SSE 流式传输 CURLOPT_WRITEFUNCTION实时转发 API 响应,避免内存积压base64_encode处理中文编码问题,确保传输稳定history参数实现多轮对话上下文记忆
四、前端界面实现
<!DOCTYPE html>
<html>
<head>
<title>智能客服</title>
<meta charset="utf-8">
<style>
body { margin: 0; background: #1a1a1a; color: #fff; font-family: monospace; }
#chat { height: 90vh; overflow-y: auto; padding: 20px; }
.msg { margin: 10px 0; }
.user { text-align: right; color: #4af; }
.bot { color: #0f0; }
#input { position: fixed; bottom: 0; width: 100%; padding: 10px; background: #333; }
#msgInput { width: 80%; padding: 8px; background: #222; color: #fff; border: none; }
button { padding: 8px 20px; background: #4af; color: #fff; border: none; cursor: pointer; }
</style>
</head>
<body>
<div id="chat"></div>
<div id="input">
<input type="text" id="msgInput" placeholder="输入问题...">
<button onclick="send()">发送</button>
</div>
<script>
let history = [];
function send() {
const input = document.getElementById('msgInput');
const msg = input.value.trim();
if (!msg) return;
appendMsg('user', msg);
input.value = '';
const source = new EventSource(`chat.php?action=stream`);
source.onmessage = e => {
const data = JSON.parse(atob(e.data));
if (data.choices?.[0].delta.content) {
appendMsg('bot', data.choices[0].delta.content, true);
}
};
}
function appendMsg(role, text, stream = false) {
const chat = document.getElementById('chat');
if (!stream || !chat.lastElementChild?.classList.contains('bot')) {
chat.innerHTML += `<div class="${role}">${text}</div>`;
} else {
chat.lastElementChild.textContent += text;
}
chat.scrollTop = chat.scrollHeight;
}
</script>
</body>
</html>
界面设计原则:
- 暗色主题减少视觉疲劳
- 流式输出模拟真人打字效果
- 无依赖设计确保兼容性
五、部署与优化技巧
部署步骤:
- 将
chat.php和index.html上传到支持 PHP 的服务器 - 修改
$apiKey为你的实际密钥 - 访问
index.html即可使用
性能优化:
- 缓存高频问题:对"运费多少"、"如何退换货"等标准问题,直接在 PHP 中建立问答映射表,避免 API 调用
- 批量处理:硅基流动 API 支持批量请求,可合并多个用户问题提升吞吐量
- 降级策略:API 超时时返回预设话术,保障用户体验
成本控制:
- 设置
max_tokens限制避免 Token 浪费 - 使用
temperature=0.7平衡回答质量与消耗 - 监控 Token 用量,硅基流动控制台提供实时统计
六、扩展方向
- 知识库增强:通过 RAG 技术接入产品文档,提升回答精准度
- 多轮对话优化:在
history中实现摘要压缩,支持更长上下文 - 情绪识别:调用硅基流动的 Embedding API 识别用户情绪,自动转人工
- 数据统计:接入轻量级日志系统分析高频问题,指导业务优化
结语
30 行 PHP 代码实现的不仅是功能,更是一种"极致简约"的开发哲学。在 AI 时代,开发者应将精力集中在业务逻辑而非底层架构,让专业平台处理模型部署与优化。硅基流动完善的 API 生态和慷慨的免费额度,为个人开发者提供了前所未有的创新空间。
这套代码已在多个轻量级项目中验证,从个人博客答疑到小程序客服,均表现出稳定可靠。将其部署到你网站根目录,再配一个子域名(如 chat.yourdomain.com),即可对外提供专业服务。后续可逐步增加知识库、工单系统等模块,但核心逻辑永远保持这 30 行代码的简洁与高效。
记住:最好的代码不是最长的,而是最能解决问题的。当你的客服系统跑起来那一刻,你会深刻理解这句话的含义。


