<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>AIDiscount 部落格</title><link>https://aidiscount.ai/zh-hant/blog</link><atom:link href="https://aidiscount.ai/zh-hant/blog/rss.xml" rel="self" type="application/rss+xml"/><description>AIDiscount 的 AI API 教學與指南</description><language>zh-Hant</language><lastBuildDate>Wed, 25 Nov 2026 00:00:00 +0000</lastBuildDate><item><title>透過第三方 API 使用 Claude Code、Codex CLI 和 OpenCode</title><link>https://aidiscount.ai/zh-hant/blog/terminal-coding-agents-custom-provider</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/terminal-coding-agents-custom-provider</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>讓終端機程式代理程式改用第三方 API：Claude Code 的環境變數、Codex CLI 的 config.toml 與 OpenCode 的 opencode.json。</description><category>Claude Code</category><category>Codex CLI</category><category>OpenCode</category><category>Coding tools</category><content:encoded><![CDATA[<p>終端機程式設計代理程式會從環境變數或設定檔讀取 API 位址和金鑰。只要幾行設定，就能讓它們改連其他供應商。本文介紹三款熱門的代理程式。它們各自使用不同的 API 格式，而 AIDiscount 用同一把金鑰就能支援這三種格式。</p>
<table>
<tr><th>工具</th><th>API 格式</th><th>Base URL</th></tr>
<tr><td>Claude Code</td><td>Anthropic Messages</td><td><code>https://aidiscount.ai</code></td></tr>
<tr><td>Codex CLI</td><td>OpenAI Responses</td><td><code>https://aidiscount.ai/v1</code></td></tr>
<tr><td>OpenCode</td><td>OpenAI Responses 或 Chat Completions</td><td><code>https://aidiscount.ai/v1</code></td></tr>
</table>
<p><a href="https://aidiscount.ai/register">註冊</a>後，在 API Keys 頁面建立金鑰。模型 ID 請從<a href="https://aidiscount.ai/models">模型市集</a>取得。</p>

<h2 id="claude-code">Claude Code</h2>
<p>執行 <code>claude</code> 之前，先設定兩個環境變數：</p>
<pre><code># macOS / Linux
export ANTHROPIC_BASE_URL="https://aidiscount.ai"
export ANTHROPIC_AUTH_TOKEN="sk-..."

# Windows PowerShell
$env:ANTHROPIC_BASE_URL="https://aidiscount.ai"
$env:ANTHROPIC_AUTH_TOKEN="sk-..."</code></pre>
<p>Base URL 不要加 <code>/v1</code>。Claude Code 會自己加上 <code>/v1/messages</code>。</p>
<p>如果要讓設定永久生效，可以把 <code>export</code> 這幾行加到 <code>~/.bashrc</code> 或 <code>~/.zshrc</code>。也可以改寫在 <code>~/.claude/settings.json</code> 的 <code>env</code> 區塊中：</p>
<pre><code>{
  "env": {
    "ANTHROPIC_BASE_URL": "https://aidiscount.ai",
    "ANTHROPIC_AUTH_TOKEN": "sk-..."
  }
}</code></pre>
<p>如果你之前曾用帳號登入 Claude Code，請先執行 <code>/logout</code>，讓它改用環境變數中的 token。</p>

<h2 id="codex-cli">Codex CLI</h2>
<p>在 <code>~/.codex/config.toml</code> 中新增一個供應商：</p>
<pre><code>model_provider = "aidiscount"
model = "YOUR_MODEL_ID"

[model_providers.aidiscount]
name = "AIDiscount"
base_url = "https://aidiscount.ai/v1"
env_key = "AIDISCOUNT_API_KEY"
wire_api = "responses"</code></pre>
<p>接著設定金鑰並啟動 Codex：</p>
<pre><code>export AIDISCOUNT_API_KEY="sk-..."
codex</code></pre>
<p>遇到 Codex 不認識的模型時，它會印出 <code>Model metadata for ... not found. Defaulting to fallback metadata</code>。請求仍然可以正常運作。這個警告表示 Codex 不知道該模型的上下文長度。把長度告訴它，它才會在正確的時機壓縮較長的工作階段。以上下文長度為 200K token 的模型為例：</p>
<pre><code>model_context_window = 200000
model_auto_compact_token_limit = 160000</code></pre>
<p>把這兩行放在 <code>config.toml</code> 的最上方。上下文長度請以市集中該模型頁面上標示的數值為準。</p>

<h2 id="opencode">OpenCode</h2>
<p>在 <code>opencode.json</code> 中新增一個供應商（放在專案中，或放在 <code>~/.config/opencode/</code> 以套用到所有專案）：</p>
<pre><code>{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "aidiscount": {
      "npm": "@ai-sdk/openai",
      "name": "AIDiscount",
      "options": {
        "baseURL": "https://aidiscount.ai/v1",
        "apiKey": "{env:AIDISCOUNT_API_KEY}"
      },
      "models": {
        "YOUR_MODEL_ID": { "name": "YOUR_MODEL_ID" }
      }
    }
  }
}</code></pre>
<p><code>@ai-sdk/openai</code> 套件使用 Responses API。如果某個模型在這個 API 上出錯，請把套件改成使用 Chat Completions 的 <code>@ai-sdk/openai-compatible</code>。兩者都能使用同一把金鑰。</p>

<h2 id="確認設定成功">確認設定成功</h2>
<ol>
<li>問代理程式一個簡單的問題，例如「這個資料夾裡有哪些檔案？」</li>
<li>開啟 AIDiscount 控制台的 Usage 頁面。這筆請求應該會出現，並顯示模型名稱和扣款金額。</li>
</ol>
<p>如果沒有出現任何紀錄，表示代理程式還在使用先前的供應商。請確認環境變數是設定在你啟動代理程式的同一個終端機中。</p>

<h2 id="為代理程式挑選模型">為代理程式挑選模型</h2>
<p>代理程式會連續進行許多次工具呼叫，而且每次都會重送整段對話，因此會消耗大量輸入 token。強大的模型出錯較少，需要的步驟也較少；較便宜的模型則每一步的成本較低。實務上的做法是：規劃和棘手的 bug 交給強大的模型，例行的修改交給較便宜的模型。以下是幾個成本較低的選擇及其價格：</p>
<table><tr><th>模型</th><th>輸入 / 百萬 tokens</th><th>輸出 / 百萬 tokens</th><th>與官方價格比較</th></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-v4.1-flash">DeepSeek V4.1 Flash</a><br><code>deepseek-v4.1-flash</code></td><td>$0.0857</td><td>$0.3429</td><td>優惠 42.9%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/glm-5.3">GLM-5.3</a><br><code>glm-5.3</code></td><td>$0.6857</td><td>$2.40</td><td>優惠 45.5%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/kimi-k2.7-code">Kimi K2.7 Code</a><br><code>kimi-k2.7-code</code></td><td>$0.5571</td><td>$2.314</td><td>優惠 41.4%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-v4-pro">DeepSeek V4 Pro</a><br><code>deepseek-v4-pro</code></td><td>$0.3857</td><td>$1.1571</td><td>優惠 41.6%</td></tr></table><p class="meta">價格於產生本頁時從<a href="https://aidiscount.ai/models">模型廣場</a>即時讀取，可能會變動，請以模型廣場顯示的目前價格為準。</p>
<p>想進一步降低代理程式的成本，請參考<a href="https://aidiscount.ai/zh-hant/blog/reduce-ai-api-costs">如何降低 AI API 成本</a>。</p>
]]></content:encoded></item><item><title>如何在 Python 和 Node.js 中串流 AI API 回應</title><link>https://aidiscount.ai/zh-hant/blog/stream-ai-api-responses</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/stream-ai-api-responses</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>說明 OpenAI 相容 API 的 token 串流如何運作，附上可直接執行的 Python 與 Node.js 伺服器推送事件（SSE）程式碼，以及連線中斷時的處理方式。</description><category>Streaming</category><category>Python</category><category>Node.js</category><category>API</category><content:encoded><![CDATA[<p>串流（streaming）會在模型產生答案的同時就把內容送出，而不是等完整回應產生完畢。應用程式可以在文字送達時立即顯示，就像聊天介面逐字打出內容一樣。這也讓冗長的答案能立刻開始呈現，不必等全部完成。</p>

<h2 id="運作原理">運作原理</h2>
<p>一般的 API 呼叫會在模型完成後回傳一個 JSON 物件。串流呼叫則會保持 HTTP 連線開啟，並使用<strong>伺服器推送事件（server-sent events，SSE）</strong>送出一連串小事件：每個事件是一行以 <code>data: </code> 開頭、後面接著 JSON 片段的文字，最後以 <code>data: [DONE]</code> 這一行結束。每個片段只攜帶答案的一小部分（稱為「delta」），而不是到目前為止的完整文字，所以你的程式碼要把每一段依序附加到緩衝區中。</p>
<p>要在 OpenAI 相容 API 中啟用串流，請在請求內容中設定 <code>"stream": true</code>。</p>

<h2 id="python-搭配-openai-sdk">Python 搭配 OpenAI SDK</h2>
<pre><code>from openai import OpenAI

client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])

stream = client.chat.completions.create(
    model="gpt-6-luna",
    messages=[{"role": "user", "content": "Write a short poem about rivers."}],
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)</code></pre>

<h2 id="python-直接處理-sse-不使用-sdk">Python 直接處理 SSE（不使用 SDK）</h2>
<pre><code>import json, os, requests

with requests.post(
    "https://aidiscount.ai/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['AIDISCOUNT_API_KEY']}"},
    json={"model": "gpt-6-luna", "stream": True,
          "messages": [{"role": "user", "content": "Write a short poem about rivers."}]},
    stream=True, timeout=120,
) as r:
    r.raise_for_status()
    for line in r.iter_lines():
        if not line or not line.startswith(b"data: "):
            continue
        payload = line[len(b"data: "):]
        if payload == b"[DONE]":
            break
        delta = json.loads(payload)["choices"][0]["delta"].get("content")
        if delta:
            print(delta, end="", flush=True)</code></pre>

<h2 id="node-js-搭配-openai-sdk">Node.js 搭配 OpenAI SDK</h2>
<pre><code>import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://aidiscount.ai/v1", apiKey: process.env.AIDISCOUNT_API_KEY });

const stream = await client.chat.completions.create({
  model: "gpt-6-luna",
  messages: [{ role: "user", content: "Write a short poem about rivers." }],
  stream: true,
});
for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) process.stdout.write(delta);
}</code></pre>

