原文使用的 www.simsimi.com 網頁版介面已停止公開 API 服務,且需要 Cookie/CSRF Token 複雜流程。現代開發應使用 官方 SimSimi API(需申請 API Key)或替代方案:
<?php
class SimSimiClient
{
private string $apiKey;
private string $baseUrl = 'https://api.simsimi.com/v2/';
private int $timeout = 10;
private string $language = 'zh'; // zh, en, ko, jp 等
public function __construct(string $apiKey, string $language = 'zh')
{
$this->apiKey = $apiKey;
$this->language = $language;
}
/**
* 發送訊息並取得回覆
* @param string $text 用戶輸入文字
* @param string|null $sessionId 會話 ID(可選,用於上下文連續)
* @return array ['text' => 回覆文字, 'session_id' => 會話ID, 'success' => bool]
*/
public function talk(string $text, ?string $sessionId = null): array
{
$payload = [
'utext' => $text,
'lang' => $this->language,
];
if ($sessionId) {
$payload['session_id'] = $sessionId;
}
$ch = curl_init($this->baseUrl . 'talk');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'x-api-key: ' . $this->apiKey,
],
CURLOPT_SSL_VERIFYPEER => true,
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($errno !== CURLE_OK) {
return ['success' => false, 'error' => "cURL error: " . curl_error($ch)];
}
if ($httpCode !== 200) {
return ['success' => false, 'error' => "HTTP {$httpCode}: {$response}"];
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return ['success' => false, 'error' => 'Invalid JSON response'];
}
// 官方回應格式:{ "atext": "回覆文字", "session_id": "xxx" }
return [
'success' => true,
'text' => $data['atext'] ?? '',
'session_id' => $data['session_id'] ?? null,
];
}
}
// 使用範例
$client = new SimSimiClient('YOUR_API_KEY', 'zh');
$response = $client->talk('你好,今天天氣如何?');
if ($response['success']) {
echo "小黃雞:{$response['text']}\n";
// 保存 session_id 供下輪對話使用
$sessionId = $response['session_id'];
} else {
echo "錯誤:{$response['error']}\n";
}
?>
<?php
class GptChatBot
{
private string $apiKey;
private string $model = 'gpt-3.5-turbo';
private array $systemPrompt = [
'role' => 'system',
'content' => '你是一個友善、幽默的中文聊天機器人「小黃雞」,用繁體中文回覆,語氣輕鬆可愛。'
];
public function __construct(string $apiKey, string $model = 'gpt-3.5-turbo')
{
$this->apiKey = $apiKey;
$this->model = $model;
}
public function chat(array $messages, array $options = []): array
{
$payload = array_merge([
'model' => $this->model,
'messages' => array_merge([$this->systemPrompt], $messages),
'temperature' => 0.8,
'max_tokens' => 500,
], $options);
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey,
],
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
curl_close($ch);
if ($errno !== CURLE_OK) {
return ['success' => false, 'error' => curl_error($ch)];
}
$data = json_decode($response, true);
if (isset($data['error'])) {
return ['success' => false, 'error' => $data['error']['message']];
}
return [
'success' => true,
'text' => $data['choices'][0]['message']['content'] ?? '',
'usage' => $data['usage'] ?? null,
];
}
}
// 使用:維護對話歷史
$bot = new GptChatBot('YOUR_OPENAI_KEY');
$history = [];
$userInput = '你好!';
$history[] = ['role' => 'user', 'content' => $userInput];
$response = $bot->chat($history);
if ($response['success']) {
$history[] = ['role' => 'assistant', 'content' => $response['text']];
echo $response['text'];
}
?>
<?php
class OllamaChatBot
{
private string $baseUrl = 'https://localhost:11434';
private string $model = 'llama3:8b';
public function chat(string $prompt, array $options = []): array
{
$payload = array_merge([
'model' => $this->model,
'prompt' => $prompt,
'stream' => false,
], $options);
$ch = curl_init($this->baseUrl . '/api/generate');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120, // 本地推理較慢
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
return [
'success' => isset($data['response']),
'text' => $data['response'] ?? '',
];
}
}
// 需先安裝 Ollama 並 pull 模型:ollama pull llama3:8b
?>
<?php
// Line Bot Webhook 入口
require 'vendor/autoload.php';
use LINE\LINEBot\HTTPClient\CurlHTTPClient;
use LINE\LINEBot;
use LINE\LINEBot\MessageBuilder\TextMessageBuilder;
$channelSecret = 'YOUR_CHANNEL_SECRET';
$channelAccessToken = 'YOUR_CHANNEL_ACCESS_TOKEN';
$httpClient = new CurlHTTPClient($channelAccessToken);
$bot = new LINEBot($httpClient, ['channelSecret' => $channelSecret]);
$signature = $_SERVER['HTTP_X_LINE_SIGNATURE'] ?? '';
$body = file_get_contents('php://input');
try {
$events = $bot->parseEventRequest($body, $signature);
foreach ($events as $event) {
if ($event instanceof \LINE\LINEBot\Event\MessageEvent\TextMessage) {
$userText = $event->getText();
$replyToken = $event->getReplyToken();
// 呼叫聊天機器人(SimSimi/GPT/Ollama)
$botResponse = getBotResponse($userText); // 你的實作
$bot->replyMessage($replyToken, new TextMessageBuilder($botResponse['text']));
}
}
} catch (\LINE\LINEBot\Exception\InvalidSignatureException $e) {
http_response_code(400);
exit('Invalid signature');
}
?>
| 方案 | 延遲 | 成本 | 資料隱私 | 自訂程度 |
|---|---|---|---|---|
| SimSimi 官方 API | ~200-500ms | 免費額度後付費 | 資料送第三方 | 低(固定人設) |
| OpenAI GPT-3.5 | ~500-2000ms | ~$0.002/1K tokens | 資料送 OpenAI | 高(System Prompt 完全控制) |
| OpenAI GPT-4o | ~1-3s | ~$0.01/1K tokens | 資料送 OpenAI | 極高 |
| Ollama 本地 | ~1-10s (視 GPU) | 硬體成本一次性 | 完全本地 | 高(可微調/LoRA) |
<?php
class CachedChatBot
{
private ChatBotInterface $bot;
private Redis $redis;
private int $ttl = 3600; // 1小時快取相同問題
public function talk(string $text): array
{
$cacheKey = 'chatbot:' . md5(strtolower(trim($text)));
// 檢查快取
$cached = $this->redis->get($cacheKey);
if ($cached) {
return json_decode($cached, true) + ['cached' => true];
}
$response = $this->bot->talk($text);
if ($response['success']) {
$this->redis->setex($cacheKey, $this->ttl, json_encode($response));
}
return $response + ['cached' => false];
}
}
?>
原文的網頁版 SimSimi 爬蟲方式已失效。現代開發請:
SimSimiClient