萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 串接 SimSimi 小黃雞聊天機器人 API:完整實作與避坑指南

SimSimi API 現狀說明

原文使用的 www.simsimi.com 網頁版介面已停止公開 API 服務,且需要 Cookie/CSRF Token 複雜流程。現代開發應使用 官方 SimSimi API(需申請 API Key)或替代方案:

  • 官方 API:developer.simsimi.com,免費額度每日 100 次,付費方案支援更高並發
  • 替代方案:OpenAI GPT、Google Dialogflow、Rasa、本地 LLM (Ollama/Llama.cpp)

官方 API 串接實作(推薦)

<?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";
}
?>

無 API Key 替代方案:OpenAI GPT 打造專屬聊天機器人

<?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'];
}
?>

本地離線方案:Ollama + Llama 3(資料不出本機、零成本)

<?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
?>

Webhook 整合:Line Bot / Messenger 回調處理

<?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 爬蟲方式已失效。現代開發請:

  1. 快速上線:申請 SimSimi 官方 API Key,使用上方 SimSimiClient
  2. 高度客製化/品牌人設:使用 OpenAI GPT 配合 System Prompt
  3. 資料敏感/零成本/離線:部署 Ollama + 開源 LLM
  4. 生產環境必備:Redis 快取重複問題、Token Bucket 限流、熔斷器防止下游故障擴散
copyright © 萬盛學電腦網 all rights reserved