<h2 id="node-js-搭配-fetch-不使用-sdk">Node.js 搭配 fetch（不使用 SDK）</h2>
<pre><code>const res = await fetch("https://aidiscount.ai/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AIDISCOUNT_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-6-luna",
    stream: true,
    messages: [{ role: "user", content: "Write a short poem about rivers." }],
  }),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buf += decoder.decode(value, { stream: true });
  const lines = buf.split("\n");
  buf = lines.pop();
  for (const line of lines) {
    if (!line.startsWith("data: ")) continue;
    const data = line.slice(6);
    if (data === "[DONE]") continue;
    const delta = JSON.parse(data).choices[0]?.delta?.content;
    if (delta) process.stdout.write(delta);
  }
}</code></pre>

<h2 id="anthropic-messages-格式">Anthropic Messages 格式</h2>
<p>事件的格式不同：每個 SSE 事件都有一行具名的 <code>event:</code>，而文字會在 <code>content_block_delta</code> 事件中送達。</p>
<pre><code>import anthropic

client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
with client.messages.stream(
    model="claude-opus-4-8",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a short poem about rivers."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)</code></pre>

<h2 id="處理連線中斷">處理連線中斷</h2>
<p>串流請求可能在中途失敗，而此時部分文字已經顯示出來了。中斷前產生的 token 通常仍會計費，所以請避免在緊密迴圈中不斷重試。在使用者介面中，請捕捉錯誤、保留已收到的文字，並顯示重試按鈕，而不是悄悄地從頭重新開始。如果要重試，請再次送出相同的請求；新的請求會開始一個新的串流。</p>
<p>如果服務位於代理伺服器或負載平衡器後方，請確認連線不會被緩衝或提早關閉。Nginx 需要對串流的路由設定 <code>proxy_buffering off;</code>，而用戶端的逾時時間應該足夠讓較慢的模型完成回應（串流回應會被視為活躍的流量，而不是閒置連線，所以大多數用戶端不需要為此特別處理逾時）。</p>

<h2 id="串流與工具呼叫">串流與工具呼叫</h2>
<p>當模型以串流方式送出工具呼叫時，函式名稱和參數也會分成好幾段，分散在多個片段中送達。請依索引緩衝 <code>tool_calls</code> 的 delta，並持續串接 <code>arguments</code> 字串直到串流結束，再將其解析為 JSON。大多數 SDK 都會自動幫你處理這種緩衝。</p>
]]></content:encoded></item><item><title>如何降低 AI API 成本：模型選擇、上下文大小與輸出長度限制</title><link>https://aidiscount.ai/zh-hant/blog/reduce-ai-api-costs</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/reduce-ai-api-costs</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>降低 AI API 費用的實用方法：依任務挑選合適的模型、減少送出的上下文、限制輸出長度、善用提示快取，並追蹤每筆請求的花費。</description><category>Cost</category><category>Tokens</category><category>Pricing</category><content:encoded><![CDATA[<p>AI API 依 token 計費。一個 token 大約是幾個字元的文字。你要為送出的 token（輸入）和模型回傳的 token（輸出）付費，而輸出 token 的價格通常是輸入 token 的好幾倍。所有省錢方法都來自以下三者之一：更低的每 token 單價、更少的輸入 token，或更少的輸出 token。</p>

<h2 id="1-用能完成工作的最小模型">1. 用能完成工作的最小模型</h2>
<p>不同模型之間的價格差距可達十倍以上。許多任務並不需要最強的模型：</p>
<ul>
<li><strong>小型、快速的模型</strong>很擅長分類、資訊擷取、簡短摘要、翻譯和自動完成。</li>
<li><strong>大型模型</strong>值得用在困難的推理、冗長的多步驟程式設計任務，以及答錯代價很高的工作上。</li>
</ul>
<p>以下是一些成本較低的模型及其目前價格：</p>
<table><tr><th>模型</th><th>輸入 / 百萬 tokens</th><th>輸出 / 百萬 tokens</th><th>與官方價格比較</th></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-v4.1-flash">DeepSeek V4.1 Flash</a><br><code>deepseek-v4.1-flash</code></td><td>$0.0857</td><td>$0.3429</td><td>優惠 42.9%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/glm-5.3-flash">GLM-5.3-Flash</a><br><code>glm-5.3-flash</code></td><td>$0.0686</td><td>$0.24</td><td>優惠 52%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/glm-5.3-flashx">GLM-5.3-FlashX</a><br><code>glm-5.3-flashx</code></td><td>$0.1714</td><td>$0.60</td><td>優惠 52%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/claude-haiku-4-5-20251001">Claude Haiku 4.5</a><br><code>claude-haiku-4-5-20251001</code></td><td>$0.075</td><td>$0.375</td><td>優惠 92.5%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-v4-pro">DeepSeek V4 Pro</a><br><code>deepseek-v4-pro</code></td><td>$0.3857</td><td>$1.1571</td><td>優惠 41.6%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/glm-5.3">GLM-5.3</a><br><code>glm-5.3</code></td><td>$0.6857</td><td>$2.40</td><td>優惠 45.5%</td></tr></table><p class="meta">價格於產生本頁時從<a href="https://aidiscount.ai/models">模型廣場</a>即時讀取，可能會變動，請以模型廣場顯示的目前價格為準。</p>
<p>常見的做法是路由（routing）：每個請求先交給小型模型處理，只有在任務困難，或小型模型的答案沒通過檢查時，才升級給大型模型。由於 OpenAI 相容 API 對每個模型都使用相同的請求格式，路由只需要更改 <code>model</code> 欄位。</p>

<h2 id="2-減少送出的上下文">2. 減少送出的上下文</h2>
<p>輸入 token 累積得很快，因為聊天應用程式和代理程式每送出一則訊息，都會重送整段對話。</p>
<ul>
<li><strong>新話題就開新對話</strong>，不要一直延續冗長的對話串。</li>
<li><strong>修剪對話紀錄。</strong>保留系統提示詞和最近幾輪對話，較早的內容改用簡短摘要取代。</li>
<li><strong>只送出相關的部分</strong>文件和程式碼。檢索（先搜尋，再送出符合的片段）通常比貼上整個檔案便宜。</li>
<li><strong>縮短系統提示詞。</strong>每次請求都會送出系統提示詞，所以裡面的每個字都會被重複計費很多次。</li>
</ul>

<h2 id="3-限制輸出長度">3. 限制輸出長度</h2>
<p>設定 <code>max_tokens</code>（Responses API 則是 <code>max_output_tokens</code>），避免失控的回答花掉超出預期的費用。明確要求你需要的格式，例如「用一句話回答」或「只回傳 JSON」，就能直接減少輸出 token。</p>
<pre><code>resp = client.chat.completions.create(
    model="deepseek-v4.1-flash",
    messages=[
        {"role": "system", "content": "Reply in at most two sentences."},
        {"role": "user", "content": "Summarize this ticket: ..."},
    ],
    max_tokens=200,
)</code></pre>
<p>推理模型在回答前也會花 token 思考，而這些思考內容會以輸出計費。請把它們用在推理確實有幫助的地方，不要拿來做簡單的查詢。</p>

<h2 id="4-善用提示快取">4. 善用提示快取</h2>
<p>許多模型提供提示快取（prompt caching）：當請求的開頭與最近一次請求的內容相同時，重複的部分會以較低的快取讀取費率計費。想要享有這個好處，請把固定的部分（系統提示詞、工具定義、冗長的參考文件）放在開頭，會變動的部分放在最後。如果模型有快取價格，<a href="https://aidiscount.ai/models">市集</a>中的模型頁面會列出來。</p>

<h2 id="5-同樣的答案不要付兩次錢">5. 同樣的答案不要付兩次錢</h2>
<p>如果你的應用程式經常被問到同樣的問題（例如產品常見問題），就把答案存在你自己的快取中，直接回傳，不必呼叫 API。</p>

<h2 id="6-批次處理小型工作">6. 批次處理小型工作</h2>
<p>與其每個項目各送一次請求，不如把幾個簡短項目放進同一個請求，並要求回傳結果清單。這樣指示只需送出一次，而不是很多次。批次的大小要適中，以免其中一個項目出問題就得整批重做。</p>

<h2 id="7-逐筆衡量請求">7. 逐筆衡量請求</h2>
<p>沒有衡量，就無從降低。每個 API 回應都包含 <code>usage</code> 欄位，記錄輸入和輸出的 token 數：</p>
<pre><code>print(resp.usage.prompt_tokens, resp.usage.completion_tokens)</code></pre>
<p>在 AIDiscount 中，控制台的 Usage 頁面會列出每筆請求的模型、token 數和扣款金額。為不同的應用程式或團隊成員使用不同的 API 金鑰，就能看出誰花得最多。</p>

<h2 id="8-比較每-token-的價格">8. 比較每 token 的價格</h2>
<p>同一個模型在不同供應商的價格可能不同。AIDiscount 在每個模型的頁面上都會顯示每百萬 token 的價格，並在適用時標示與官方定價的比較。由於價格會變動，選擇之前請先到<a href="https://aidiscount.ai/models">市集</a>確認目前的費率。</p>
]]></content:encoded></item><item><title>推理強度：何時使用思考模型，以及成本如何計算</title><link>https://aidiscount.ai/zh-hant/blog/reasoning-effort-cost-guide</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/reasoning-effort-cost-guide</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>說明推理模型如何對隱藏的推理 token 計費、推理強度（reasoning effort）設定如何影響成本與速度，以及何時選用一般模型比較合適。</description><category>Reasoning</category><category>Cost</category><category>Tokens</category><category>API</category><content:encoded><![CDATA[<p>推理模型（也稱為思考模型）會在寫出答案之前，一步一步地思考問題。這些額外的思考讓它們在數學、多步驟邏輯、規劃和困難的程式設計任務上表現更好。但這也會提高成本，因為思考的內容是由 token 組成的，而你要為這些 token 付費。</p>

<h2 id="推理如何計費">推理如何計費</h2>
<p>推理 token 會以<strong>輸出 token</strong> 計費，採用模型的輸出費率，即使 API 沒有把推理文字顯示給你看也一樣。一個簡短的最終答案，背後可能用掉了數千個推理 token。請查看 <code>usage</code> 欄位，才能看到真實的數量：</p>
<pre><code>resp = client.chat.completions.create(model="gpt-6.2-sol", messages=messages)
u = resp.usage
print(u.completion_tokens, getattr(u, "completion_tokens_details", None))
# completion_tokens_details.reasoning_tokens is the hidden thinking part</code></pre>
<p>在 AIDiscount 中，控制台的 Usage 頁面會顯示每筆請求所收取的輸出 token 數，其中包含推理部分。</p>

