Back to blog

    無需 OpenAI API 成本的 Shopify AI 助手

    如何為您的 Shopify 商店構建自定義 AI 助手,使用本地微調模型替換 OpenAI API 調用。逐步指南,附代碼示例。

    A pale astronomical impression in graphite and copper, with a soft amber penumbra on warm paper.An asymmetric engraved lunar crescent with cool cyan rim-light and a faint amber counter-impression.

    大多數 Shopify AI 助手指南假設您將一直使用 OpenAI API。這對第一個月很好。然後您的商店增長了,API 賬單隨之增長,您意識到您的 AI 功能正在消耗您的利潤。

    本指南向您展示如何使用本地微調模型構建 Shopify AI 助手。您的模型在自己的服務器上運行:沒有按 token 費用,沒有速率限制,對您商店的語氣、產品術語和客戶服務政策完全定制。


    架構概述

    Code example
    Shopify 店面
        │
        ▼
    主題 JavaScript(聊天小部件)
        │
        ▼ HTTP POST
    API 網關(您的 VPS/伺服器)
        │
        ▼
    Ollama API(本地推理)
        │
        ▼
    您的微調 GGUF 模型
    

    這就是全部了。Shopify 主題調用您的 API 端點,即一個在您的服務器上運行的簡單 Express.js 應用程序,連接到 Ollama 的本地推理 API。Ollama 的 API 與 OpenAI 兼容,所以如果您已經為 OpenAI 編寫了代碼,它將無需修改地工作。


    第一步:設置您的服務器

    您需要一個 VPS。每月約 $30 的預算足以租用一台 16GB RAM 的 VPS(Hetzner 的 CX43 截至 2026 年 10 月每月 €16.49,不含增值稅),處理 7B 模型服務所需的工作負載沒有問題。如果您有更高的並發(50 個以上同時用戶),考慮帶 GPU 的實例。

    在您的 VPS 上安裝 Ollama:

    Code example
    curl -fsSL https://ollama.com/install.sh | sh

    將您的 GGUF 模型上傳到服務器並創建一個 Modelfile:

    Code example
    FROM ./your-shopify-assistant.gguf
    
    SYSTEM """
    您是 [商店名稱] 的助手。您幫助客戶找到產品、回答關於訂單的問題,並提供友好、有幫助的客戶支持。
    
    商店政策:
    - 30 天無問題退貨
    - 標準訂單的 5-7 個工作日運輸
    - 免費送達超過 $50 的訂單
    
    請保持簡短的響應(2-3 句話),除非客戶詢問詳細信息。
    """
    

    運行:

    Code example
    ollama create shopify-assistant -f Modelfile
    ollama serve

    第二步:構建 API 網關

    創建一個將 Shopify 主題 JavaScript 連接到 Ollama 的簡單 Express.js 服務器:

    Code example
    import express from "express";
    import cors from "cors";
    
    const app = express();
    
    // 僅允許您的 Shopify 域名
    app.use(
      cors({
        origin: ["https://your-store.myshopify.com", "https://your-custom-domain.com"],
      })
    );
    
    app.use(express.json());
    
    app.post("/chat", async (req, res) => {
      const { message, history = [] } = req.body;
    
      if (!message || typeof message !== "string") {
        return res.status(400).json({ error: "需要消息" });
      }
    
      // 可選:注入 Shopify 上下文(當前頁面、產品等)
      const systemContext = req.body.context || "";
    
      const messages = [
        ...history.slice(-10), // 限制上下文窗口
        { role: "user", content: message },
      ];
    
      try {
        const response = await fetch("http://localhost:11434/api/chat", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            model: "shopify-assistant",
            messages,
            stream: false,
            options: {
              temperature: 0.7,
              num_predict: 256, // 保持響應簡潔
            },
          }),
        });
    
        const data = await response.json();
        res.json({
          response: data.message.content,
          role: "assistant",
        });
      } catch (err) {
        console.error("推理錯誤:", err);
        res.status(500).json({ error: "助手暫時不可用" });
      }
    });
    
    app.listen(3001, () => console.log("API 網關運行在端口 3001"));

    使用 PM2 部署:

    Code example
    npm install -g pm2
    pm2 start server.js --name shopify-ai
    pm2 save
    pm2 startup

    設置 nginx 反向代理以暴露 HTTPS 端點,因為 Shopify 需要 HTTPS 用於外部 API 調用。


    第三步:Shopify 主題集成

    在您的 Shopify 主題中,添加聊天小部件。在 theme.liquid 中或作為單獨的部分創建一個片段:

    Code example
    {% comment %} AI 聊天助手 {% endcomment %}
    <div id="ai-chat-widget" style="display:none;">
      <div id="chat-messages"></div>
      <div id="chat-input-area">
        <input type="text" id="chat-input" placeholder="有什麼我可以幫助您的嗎?" />
        <button id="chat-send">發送</button>
      </div>
    </div>
    
    <button id="chat-toggle">聊天</button>
    
    <script>
    (function() {
      const API_URL = "https://your-api-domain.com/chat";
      let chatHistory = [];
    
      // 從 Shopify 收集上下文
      const shopContext = {
        currentPage: {{ request.page_type | json }},
        currentProduct: {% if product %}{{ product.title | json }}{% else %}null{% endif %},
        cartItemCount: {{ cart.item_count }},
      };
    
      document.getElementById("chat-toggle").addEventListener("click", function() {
        const widget = document.getElementById("ai-chat-widget");
        widget.style.display = widget.style.display === "none" ? "flex" : "none";
      });
    
      document.getElementById("chat-send").addEventListener("click", sendMessage);
      document.getElementById("chat-input").addEventListener("keypress", function(e) {
        if (e.key === "Enter") sendMessage();
      });
    
      async function sendMessage() {
        const input = document.getElementById("chat-input");
        const message = input.value.trim();
        if (!message) return;
    
        input.value = "";
        appendMessage("您", message);
    
        try {
          const response = await fetch(API_URL, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              message,
              history: chatHistory,
              context: JSON.stringify(shopContext),
            }),
          });
    
          const data = await response.json();
          appendMessage("助手", data.response);
    
          chatHistory.push(
            { role: "user", content: message },
            { role: "assistant", content: data.response }
          );
        } catch (err) {
          appendMessage("助手", "抱歉,目前出了一些問題。請稍後再試。");
        }
      }
    
      function appendMessage(sender, text) {
        const messages = document.getElementById("chat-messages");
        const div = document.createElement("div");
        div.className = sender === "您" ? "user-message" : "assistant-message";
        div.textContent = text;
        messages.appendChild(div);
        messages.scrollTop = messages.scrollHeight;
      }
    })();
    </script>

    第四步:微調您的模型

    這是從通用 AI 助手過渡到真正了解您的業務的 AI 助手的關鍵步驟。

    收集訓練數據:真實的客戶服務交互最為理想。目標是 1,000-3,000 個示例:

    Code example
    {"messages": [
      {"role": "user", "content": "你們的運輸需要多長時間?"},
      {"role": "assistant", "content": "標準運輸通常需要 5-7 個工作日。如果您需要更快,我們提供特快運輸,需要 2-3 個工作日,額外費用為 $12.99。您希望我為您的訂單添加特快運輸嗎?"}
    ]}
    Code example
    {"messages": [
      {"role": "user", "content": "我可以退回一件我 3 週前購買的商品嗎?"},
      {"role": "assistant", "content": "是的!我們提供 30 天無問題退貨政策,所以您的購買仍然符合條件。只需通過訂單確認電子郵件中的鏈接提交退貨,我們將為您安排快遞取件。您需要幫助找到那封電子郵件嗎?"}
    ]}

    使用 Ertas Studio 進行微調,導出到 GGUF,按照第一步中所示更新您的 Modelfile。


    成本比較

    月交互次數OpenAI API 成本自托管成本節省
    1,000約 $25/月$30/月(VPS)持平
    5,000約 $125/月$30/月76%
    20,000約 $500/月$30/月94%
    100,000約 $2,500/月$30-80/月97%

    盈虧平衡點約為每月 5,000 次交互。在那之後,節省隨規模線性擴展。


    生產注意事項

    速率限制:實現基本速率限制(每個 IP 每分鐘 10 個請求),防止濫用並保持服務器響應性。

    降級:如果您的本地服務器宕機,您的 Shopify 助手應該優雅降級,隱藏聊天小部件或顯示靜態幫助文本,而不是顯示錯誤。

    日誌記錄:記錄交互(不含 PII)以改進培訓數據並識別助手掙扎的常見問題。

    模型更新:隨著您積累更多客戶交互,定期重新訓練您的模型。新的訓練數據讓助手更好地符合您商店的實際客戶問題。


    延伸閱讀