<h2 id="推理強度設定">推理強度設定</h2>
<p>大多數推理模型都讓你選擇思考的力度。較低的強度代表較少的推理 token、較快出現第一個 token，以及較低的費用。較高的強度有助於處理困難的問題，但用在簡單的問題上就是浪費錢。</p>
<p>OpenAI 相容格式：</p>
<pre><code>resp = client.chat.completions.create(
    model="gpt-6.2-sol",
    reasoning_effort="low",
    messages=[{"role": "user", "content": "Classify this ticket as billing, bug or other: ..."}],
)</code></pre>
<p>各模型接受的值不同。有些接受 <code>low</code>、<code>medium</code> 和 <code>high</code>，有些還多了 <code>xhigh</code> 或 <code>max</code>，也有些接受 <code>none</code> 來關閉思考功能。<a href="https://aidiscount.ai/models">市集</a>中的模型頁面會列出該模型支援的值。</p>
<p>Anthropic Messages 格式則在支援的模型上使用以 token 計算的思考預算：</p>
<pre><code>resp = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=8000,
    thinking={"type": "enabled", "budget_tokens": 4000},
    messages=[{"role": "user", "content": "Plan a database migration for ..."}],
)</code></pre>
<p>這個預算必須小於 <code>max_tokens</code>，因為思考和答案共用同一個輸出上限。部分較新的 Claude 模型改用強度設定而不是 token 預算，模型頁面會顯示該模型適用哪一種方式。</p>

<h2 id="何時使用哪種設定">何時使用哪種設定</h2>
<table>
<tr><th>任務</th><th>建議設定</th></tr>
<tr><td>分類、資訊擷取、翻譯、簡短摘要</td><td>一般模型，或關閉推理、設為低強度</td></tr>
<tr><td>聊天與寫作</td><td>低或中等強度</td></tr>
<tr><td>多步驟程式設計、除錯、資料分析</td><td>中等或高強度</td></tr>
<tr><td>困難的數學、證明、複雜規劃</td><td>高強度或更高</td></tr>
</table>
<p>先從低強度開始，只有在答案出錯時才提高強度。請用你實際請求的樣本來測試。合適的設定主要取決於任務本身，而不是模型。</p>

<h2 id="需要留意的事項">需要留意的事項</h2>
<ul>
<li><strong>在 <code>max_tokens</code> 中留出空間。</strong>如果上限設得太小，模型可能把額度全花在思考上，導致回答空白或被截斷。</li>
<li><strong>預期第一個 token 會比較慢出現。</strong>模型會先思考才寫出內容。請使用串流讓使用者看到進度，並把用戶端逾時時間設得足夠長，以應付高強度推理。</li>
<li><strong>部分參數在思考時會被固定。</strong>許多模型在開啟推理時會拒絕自訂的 <code>temperature</code>。請保留預設值。</li>
<li><strong>不要再額外要求「逐步說明」。</strong>推理模型內部本來就會這麼做。要求顯示步驟只會增加輸出 token，而不會改善答案品質。</li>
</ul>

<h2 id="目前價格">目前價格</h2>
<p>由於推理是以輸出計費，當你打算使用高強度推理時，請以輸出價格來比較模型：</p>
<table><tr><th>模型</th><th>輸入 / 百萬 tokens</th><th>輸出 / 百萬 tokens</th><th>與官方價格比較</th></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/gpt-6.2-sol">GPT-6.2 Sol</a><br><code>gpt-6.2-sol</code></td><td>$0.20</td><td>$1.00</td><td>優惠 90%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/claude-sonnet-5-5">Claude Sonnet 5.5</a><br><code>claude-sonnet-5-5</code></td><td>$0.15</td><td>$0.75</td><td>優惠 92.5%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-v4-pro">DeepSeek V4 Pro</a><br><code>deepseek-v4-pro</code></td><td>$0.3857</td><td>$1.1571</td><td>優惠 41.6%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-flash">DeepSeek V4.1 Flash 1017</a><br><code>deepseek-flash</code></td><td>$0.0857</td><td>$0.3429</td><td>優惠 42.9%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/glm-5.3">GLM-5.3</a><br><code>glm-5.3</code></td><td>$0.6857</td><td>$2.40</td><td>優惠 45.5%</td></tr></table><p class="meta">價格於產生本頁時從<a href="https://aidiscount.ai/models">模型廣場</a>即時讀取，可能會變動，請以模型廣場顯示的目前價格為準。</p>
]]></content:encoded></item><item><title>提示快取：運作原理與省錢方法</title><link>https://aidiscount.ai/zh-hant/blog/prompt-caching-save-money</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/prompt-caching-save-money</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>說明提示快取如何讓重複請求的輸入 token 以較低費率計費、如何安排提示詞結構才能真正命中快取，以及目前的快取價格。</description><category>Prompt caching</category><category>Pricing</category><category>Tokens</category><category>API</category><content:encoded><![CDATA[<p>提示快取（prompt caching）讓模型可以跳過重新處理最近已看過的提示詞部分。當新請求的開頭與過去幾分鐘內某個請求的內容相同時，重複的前綴會以較低的<strong>快取讀取</strong>費率計費，而不是一般的輸入費率。建立快取的第一個請求通常會稍貴一些（<strong>快取寫入</strong>費率），之後每個符合的請求都會比較便宜。</p>

<h2 id="為什麼重要">為什麼重要</h2>
<p>許多實際的應用程式每次請求都會重送一大段固定文字：系統提示詞、一組工具定義、使用者正在提問的長篇文件，或是程式設計代理程式所需的整個程式碼庫上下文。沒有快取時，你每次都要為這段內容支付完整的輸入費率。有了快取，你只需付一次，之後每個重複使用它的請求都只需支付快取讀取費率，通常只是一般輸入價格的一小部分。</p>

<h2 id="如何安排提示詞結構以命中快取">如何安排提示詞結構以命中快取</h2>
<p>快取比對的是前綴：從提示詞開頭到某個位置為止完全相同的文字。請依以下順序安排內容：</p>
<ol>
<li><strong>固定內容放前面</strong>：系統提示詞、工具定義、冗長的參考文件、少樣本（few-shot）範例。這些內容在每次請求之間應該逐位元組完全相同。</li>
<li><strong>變動內容放最後</strong>：使用者目前的訊息、對話的最新一輪，以及每次呼叫都會改變的任何內容。</li>
</ol>
<p>只要固定部分改了一個字元，從那個位置開始快取就會失效，變更處之後的所有內容都會改回一般輸入費率計費。常見的意外破壞快取的方式包括：在系統提示詞中插入時間戳記、調換工具定義的順序，或以不同的鍵順序或空白重新序列化 JSON。</p>

<h2 id="範例-冗長的系統提示詞">範例：冗長的系統提示詞</h2>
<pre><code>from openai import OpenAI

client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])

SYSTEM_PROMPT = open("system_prompt.txt").read()  # several thousand tokens, identical every call

def ask(user_message):
    return client.chat.completions.create(
        model="claude-opus-4-8",
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": user_message},
        ],
    )</code></pre>
<p>由於 <code>SYSTEM_PROMPT</code> 每次呼叫都完全相同且放在最前面，在快取有效期間內的第二次及之後的呼叫，這段內容都會以快取讀取費率計費。</p>

<h2 id="確認快取是否真的命中">確認快取是否真的命中</h2>
<p>回應中的 <code>usage</code> 欄位會分開列出快取的 token 數，讓你能確認快取確實在運作，而不是憑假設：</p>
<pre><code>resp = ask("What does section 4 say about refunds?")
print(resp.usage.prompt_tokens, getattr(resp.usage, "prompt_tokens_details", None))
# prompt_tokens_details.cached_tokens > 0 means the cache hit</code></pre>
<p>如果以相同前綴重複呼叫，<code>cached_tokens</code> 卻一直是 0，代表固定部分在請求之間有所變動，或是請求之間的間隔超過了快取的保留時間。</p>

<h2 id="anthropic-messages-格式">Anthropic Messages 格式</h2>
<p>Anthropic 的格式會在內容區塊上用 <code>cache_control</code> 明確標示快取邊界，而不只是依賴從開頭比對前綴：</p>
<pre><code>resp = client.messages.create(
    model="claude-opus-4-8", max_tokens=1024,
    system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}],
    messages=[{"role": "user", "content": "What does section 4 say about refunds?"}],
)
print(resp.usage.cache_read_input_tokens, resp.usage.cache_creation_input_tokens)</code></pre>

<h2 id="哪些情況有幫助-哪些沒有">哪些情況有幫助，哪些沒有</h2>
<ul>
<li><strong>很適合</strong>：具有冗長固定系統提示詞、使用者每輪訊息很短的聊天機器人；會重送同一個大型檔案的程式設計代理程式；針對單一文件回答許多問題的文件問答應用程式。</li>
<li><strong>幫助不大</strong>：請求之間沒有共同前綴的簡短一次性提示詞；唯一的大段內容剛好是每次都會改變的部分。</li>
<li><strong>多輪對話</strong>：每則新訊息都會延伸先前的對話，所以只要不修改較早的對話輪次，不斷增長的對話紀錄本身就會成為被快取的前綴。如果希望快取持續有效，請避免直接修改較早的訊息。</li>
</ul>

<h2 id="目前的快取價格">目前的快取價格</h2>
<p>快取價格依模型而定，並非每個模型都提供。若模型支援快取，<a href="https://aidiscount.ai/models">市集</a>中的模型頁面會在一般輸入與輸出價格旁列出讀取和寫入費率。</p>
<table><tr><th>模型</th><th>輸入 / 百萬 tokens</th><th>輸出 / 百萬 tokens</th><th>與官方價格比較</th></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/claude-opus-4-8">Claude Opus 4.8</a><br><code>claude-opus-4-8</code></td><td>$0.375</td><td>$1.875</td><td>優惠 92.5%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/claude-haiku-4-5-20251001">Claude Haiku 4.5</a><br><code>claude-haiku-4-5-20251001</code></td><td>$0.075</td><td>$0.375</td><td>優惠 92.5%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-v4-pro">DeepSeek V4 Pro</a><br><code>deepseek-v4-pro</code></td><td>$0.3857</td><td>$1.1571</td><td>優惠 41.6%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/gpt-6.2-sol">GPT-6.2 Sol</a><br><code>gpt-6.2-sol</code></td><td>$0.20</td><td>$1.00</td><td>優惠 90%</td></tr></table><p class="meta">價格於產生本頁時從<a href="https://aidiscount.ai/models">模型廣場</a>即時讀取，可能會變動，請以模型廣場顯示的目前價格為準。</p>
]]></content:encoded></item><item><title>什麼是 OpenAI 相容 API？如何切換 Base URL</title><link>https://aidiscount.ai/zh-hant/blog/openai-compatible-api-base-url</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/openai-compatible-api-base-url</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>OpenAI 相容 API 接受與 OpenAI API 相同的請求。本文說明如何只改兩項設定，就讓 OpenAI SDK、curl 和常用工具改連其他供應商。</description><category>OpenAI-compatible</category><category>API</category><category>Python</category><category>Node.js</category><content:encoded><![CDATA[<p>大多數 AI 工具和 SDK 都是針對 OpenAI API 開發的。許多其他供應商也接受相同的請求格式，所以同一份程式碼就能和它們溝通。這類供應商稱為 <strong>OpenAI 相容</strong>。在它們之間切換，通常只需要改兩項設定：<strong>Base URL</strong> 和 <strong>API 金鑰</strong>。</p>

<h2 id="openai-相容-是什麼意思">「OpenAI 相容」是什麼意思</h2>
<p>當供應商以相同的路徑、相同的 JSON 結構提供服務，就算是 OpenAI 相容。最常見的端點如下：</p>
<table>
<tr><th>端點</th><th>用途</th></tr>
<tr><td><code>POST /v1/chat/completions</code></td><td>聊天和大多數工具。支援度最廣的格式。</td></tr>
<tr><td><code>POST /v1/responses</code></td><td>OpenAI 較新的介面，Codex CLI 和 Agents SDK 使用這個格式。</td></tr>
<tr><td><code>GET /v1/models</code></td><td>列出你的金鑰可用的模型 ID。</td></tr>
<tr><td><code>POST /v1/images/generations</code></td><td>圖片生成。</td></tr>
<tr><td><code>POST /v1/embeddings</code></td><td>文字嵌入（embeddings）。</td></tr>
</table>
<p>相容性指的是請求與回應的格式。每家供應商仍然自行決定提供哪些模型，所以 <code>model</code> 的值必須是該供應商列出的模型 ID。</p>

<h2 id="需要修改的兩項設定">需要修改的兩項設定</h2>
<ul>
<li><strong>Base URL。</strong> 位於 <code>/chat/completions</code> 之前的那段網址。OpenAI 是 <code>https://api.openai.com/v1</code>，AIDiscount 則是 <code>https://aidiscount.ai/v1</code>。</li>
<li><strong>API 金鑰。</strong> 各供應商自己的金鑰，以 <code>Authorization: Bearer sk-...</code> 的形式送出。一家供應商的金鑰無法在另一家使用。</li>
</ul>
<p>請把金鑰放在環境變數裡，不要寫進程式碼：</p>
<pre><code># macOS / Linux
export AIDISCOUNT_API_KEY="sk-..."

# Windows PowerShell
$env:AIDISCOUNT_API_KEY="sk-..."</code></pre>

<h2 id="curl">curl</h2>
<pre><code>curl https://aidiscount.ai/v1/chat/completions \
  -H "Authorization: Bearer $AIDISCOUNT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4.1-flash",
    "messages": [{"role": "user", "content": "Hello"}]
  }'</code></pre>

<h2 id="python-官方-openai-sdk">Python（官方 OpenAI SDK）</h2>
<pre><code>import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AIDISCOUNT_API_KEY"],
    base_url="https://aidiscount.ai/v1",
)

resp = client.chat.completions.create(
    model="deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Hello"}],
)
print(resp.choices[0].message.content)</code></pre>
<p>SDK 也會從環境變數讀取 <code>OPENAI_BASE_URL</code> 和 <code>OPENAI_API_KEY</code>。兩者都設定好之後，完全不用改程式碼就能切換供應商。</p>

<h2 id="node-js-官方-openai-sdk">Node.js（官方 OpenAI SDK）</h2>
<pre><code>import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AIDISCOUNT_API_KEY,
  baseURL: "https://aidiscount.ai/v1",
});

const resp = await client.chat.completions.create({
  model: "deepseek-v4.1-flash",
  messages: [{ role: "user", content: "Hello" }],
});
console.log(resp.choices[0].message.content);</code></pre>

<h2 id="串流的用法也一樣">串流的用法也一樣</h2>
<p>加上 <code>stream=True</code>（Python）或 <code>stream: true</code>（Node.js）即可。供應商會以和 OpenAI 相同的格式送出 server-sent events。</p>
<pre><code>stream = client.chat.completions.create(
    model="deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Write a haiku"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)</code></pre>

<h2 id="查詢可用的模型-id">查詢可用的模型 ID</h2>
<pre><code>curl https://aidiscount.ai/v1/models \
  -H "Authorization: Bearer $AIDISCOUNT_API_KEY"</code></pre>
<p><a href="https://aidiscount.ai/models">模型市集</a>也列出了同樣的 ID 和目前的價格。</p>

<h2 id="常見錯誤">常見錯誤</h2>
<ul>
<li><strong>404 Not Found。</strong> Base URL 少了 <code>/v1</code>，或是工具會自動加上 <code>/v1</code>，你又多加了一次。請改用另一種寫法。</li>
<li><strong>401 Unauthorized。</strong> 金鑰屬於其他供應商、有打錯字，或已被刪除。</li>
<li><strong>Model not found。</strong> 填入的模型名稱是該供應商沒有提供的。請從 <code>/v1/models</code> 複製完整的 ID。</li>
</ul>
<p>更多解法請參考<a href="https://aidiscount.ai/zh-hant/blog/fix-ai-api-errors-401-403-404-429">如何修正常見的 AI API 錯誤</a>。</p>

<h2 id="那-anthropic-格式呢">那 Anthropic 格式呢？</h2>
<p>有些工具改用 Anthropic Messages API（<code>POST /v1/messages</code>，搭配 <code>x-api-key</code> 標頭）。AIDiscount 也接受這種格式。使用 Anthropic SDK 時，Base URL 請填 <code>https://aidiscount.ai</code>，不要加 <code>/v1</code>，因為 SDK 會自己加上 <code>/v1/messages</code>。完整範例請見 <a href="https://aidiscount.ai/docs#anthropic">API 文件</a>。</p>
]]></content:encoded></item><item><title>在 LangChain 和 Vercel AI SDK 中使用自訂 API 供應商</title><link>https://aidiscount.ai/zh-hant/blog/langchain-vercel-ai-sdk-custom-provider</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/langchain-vercel-ai-sdk-custom-provider</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>說明如何透過變更 base URL 和金鑰，讓 LangChain（Python 和 JS）與 Vercel AI SDK 指向 OpenAI 相容端點，並附上可直接執行的範例。</description><category>LangChain</category><category>Vercel AI SDK</category><category>API</category><category>Node.js</category><category>Python</category><content:encoded><![CDATA[<p>LangChain 和 Vercel AI SDK 都是透過已經支援 OpenAI 相容 API 的轉接器與模型溝通。在任一框架中切換供應商，指的是在 OpenAI 相容的用戶端上設定 base URL 和金鑰，而不是改變你呼叫框架本身的方式。</p>

<h2 id="langchain-python">LangChain（Python）</h2>
<p><code>ChatOpenAI</code> 可以透過 <code>base_url</code>（或 <code>OPENAI_BASE_URL</code> 環境變數）接受自訂的 base URL：</p>
<pre><code>import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-6-luna",
    base_url="https://aidiscount.ai/v1",
    api_key=os.environ["AIDISCOUNT_API_KEY"],
)
response = llm.invoke("Summarize the plot of Hamlet in two sentences.")
print(response.content)</code></pre>
<p>串流、用 <code>llm.bind_tools(...)</code> 綁定工具，以及 LangChain Expression Language 鏈，全都不需修改就能正常運作，因為它們都是透過同一個底層用戶端運作。</p>

<h2 id="langchain-js-ts">LangChain（JS/TS）</h2>
<pre><code>import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "gpt-6-luna",
  configuration: { baseURL: "https://aidiscount.ai/v1" },
  apiKey: process.env.AIDISCOUNT_API_KEY,
});
const response = await llm.invoke("Summarize the plot of Hamlet in two sentences.");
console.log(response.content);</code></pre>

<h2 id="搭配-anthropic-messages-格式的-langchain">搭配 Anthropic Messages 格式的 LangChain</h2>
<p>請使用 <code>ChatAnthropic</code> 和它自己的 base URL 選項，而不是 <code>ChatOpenAI</code>：</p>
<pre><code>from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(
    model="claude-opus-4-8",
    anthropic_api_url="https://aidiscount.ai",
    api_key=os.environ["AIDISCOUNT_API_KEY"],
)</code></pre>

<h2 id="vercel-ai-sdk">Vercel AI SDK</h2>
<p><code>@ai-sdk/openai</code> 這個供應商在用 <code>createOpenAI</code> 建立時可以接受 <code>baseURL</code>，而不是使用預設的 <code>openai</code> 匯出物件：</p>
<pre><code>import { createOpenAI } from "@ai-sdk/openai";
import { generateText } from "ai";

const aidiscount = createOpenAI({
  baseURL: "https://aidiscount.ai/v1",
  apiKey: process.env.AIDISCOUNT_API_KEY,
});

const { text } = await generateText({
  model: aidiscount("gpt-6-luna"),
  prompt: "Summarize the plot of Hamlet in two sentences.",
});
console.log(text);</code></pre>
<p>串流也是用同樣的方式透過 <code>streamText</code> 運作：</p>
<pre><code>import { streamText } from "ai";

const { textStream } = streamText({
  model: aidiscount("gpt-6-luna"),
  prompt: "Write a short poem about rivers.",
});
for await (const chunk of textStream) process.stdout.write(chunk);</code></pre>
<p>對於 Anthropic Messages 格式，請用同樣的方式，使用 <code>@ai-sdk/anthropic</code> 中的 <code>createAnthropic</code>，並設定 <code>baseURL: "https://aidiscount.ai"</code>。</p>

<h2 id="透過這些框架使用工具">透過這些框架使用工具</h2>
<p>這兩個框架都會把各自的工具定義轉換成底層 API 所需的同一種 JSON Schema 結構，所以一旦設定好 base URL，工具呼叫就能正常運作，不需要額外設定。LangChain 使用 <code>llm.bind_tools([...])</code> 或代理執行器（agent executor）；Vercel AI SDK 則是把 <code>tools</code> 物件傳給 <code>generateText</code> 或 <code>streamText</code>。底層的請求與回應結構請參閱<a href="https://aidiscount.ai/zh-hant/blog/function-calling-tool-use-guide">函式呼叫指南</a>。</p>

<h2 id="常見錯誤">常見錯誤</h2>
<ul>
<li><strong>把 base URL 設在錯誤的物件上。</strong>在 LangChain JS 中，base URL 要放在 <code>configuration</code> 底下，而不是最外層的欄位。</li>
<li><strong>把 Chat Completions 的 base URL 和 Anthropic 格式的模型名稱混用，或反過來。</strong>每個轉接器都只對應一種 API 結構；OpenAI 格式請用 <code>ChatOpenAI</code>／<code>createOpenAI</code>，Anthropic 格式請用 <code>ChatAnthropic</code>／<code>createAnthropic</code>，並讓 base URL 與其正確搭配。</li>
<li><strong>沿用 Vercel AI SDK 預設的 <code>openai</code> 匯出物件。</strong>那個匯出物件永遠指向 OpenAI 自家的 API；你需要用 <code>createOpenAI</code> 才能設定不同的 base URL。</li>
</ul>

<h2 id="挑選模型">挑選模型</h2>
<p>一旦設定好 base URL 和金鑰，<a href="https://aidiscount.ai/models">市集</a>中的任何模型 ID 都可以直接當作 <code>model</code> 參數使用；切換模型時，LangChain 或 Vercel AI SDK 程式碼的其他部分都不需要變動。</p>
]]></content:encoded></item><item><title>讓 AI 模型穩定輸出 JSON</title><link>https://aidiscount.ai/zh-hant/blog/json-structured-output-guide</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/json-structured-output-guide</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>如何讓 AI API 穩定回傳有效的 JSON：response_format 的 JSON 模式、用 JSON Schema 固定結構，以及模型仍然出錯時的備援做法。</description><category>JSON</category><category>Structured output</category><category>API</category><category>Python</category><content:encoded><![CDATA[<p>許多應用程式需要模型以固定的結構回答：一個具有特定欄位的 JSON 物件，而不是一段文字。在提示詞中客氣地要求（「請以 JSON 回覆」）通常有效，但並非每次都行：模型可能在 JSON 前面多加一句話、用 markdown 程式碼區塊包起來，或漏掉某個欄位。可靠程度由弱到強可分為三個層級。</p>

<h2 id="層級-1-在提示詞中要求">層級 1：在提示詞中要求</h2>
<p>大多數時候有效，偶爾會失敗。只適合用在影響不大的情境，或與下面更可靠的方法搭配使用。</p>
<pre><code>messages = [{"role": "user", "content":
    'Extract the name and age from this text as JSON with keys "name" and "age": '
    '"Maria is 34 years old."'}]</code></pre>

<h2 id="層級-2-json-模式">層級 2：JSON 模式</h2>
<p>設定 <code>response_format={"type": "json_object"}</code> 會強制輸出語法正確的 JSON。但它不會限制必須包含哪些欄位，所以請在提示詞中寫明確切的欄位名稱。</p>
<pre><code>from openai import OpenAI
import json

client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])

resp = client.chat.completions.create(
    model="gpt-6-luna",
    response_format={"type": "json_object"},
    messages=[{"role": "user", "content":
        'Extract the name and age as JSON with keys "name" and "age": "Maria is 34 years old."'}],
)
data = json.loads(resp.choices[0].message.content)
print(data["name"], data["age"])</code></pre>
<p>JSON 模式要求對話中某處必須出現「JSON」這個字，通常放在系統訊息或使用者訊息中；否則部分模型會回傳錯誤。</p>

<h2 id="層級-3-json-schema-建議使用">層級 3：JSON Schema（建議使用）</h2>
<p>將 <code>response_format</code> 設為 JSON Schema，可以同時限制語法和結構：必填欄位、型別和列舉值都會在生成過程中強制遵守，而不只是事後檢查。</p>
<pre><code>schema = {
    "type": "json_schema",
    "json_schema": {
        "name": "person",
        "schema": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"},
            },
            "required": ["name", "age"],
            "additionalProperties": False,
        },
        "strict": True,
    },
}
resp = client.chat.completions.create(
    model="gpt-6-luna",
    response_format=schema,
    messages=[{"role": "user", "content": "Maria is 34 years old."}],
)
data = json.loads(resp.choices[0].message.content)</code></pre>
<p>Schema 只要滿足任務所需即可，越精簡越好。比起只有少數必填欄位的扁平 schema，包含許多選填欄位和巢狀物件的 schema 更難讓模型正確填寫。</p>

<h2 id="anthropic-messages-格式">Anthropic Messages 格式</h2>
<p>Messages API 沒有專用的 JSON 模式；可靠的做法是在系統提示詞中描述 schema，並要求模型呼叫一個工具，因為工具呼叫的參數本來就會嚴格遵守 JSON Schema。</p>
<pre><code>import anthropic

client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
tools = [{
    "name": "extract_person",
    "description": "Record the extracted person",
    "input_schema": {
        "type": "object",
        "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
        "required": ["name", "age"],
    },
}]
resp = client.messages.create(
    model="claude-opus-4-8", max_tokens=256,
    tool_choice={"type": "tool", "name": "extract_person"},
    tools=tools,
    messages=[{"role": "user", "content": "Maria is 34 years old."}],
)
data = next(b.input for b in resp.content if b.type == "tool_use")</code></pre>

<h2 id="解析仍然失敗時的備援做法">解析仍然失敗時的備援做法</h2>
<p>即使使用了 schema，也請把回應視為不可信的輸入：過長的上下文、奇特的邊界情況或模型本身的限制，仍可能產生損壞的輸出。請用重試機制包住解析步驟：</p>
<pre><code>import json

def extract(prompt, retries=2):
    last_err = None
    for _ in range(retries + 1):
        resp = client.chat.completions.create(model="gpt-6-luna", response_format=schema,
                                                messages=[{"role": "user", "content": prompt}])
        try:
            return json.loads(resp.choices[0].message.content)
        except json.JSONDecodeError as e:
            last_err = e
    raise last_err</code></pre>
<p>即使 API 已在伺服器端強制套用 schema，使用前也請在程式碼中再用 schema 驗證解析後的物件（可使用 <code>pydantic</code> 或 <code>jsonschema</code> 等函式庫）。模型填入的任何欄位，在進入資料庫查詢、shell 指令或檔案路徑之前，都應該像使用者輸入一樣視為不可信。</p>

<h2 id="模型支援">模型支援</h2>
<p>各模型對 JSON Schema 的支援程度不同；在依賴 <code>strict: true</code> 之前，請先查看<a href="https://aidiscount.ai/models">市集</a>中模型頁面的功能清單。以下是幾個支援結構化輸出的模型：</p>
<table><tr><th>模型</th><th>輸入 / 百萬 tokens</th><th>輸出 / 百萬 tokens</th><th>與官方價格比較</th></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/gpt-6-luna">GPT-6 Luna</a><br><code>gpt-6-luna</code></td><td>$0.05</td><td>$0.30</td><td>優惠 40%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/claude-opus-4-8">Claude Opus 4.8</a><br><code>claude-opus-4-8</code></td><td>$0.375</td><td>$1.875</td><td>優惠 92.5%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-v4-pro">DeepSeek V4 Pro</a><br><code>deepseek-v4-pro</code></td><td>$0.3857</td><td>$1.1571</td><td>優惠 41.6%</td></tr></table><p class="meta">價格於產生本頁時從<a href="https://aidiscount.ai/models">模型廣場</a>即時讀取，可能會變動，請以模型廣場顯示的目前價格為準。</p>
]]></content:encoded></item><item><title>函式呼叫與工具使用：實用指南</title><link>https://aidiscount.ai/zh-hant/blog/function-calling-tool-use-guide</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/function-calling-tool-use-guide</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>說明函式呼叫如何透過 OpenAI 相容 API 和 Anthropic Messages 運作，並附上完整的多輪範例，示範呼叫函式並回傳結果。</description><category>Function calling</category><category>Tool use</category><category>API</category><category>Python</category><content:encoded><![CDATA[<p>函式呼叫（function calling，也稱為工具使用 tool use）讓模型可以請你的程式碼執行某個函式，而不是直接回答：例如查詢天氣 API、查詢資料庫或進行計算，再用得到的結果完成回答。模型本身從不執行任何東西；它只會回傳一個「以特定參數呼叫某函式」的請求，而是否真的執行，由你的程式碼決定。</p>

<h2 id="請求的結構">請求的結構</h2>
<p>你要用 JSON Schema 描述每個可用的函式：名稱、說明，以及參數的結構。</p>
<pre><code>tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name, e.g. Tokyo"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["city"],
        },
    },
}]</code></pre>
<p>模型會依據函式說明和參數說明來決定何時以及如何呼叫函式，所以請像向另一個人解釋這個函式那樣撰寫說明，而不只是寫出型別簽章。</p>

<h2 id="完整的多輪範例">完整的多輪範例</h2>
<p>工具呼叫並不是對話的終點。模型會暫停，由你執行函式，再把結果放在一則新訊息中送回，讓模型繼續作答。</p>
<pre><code>import json
from openai import OpenAI

client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])

def get_weather(city, unit="celsius"):
    return {"city": city, "temperature": 18, "unit": unit, "condition": "cloudy"}

messages = [{"role": "user", "content": "What's the weather in Tokyo right now?"}]

resp = client.chat.completions.create(model="gpt-6-luna", messages=messages, tools=tools)
msg = resp.choices[0].message
messages.append(msg)

if msg.tool_calls:
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_weather(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })
    final = client.chat.completions.create(model="gpt-6-luna", messages=messages, tools=tools)
    print(final.choices[0].message.content)</code></pre>
<p>這個範例依賴的重點：先附加助理的工具呼叫訊息，再附加工具結果；讓每個 <code>tool_call_id</code> 對應到它所回覆的呼叫；並以字串形式送出 <code>content</code>（物件請用 <code>json.dumps</code> 編碼）。</p>

<h2 id="單輪中的多個工具呼叫">單輪中的多個工具呼叫</h2>
<p>模型可以一次要求多個工具呼叫，例如查詢三個城市的天氣。請逐一處理 <code>msg.tool_calls</code>，為每個呼叫附加一則 <code>"role": "tool"</code> 訊息，各自帶上對應的 <code>tool_call_id</code>，然後再呼叫模型。</p>

<h2 id="anthropic-messages-格式">Anthropic Messages 格式</h2>
<p>結構有所不同：每個工具的 schema 放在 <code>input_schema</code> 而非 <code>function.parameters</code>；工具呼叫會以 <code>tool_use</code> 內容區塊送達；結果則要以 <code>tool_result</code> 內容區塊放在使用者訊息中送回。</p>
<pre><code>import anthropic

client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
tools = [{
    "name": "get_weather",
    "description": "Get the current weather for a city",
    "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"],
    },
}]

messages = [{"role": "user", "content": "What's the weather in Tokyo right now?"}]
resp = client.messages.create(model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools)
messages.append({"role": "assistant", "content": resp.content})

tool_use = next(b for b in resp.content if b.type == "tool_use")
result = get_weather(**tool_use.input)
messages.append({
    "role": "user",
    "content": [{"type": "tool_result", "tool_use_id": tool_use.id, "content": json.dumps(result)}],
})
final = client.messages.create(model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools)
print(final.content[0].text)</code></pre>

<h2 id="強制或停用工具使用">強制或停用工具使用</h2>
<p>預設情況下，由模型決定是否呼叫工具。若要強制使用某個特定工具，請傳入 <code>tool_choice={"type": "function", "function": {"name": "get_weather"}}</code>（OpenAI 格式）或 <code>tool_choice={"type": "tool", "name": "get_weather"}</code>（Anthropic 格式）。若要在保留工具定義的同時，讓模型在某次請求中不呼叫工具，請設定 <code>tool_choice="none"</code>（OpenAI 格式）或 <code>tool_choice={"type": "none"}</code>（Anthropic 格式）。</p>

<h2 id="常見錯誤">常見錯誤</h2>
<ul>
<li><strong>用錯誤的角色回傳工具結果。</strong>OpenAI 格式要求使用 <code>"role": "tool"</code>；它不接受以一般的使用者或助理訊息回傳結果。</li>
<li><strong>忘了把助理的工具呼叫訊息送回去。</strong>模型需要在對話紀錄中看到自己的工具呼叫，才能把它和結果連結起來。</li>
<li><strong>在 <code>content</code> 中送出原始 Python 物件</strong>，而不是 JSON 字串。請一律用 <code>json.dumps</code> 序列化。</li>
<li><strong>執行函式前沒有驗證參數。</strong>請把工具呼叫的參數視為來自模型的不可信輸入；在採取行動前先驗證型別和範圍，尤其是在將它們用於資料庫查詢或 shell 指令之前。</li>
</ul>

<h2 id="挑選模型">挑選模型</h2>
<p>AIDiscount 上大多數現行模型都支援工具呼叫；<a href="https://aidiscount.ai/models">市集</a>中的模型頁面會在功能清單中列出。以下是幾個支援工具的模型及其目前價格：</p>
<table><tr><th>模型</th><th>輸入 / 百萬 tokens</th><th>輸出 / 百萬 tokens</th><th>與官方價格比較</th></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/gpt-6-luna">GPT-6 Luna</a><br><code>gpt-6-luna</code></td><td>$0.05</td><td>$0.30</td><td>優惠 40%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/claude-opus-4-8">Claude Opus 4.8</a><br><code>claude-opus-4-8</code></td><td>$0.375</td><td>$1.875</td><td>優惠 92.5%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/deepseek-v4-pro">DeepSeek V4 Pro</a><br><code>deepseek-v4-pro</code></td><td>$0.3857</td><td>$1.1571</td><td>優惠 41.6%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/kimi-k3">Kimi K3</a><br><code>kimi-k3</code></td><td>$1.714</td><td>$8.571</td><td>優惠 42.9%</td></tr><tr><td><a href="https://aidiscount.ai/zh-hant/models/glm-5.3">GLM-5.3</a><br><code>glm-5.3</code></td><td>$0.6857</td><td>$2.40</td><td>優惠 45.5%</td></tr></table><p class="meta">價格於產生本頁時從<a href="https://aidiscount.ai/models">模型廣場</a>即時讀取，可能會變動，請以模型廣場顯示的目前價格為準。</p>
]]></content:encoded></item><item><title>如何修正常見的 AI API 錯誤：401、403、404、429 與 5xx</title><link>https://aidiscount.ai/zh-hant/blog/fix-ai-api-errors-401-403-404-429</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/fix-ai-api-errors-401-403-404-429</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>說明 AI API 回傳的各種 HTTP 錯誤代表什麼、該如何修正，並附上處理速率限制與暫時性伺服器錯誤的重試程式碼。</description><category>Errors</category><category>Troubleshooting</category><category>API</category><content:encoded><![CDATA[<p>AI API 請求失敗時，HTTP 狀態碼會告訴你該從哪裡查起。本文整理了 OpenAI 或 Anthropic 相容 API 最常出現的狀態碼、發生原因，以及處理方式。</p>

<h2 id="快速對照表">快速對照表</h2>
<table>
<tr><th>狀態碼</th><th>意義</th><th>要重試嗎？</th></tr>
<tr><td>400</td><td>請求內容無效。</td><td>不用。請修正請求。</td></tr>
<tr><td>401</td><td>缺少金鑰、金鑰錯誤或已被刪除。</td><td>不用。請修正金鑰。</td></tr>
<tr><td>403</td><td>金鑰有效但沒有權限，通常是因為餘額不足。</td><td>不用。請儲值或更換方案。</td></tr>
<tr><td>404</td><td>路徑或 Base URL 錯誤，或模型不存在。</td><td>不用。請修正網址或模型。</td></tr>
<tr><td>429</td><td>請求過多，或已達用量上限。</td><td>要，並搭配退避（backoff）。</td></tr>
<tr><td>500, 502, 503, 504</td><td>伺服器或上游的暫時性錯誤。</td><td>要，並搭配退避（backoff）。</td></tr>
</table>

<h2 id="400-bad-request">400 Bad Request</h2>
<p>伺服器無法接受這個請求。請閱讀回應內容中的錯誤訊息，通常會指出是哪個欄位出問題。常見原因：</p>
<ul>
<li>JSON 格式錯誤，常見於 shell 指令中的引號沒有跳脫。</li>
<li><code>messages</code> 清單是空的，或含有無效的 <code>role</code>。</li>
<li><code>max_tokens</code> 超過模型允許的上限，或提示詞超出上下文視窗長度。</li>
<li>Anthropic 格式的請求缺少 <code>max_tokens</code>，而這個格式規定必須提供。</li>
</ul>

<h2 id="401-unauthorized">401 Unauthorized</h2>
<p>API 無法辨識這把金鑰。</p>
<ul>
<li>檢查標頭。OpenAI 格式使用 <code>Authorization: Bearer sk-...</code>，Anthropic 格式使用 <code>x-api-key: sk-...</code>。</li>
<li>檢查複製金鑰時是否帶到了空白或換行。</li>
<li>確認發出請求的 shell 或程序中有設定環境變數。執行 <code>echo $AIDISCOUNT_API_KEY</code> 應該會印出金鑰。</li>
<li>一家供應商的金鑰無法在另一家使用。如果你換了 Base URL，金鑰也要跟著換。</li>
<li>如果金鑰已在 API Keys 頁面刪除，請建立一把新的。</li>
</ul>
<p>在 AIDiscount 上，對應的錯誤代碼是 <code>INVALID_API_KEY</code>。</p>

<h2 id="403-forbidden">403 Forbidden</h2>
<p>金鑰有效，但這個請求不被允許。在 AIDiscount 上最常見的代碼是 <code>INSUFFICIENT_BALANCE</code>：請到 Pricing 頁面儲值或購買方案。403 也可能表示你的金鑰所屬群組無法使用該模型。可以查詢金鑰可用的模型清單：</p>
<pre><code>curl https://aidiscount.ai/v1/models \
  -H "Authorization: Bearer $AIDISCOUNT_API_KEY"</code></pre>

<h2 id="404-not-found">404 Not Found</h2>
<p>幾乎都是 Base URL 的問題。</p>
<ul>
<li>OpenAI 格式：完整路徑是 <code>https://aidiscount.ai/v1/chat/completions</code>。SDK 和大多數工具要求的 Base URL 是 <code>https://aidiscount.ai/v1</code>。</li>
<li>Anthropic SDK 和 Claude Code：Base URL 是 <code>https://aidiscount.ai</code>，不加 <code>/v1</code>，因為它們會自己加上 <code>/v1/messages</code>。</li>
<li>有些應用程式會自動加上 <code>/v1</code>。如果你也手動加了，路徑就會變成 <code>/v1/v1/...</code>。請分別試試有加和沒加 <code>/v1</code> 的 Base URL。</li>
<li>模型 ID 拼錯也可能回傳 404 或「model not found」。請從<a href="https://aidiscount.ai/models">市集</a>複製 ID。</li>
</ul>

<h2 id="429-too-many-requests">429 Too Many Requests</h2>
<p>你送出請求的速度超過允許範圍，或已達用量上限（例如方案的每週額度）。請放慢速度，並以指數退避的方式重試。如果回應中有 <code>Retry-After</code> 標頭，至少要等待那麼久。如果上限來自方案額度，請等額度重置，或改用隨用隨付的餘額。</p>

<h2 id="5xx-伺服器錯誤">5xx 伺服器錯誤</h2>
<p>500、502、503 和 504 通常代表上游發生暫時性問題。請搭配退避重試。耗時較長的請求也可能在你這端逾時，因此輸出較長時請使用串流，讓連線保持活動。</p>

<h2 id="重試程式碼">重試程式碼</h2>
<p>官方 OpenAI SDK 預設就會對 429 和 5xx 錯誤重試兩次。你可以調高次數：</p>
<pre><code>from openai import OpenAI
client = OpenAI(base_url="https://aidiscount.ai/v1", max_retries=5, timeout=120)</code></pre>
<p>不使用 SDK 的話，一個簡單的退避迴圈就夠用：</p>
<pre><code>import os, random, time, requests

def call(payload, attempts=5):
    for i in range(attempts):
        r = requests.post(
            "https://aidiscount.ai/v1/chat/completions",
            headers={"Authorization": f"Bearer {os.environ['AIDISCOUNT_API_KEY']}"},
            json=payload, timeout=120,
        )
        if r.status_code not in (429, 500, 502, 503, 504):
            r.raise_for_status()
            return r.json()
        wait = float(r.headers.get("Retry-After", 0)) or (2 ** i + random.random())
        time.sleep(wait)
    r.raise_for_status()</code></pre>
<p>不要重試 400、401、403 或 404。同樣的請求只會以同樣的方式失敗。</p>

<h2 id="還是無法解決">還是無法解決？</h2>
<p>請記下請求的時間和回應標頭中的請求 ID，並透過網站頁尾的連結聯絡客服。客服訊息中絕對不要附上你的 API 金鑰。</p>
]]></content:encoded></item><item><title>如何在 Cursor、Cline 和 Continue 中使用自訂的 OpenAI 相容 API</title><link>https://aidiscount.ai/zh-hant/blog/cursor-cline-continue-custom-api</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/cursor-cline-continue-custom-api</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>逐步說明如何在 Cursor、Cline 和 Continue 中使用自己的 API 金鑰與 Base URL，並列出模型沒有回應時該檢查哪些設定。</description><category>Cursor</category><category>Cline</category><category>Continue</category><category>Coding tools</category><content:encoded><![CDATA[<p>Cursor、Cline 和 Continue 都能把請求送到任何 OpenAI 相容的 API。你需要準備三樣東西：</p>
<ul>
<li><strong>Base URL：</strong> <code>https://aidiscount.ai/v1</code></li>
<li><strong>API 金鑰：</strong> 以 <code>sk-</code> 開頭的金鑰，<a href="https://aidiscount.ai/register">註冊</a>後在 API Keys 頁面建立</li>
<li><strong>模型 ID：</strong> 從<a href="https://aidiscount.ai/models">模型市集</a>原封不動複製，例如 <code>deepseek-v4.1-flash</code> 或 <code>glm-5.3</code></li>
</ul>

<h2 id="cline-vs-code">Cline（VS Code）</h2>
<ol>
<li>開啟 Cline 面板，點選設定（齒輪）圖示。</li>
<li>將 <strong>API Provider</strong> 設為 <strong>OpenAI Compatible</strong>。</li>
<li>將 <strong>Base URL</strong> 設為 <code>https://aidiscount.ai/v1</code>。</li>
<li>把金鑰貼到 <strong>API Key</strong>。</li>
<li>在 <strong>Model ID</strong> 輸入模型 ID。</li>
<li>儲存後，送出一個簡單的任務，例如「列出這個資料夾裡的檔案」。</li>
</ol>
<p>Cline 會大量使用工具呼叫（tool calling），請選擇市集頁面上標示支援工具呼叫的模型。</p>
<p>Cline 也提供可自訂 Base URL 的 <strong>Anthropic</strong> 供應商選項。如果你偏好 Anthropic 格式，請使用 Base URL <code>https://aidiscount.ai</code>（不加 <code>/v1</code>）。</p>

<h2 id="continue-vs-code-與-jetbrains">Continue（VS Code 與 JetBrains）</h2>
<p>Continue 會從設定檔讀取模型。從 Continue 面板開啟設定檔（點齒輪圖示，再開啟設定檔），然後新增一筆模型設定：</p>
<pre><code>name: My Config
version: 0.0.1
schema: v1
models:
  - name: AIDiscount
    provider: openai
    model: YOUR_MODEL_ID
    apiBase: https://aidiscount.ai/v1
    apiKey: ${{ secrets.AIDISCOUNT_API_KEY }}
    roles:
      - chat
      - edit
      - apply</code></pre>
<p>把 <code>YOUR_MODEL_ID</code> 換成市集上的模型 ID。你也可以不用 secret，直接把金鑰貼進 <code>apiKey</code>，但這樣就不要把這個檔案提交到程式碼儲存庫。</p>
<p>自動完成需要速度快又便宜的模型。如果你另外設定了 <code>autocomplete</code> 角色的模型，請選小型模型以控制成本。</p>

<h2 id="cursor">Cursor</h2>
<ol>
<li>開啟 <strong>Cursor Settings</strong>，進入 <strong>Models</strong>。</li>
<li>在 <strong>API Keys</strong> 底下開啟 <strong>OpenAI API Key</strong>，貼上你的 AIDiscount 金鑰。</li>
<li>開啟 <strong>Override OpenAI Base URL</strong>，輸入 <code>https://aidiscount.ai/v1</code>。</li>
<li>點選 <strong>Verify</strong>。</li>
<li>用 <strong>Add model</strong> 加入模型 ID，啟用後在聊天面板中選取。</li>
</ol>
<p>有兩個限制值得注意：</p>
<ul>
<li>Cursor 的請求會先經過 Cursor 自己的伺服器，再送到 Base URL。因此這個網址必須能從公開網路連線，像 <code>localhost</code> 這樣的本機位址無法使用。</li>
<li>Cursor 的部分功能（例如 Tab 自動完成）一律使用 Cursor 自己的模型。自訂金鑰只會套用在聊天和你自行加入的模型上。</li>
</ul>
<p>Cursor 的選單在不同版本間會有變動。如果上面的名稱對不上，請到 Models 底下找 OpenAI 金鑰和 Base URL 的設定。</p>

<h2 id="如果模型沒有回應">如果模型沒有回應</h2>
<table>
<tr><th>症狀</th><th>可能原因</th></tr>
<tr><td>404 或「Not Found」</td><td>Base URL 少了 <code>/v1</code>，或 <code>/v1</code> 重複出現。</td></tr>
<tr><td>401 或「Invalid API key」</td><td>金鑰錯誤、貼上時多了空白，或金鑰已被刪除。</td></tr>
<tr><td>「Model not found」</td><td>模型 ID 打錯，或用了其他供應商的命名方式。請從市集複製。</td></tr>
<tr><td>403「Insufficient balance」</td><td>請儲值或購買方案。</td></tr>
<tr><td>代理程式停住，或在工具呼叫上無限循環</td><td>模型不擅長使用工具。改用較大的模型試試。</td></tr>
</table>
<p>更多細節請參考<a href="https://aidiscount.ai/zh-hant/blog/fix-ai-api-errors-401-403-404-429">如何修正常見的 AI API 錯誤</a>。</p>

<h2 id="留意成本">留意成本</h2>
<p>程式設計代理程式每一步都會送出整段對話和大量檔案內容，因此消耗的輸入 token 遠多於一般聊天。用過幾次之後，請到控制台的 Usage 頁面查看用量。<a href="https://aidiscount.ai/zh-hant/blog/reduce-ai-api-costs">如何降低 AI API 成本</a>介紹了壓低費用的方法。</p>
]]></content:encoded></item><item><title>在 Cherry Studio、Chatbox、LobeChat 和 Open WebUI 中新增自訂 API 供應商</title><link>https://aidiscount.ai/zh-hant/blog/chat-apps-custom-api-provider</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/chat-apps-custom-api-provider</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>如何把桌面版與網頁版聊天應用程式連接到 OpenAI 相容 API：Base URL 和金鑰要填在哪裡、如何新增模型，以及常見 404 的解法。</description><category>Cherry Studio</category><category>Chatbox</category><category>LobeChat</category><category>Open WebUI</category><category>Chat apps</category><content:encoded><![CDATA[<p>Cherry Studio、Chatbox、LobeChat 和 Open WebUI 這類聊天應用程式都能使用你自己的 API 金鑰。搭配 OpenAI 相容的供應商，你可以在同一個應用程式裡使用多家廠商的模型，並且用多少付多少，不必每家廠商各付一份月費。</p>
<p>每個應用程式都需要同樣三項資訊：</p>
<ul>
<li><strong>API 主機或 Base URL：</strong> <code>https://aidiscount.ai/v1</code>（如果應用程式會自動加上 <code>/v1</code>，則填 <code>https://aidiscount.ai</code>）</li>
<li><strong>API 金鑰：</strong> 在 API Keys 頁面取得的 <code>sk-...</code> 金鑰</li>
<li><strong>模型 ID：</strong> 從<a href="https://aidiscount.ai/models">模型市集</a>取得，或由應用程式自動抓取</li>
</ul>

<h2 id="cherry-studio">Cherry Studio</h2>
<ol>
<li>開啟 <strong>Settings</strong>（設定），再進入 <strong>Model Provider</strong>（模型服務），點選 <strong>Add</strong>（新增）。</li>
<li>輸入名稱（例如 AIDiscount），供應商類型選擇 <strong>OpenAI</strong>。</li>
<li>把金鑰貼到 <strong>API Key</strong>。</li>
<li>將 <strong>API Host</strong> 設為 <code>https://aidiscount.ai</code>。Cherry Studio 會自動加上 <code>/v1</code>。</li>
<li>點選 <strong>Manage</strong>（管理）抓取模型清單，或手動加入模型 ID。</li>
<li>點選 <strong>Check</strong>（檢查）測試連線。</li>
</ol>

<h2 id="chatbox">Chatbox</h2>
<ol>
<li>開啟 <strong>Settings</strong>（設定），新增一個自訂供應商。</li>
<li>選擇 OpenAI API 相容模式。</li>
<li>將 API 主機設為 <code>https://aidiscount.ai/v1</code>。如果測試請求回傳 404，就把 <code>/v1</code> 拿掉。</li>
<li>貼上金鑰並加入模型 ID。</li>
</ol>

<h2 id="lobechat">LobeChat</h2>
<p>如果使用雲端版或桌面版，請開啟 <strong>Settings</strong>（設定），再進入 <strong>AI Service Provider</strong>（AI 服務供應商），編輯 OpenAI 供應商或新增一個自訂供應商。將 API 代理位址設為 <code>https://aidiscount.ai/v1</code>，貼上金鑰，再抓取或加入模型。</p>
<p>如果是自行架設的 Docker 部署，改為設定環境變數：</p>
<pre><code>OPENAI_API_KEY=sk-...
OPENAI_PROXY_URL=https://aidiscount.ai/v1</code></pre>

<h2 id="open-webui">Open WebUI</h2>
<ol>
<li>以管理員身分登入，依序開啟 <strong>Admin Panel</strong>（管理員面板）、<strong>Settings</strong>（設定）、<strong>Connections</strong>（連線）。</li>
<li>在 OpenAI API 底下新增連線，網址填 <code>https://aidiscount.ai/v1</code>，並填入你的金鑰。</li>
<li>儲存。Open WebUI 會呼叫 <code>/v1/models</code>，列出你的金鑰可用的模型。</li>
</ol>
<p>使用 Docker 時，可以在啟動時就設定好連線：</p>
<pre><code>docker run -d -p 3000:8080 \
  -e OPENAI_API_BASE_URL=https://aidiscount.ai/v1 \
  -e OPENAI_API_KEY=sk-... \
  -v open-webui:/app/backend/data \
  --name open-webui ghcr.io/open-webui/open-webui:main</code></pre>

<h2 id="最常見的問題-404">最常見的問題：404</h2>
<p>出現 404 幾乎都是 <code>/v1</code> 這段填錯了。有些應用程式要求網址包含 <code>/v1</code>，有些則會自己加上。如果一種寫法不行，就換另一種：</p>
<ul>
<li><code>https://aidiscount.ai/v1</code></li>
<li><code>https://aidiscount.ai</code></li>
</ul>
<p>其他錯誤請參考<a href="https://aidiscount.ai/zh-hant/blog/fix-ai-api-errors-401-403-404-429">如何修正常見的 AI API 錯誤</a>。</p>

<h2 id="保護好你的金鑰">保護好你的金鑰</h2>
<p>桌面應用程式會把金鑰存在你的電腦上。多人共用的自架網頁應用程式則把金鑰存在伺服器上，所有使用該站台的人都會花用同一筆餘額。如果懷疑金鑰外洩，請到 API Keys 頁面刪除它，金鑰會立即失效。接著再建立一把新的金鑰。</p>
]]></content:encoded></item><item><title>API 金鑰安全：安全地儲存、設定範圍與輪換金鑰</title><link>https://aidiscount.ai/zh-hant/blog/api-key-security-best-practices</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/api-key-security-best-practices</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>處理 AI API 金鑰的實用原則：環境變數、絕不把金鑰送到瀏覽器端、每個專案使用獨立金鑰，以及金鑰外洩後該怎麼做。</description><category>API keys</category><category>Security</category><category>Best practices</category><content:encoded><![CDATA[<p>API 金鑰是一種持有即可用的憑證：任何握有它的人都能動用你的額度來付費。請把它當成密碼對待，而不是可以隨意放著不管的設定值。</p>

<h2 id="將金鑰存為環境變數-不要寫進程式碼">將金鑰存為環境變數，不要寫進程式碼</h2>
<p>絕對不要把金鑰以字面字串的形式寫進原始碼檔案中，請從環境變數讀取：</p>
<pre><code># Python
import os
api_key = os.environ["AIDISCOUNT_API_KEY"]

# Node.js
const apiKey = process.env.AIDISCOUNT_API_KEY;</code></pre>
<p>本機開發時，請把變數放進 <code>.env</code> 檔案，並<em>在建立這個檔案之前</em>先把 <code>.env</code> 加進 <code>.gitignore</code>，這樣不小心執行 <code>git add .</code> 時才不會把它一起加進去。在 CI/CD 和主機平台上，請透過平台本身的密鑰功能設定金鑰（例如 GitHub Actions 的 secrets、你所用主機的環境變數設定），絕對不要寫進已提交的工作流程檔案或 Dockerfile 中。</p>

<h2 id="絕不把金鑰放進前端或行動裝置程式碼">絕不把金鑰放進前端或行動裝置程式碼</h2>
<p>任何送到瀏覽器或行動應用程式的內容都是公開的，無論經過什麼混淆或壓縮處理都一樣。嵌在用戶端 JavaScript、行動應用程式二進位檔或瀏覽器擴充功能中的金鑰，在發布後幾小時內就會被抽取出來；這種事經常被自動化工具執行，這些爬蟲專門掃描公開程式庫和已發布的應用程式套件，尋找形似金鑰的字串。如果某個功能需要從瀏覽器端發出 AI 呼叫，請加一個小型後端端點，把金鑰保留在伺服器端並轉送請求，讓瀏覽器永遠只與你自己的伺服器溝通。</p>

<h2 id="每個專案或環境使用獨立的金鑰">每個專案或環境使用獨立的金鑰</h2>
<p>一個金鑰用在所有地方，代表一次外洩就會影響所有地方，而且單一金鑰的用量突然飆升，也無法告訴你是哪個應用程式造成的。請到控制台的 API Keys 頁面，為每個應用程式建立獨立的金鑰，並為開發、測試和正式環境分別建立不同的金鑰。如果發生外洩，你可以只撤銷受影響的那一個金鑰，而不會動到其他一切；Usage 頁面也會清楚顯示是哪個金鑰在消耗額度。</p>

<h2 id="只給每個金鑰它所需要的權限">只給每個金鑰它所需要的權限</h2>
<p>如果某個金鑰只需要存取一部分模型，或只需要較低的速率限制，就依此設定範圍，而不是發一個在各處都有完整權限的金鑰。範圍較窄的金鑰可以限制外洩時造成的損害。</p>

<h2 id="金鑰外洩時會發生什麼事">金鑰外洩時會發生什麼事</h2>
<p>外洩的金鑰通常很快就會被找到，而且多半是靠自動化掃描工具，而不是有人手動看過你的程式碼：公開的 GitHub 程式庫、貼文平台、瀏覽器擴充功能原始碼、用戶端 JavaScript 套件，甚至是網路上貼出的截圖或錄影畫面，都會持續被掃描，尋找形似金鑰的字串。一旦被找到，金鑰通常會在幾分鐘內就被濫用進行自動化大量呼叫，直到額度耗盡或金鑰被撤銷為止。</p>
<p>如果你懷疑金鑰外洩了：</p>
<ol>
<li><strong>立即到 API Keys 頁面撤銷它。</strong>撤銷會馬上生效。</li>
<li><strong>建立一個新金鑰</strong>，並更新舊金鑰曾被使用過的每一個地方。</li>
<li><strong>查看 Usage 頁面</strong>中對應時間段的紀錄，確認這個金鑰實際上被用來執行了什麼。</li>
<li><strong>先找出外洩的原因</strong>，之後才能視為問題已解決：搜尋你的 git 歷史紀錄（不只是最新一次提交，用 <code>git log -p</code> 檢查更早的提交，因為即使你後來移除了金鑰，舊的提交中仍可能留有它），並檢查 CI 紀錄，以及任何公開的程式庫或 gist。</li>
</ol>
<p>已經提交進 git 歷史紀錄的金鑰，光靠在新的提交中刪掉那一行是解決不了的；舊的提交中仍然保有它。你可以在自己掌控的程式庫上重寫歷史紀錄（使用 <code>git filter-repo</code> 或 BFG Repo-Cleaner），或者直接把這個金鑰視為已經作廢並換發新的，這種做法通常比在共用的程式庫上重寫歷史紀錄更快也更安全。</p>

<h2 id="定期輪換金鑰-不要只在外洩後才換">定期輪換金鑰，不要只在外洩後才換</h2>
<p>即使沒有已知的外洩事件，定期輪換金鑰也能限制一個悄悄外洩（卻一直沒被發現）的金鑰，能被持有者利用多久。請先發行新金鑰、更新你的應用程式、確認一切正常運作，然後才撤銷舊金鑰，而不要先撤銷再在壓力下緊急除錯因此造成的服務中斷。</p>

<h2 id="檢查清單">檢查清單</h2>
<ul>
<li>金鑰存放在環境變數或密鑰管理工具中，絕不放在已提交的檔案裡。</li>
<li><code>.env</code> 在建立檔案之前就已經加進 <code>.gitignore</code>。</li>
<li>任何前端、行動裝置或瀏覽器擴充功能程式碼中都沒有出現金鑰。</li>
<li>每個應用程式、每個環境（開發／測試／正式）都使用獨立的金鑰。</li>
<li>事先就寫好「如果這個金鑰外洩了該怎麼做」的應變計畫，而不是等事情發生後才臨時應對。</li>
</ul>
]]></content:encoded></item><item><title>在不同的 API 供應商中使用官方 Anthropic SDK</title><link>https://aidiscount.ai/zh-hant/blog/anthropic-sdk-custom-base-url</link><guid isPermaLink="true">https://aidiscount.ai/zh-hant/blog/anthropic-sdk-custom-base-url</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>說明如何讓官方的 Anthropic Python、TypeScript 和 Claude Code 用戶端指向另一個 Messages API 端點，並說明應該使用的正確 base URL。</description><category>Anthropic</category><category>Claude Code</category><category>API</category><category>Python</category><category>Node.js</category><content:encoded><![CDATA[<p>官方的 Anthropic SDK 是與 Messages API（<code>/v1/messages</code>）溝通。任何實作相同請求與回應結構的伺服器，都可以透過變更 base URL 和金鑰來頂替其後端；SDK 本身不需要知道它並不是在跟 Anthropic 自家的伺服器對話。</p>

<h2 id="base-url-是帳號根網址-不是完整路徑">base URL 是帳號根網址，不是完整路徑</h2>
<p>最常見的錯誤是：Anthropic SDK 本身就會加上 <code>/v1/messages</code>，所以 base URL 應該是 <code>https://aidiscount.ai</code>，不含 <code>/v1</code>。如果自己再加一次 <code>/v1</code>，就會在 <code>/v1/v1/messages</code> 上得到 404 錯誤。</p>

<h2 id="python">Python</h2>
<pre><code>import os
import anthropic

client = anthropic.Anthropic(
    base_url="https://aidiscount.ai",
    api_key=os.environ["AIDISCOUNT_API_KEY"],
)
resp = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Explain photosynthesis in two sentences."}],
)
print(resp.content[0].text)</code></pre>
<p>base URL 也可以用 <code>ANTHROPIC_BASE_URL</code> 環境變數設定，而不必傳入 <code>base_url</code>，這在你不想動到以無參數方式建立用戶端的既有程式碼時很方便。</p>

<h2 id="typescript-javascript">TypeScript / JavaScript</h2>
<pre><code>import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  baseURL: "https://aidiscount.ai",
  apiKey: process.env.AIDISCOUNT_API_KEY,
});
const resp = await client.messages.create({
  model: "claude-opus-4-8",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Explain photosynthesis in two sentences." }],
});
console.log(resp.content[0].text);</code></pre>

<h2 id="claude-code">Claude Code</h2>
<p>Claude Code 會從環境變數讀取同樣的兩項設定：</p>
<pre><code>export ANTHROPIC_BASE_URL="https://aidiscount.ai"
export ANTHROPIC_AUTH_TOKEN="$AIDISCOUNT_API_KEY"
claude</code></pre>
<p><code>ANTHROPIC_AUTH_TOKEN</code> 會把金鑰以 bearer token 的形式送出。Claude Code 也接受 <code>ANTHROPIC_API_KEY</code>，但這樣可能會在第一次啟動時要求你確認金鑰。這兩者只需設定一個。</p>

<h2 id="curl-作為對照">curl，作為對照</h2>
<pre><code>curl https://aidiscount.ai/v1/messages \
  -H "x-api-key: $AIDISCOUNT_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{"model": "claude-opus-4-8", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello"}]}'</code></pre>
<p>請注意標頭名稱：是 <code>x-api-key</code>，不是 <code>Authorization: Bearer</code>。SDK 會依照 <code>api_key</code> 自動為你設定這個標頭；只有在直接呼叫 API 時，才需要自己手動設定。</p>

<h2 id="串流與工具">串流與工具</h2>
<p>一旦 base URL 指向別處，串流和工具這兩項功能都能和使用 Anthropic 自家 API 時完全一樣運作，因為 SDK 的串流與工具使用程式碼並不依賴另一端是哪個伺服器。Anthropic 格式的範例請參閱<a href="https://aidiscount.ai/zh-hant/blog/stream-ai-api-responses">串流指南</a>和<a href="https://aidiscount.ai/zh-hant/blog/function-calling-tool-use-guide">工具使用指南</a>。</p>

<h2 id="模型名稱">模型名稱</h2>
<p>只要是 <a href="https://aidiscount.ai/models">市集</a>中支援 Anthropic Messages 協定的模型 ID，都可以直接當作 <code>model</code> 欄位傳入；一旦 base URL 已經改變，模型名稱就不再與 Anthropic 本身綁定。</p>

<h2 id="常見錯誤">常見錯誤</h2>
<ul>
<li><strong>base URL 中仍保留 <code>/v1</code>。</strong>會導致在 <code>/v1/v1/messages</code> 上出現 404 錯誤。</li>
<li><strong>用原始的 <code>fetch</code> 呼叫時使用 <code>Authorization: Bearer</code>。</strong>Messages API 要求的是 <code>x-api-key</code>；SDK 會自動處理這點，但手動寫的請求必須明確設定這個標頭。</li>
<li><strong>遺漏 <code>anthropic-version</code>。</strong>每個直接的 HTTP 請求都必須帶上這個標頭；官方 SDK 會自動設定。</li>
<li><strong>忘記設定 <code>max_tokens</code>。</strong>Messages API 要求每個請求都必須帶上這個參數，沒有預設值。</li>
</ul>
]]></content:encoded></item></channel></rss>
