<?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 Blog</title><link>https://aidiscount.ai/blog</link><atom:link href="https://aidiscount.ai/blog/rss.xml" rel="self" type="application/rss+xml"/><description>AI API guides and tutorials from AIDiscount</description><language>en</language><lastBuildDate>Wed, 25 Nov 2026 00:00:00 +0000</lastBuildDate><item><title>Use Claude Code, Codex CLI and OpenCode with a Third-Party API</title><link>https://aidiscount.ai/blog/terminal-coding-agents-custom-provider</link><guid isPermaLink="true">https://aidiscount.ai/blog/terminal-coding-agents-custom-provider</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>Configuration for running terminal coding agents through a third-party API: environment variables for Claude Code, config.toml for Codex CLI and opencode.json for OpenCode.</description><category>Claude Code</category><category>Codex CLI</category><category>OpenCode</category><category>Coding tools</category><content:encoded><![CDATA[<p>Terminal coding agents read their API address and key from environment variables or a config file. Pointing them at another provider takes a few lines. This guide covers three popular agents. Each one uses a different API format, and AIDiscount accepts all three with the same key.</p>
<table>
<tr><th>Tool</th><th>API format</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 or Chat Completions</td><td><code>https://aidiscount.ai/v1</code></td></tr>
</table>
<p>Create a key on the API Keys page after you <a href="https://aidiscount.ai/register">sign up</a>. Get model IDs from the <a href="https://aidiscount.ai/models">model marketplace</a>.</p>

<h2 id="claude-code">Claude Code</h2>
<p>Set two environment variables before you run <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>Do not add <code>/v1</code> to the base URL. Claude Code adds <code>/v1/messages</code> itself.</p>
<p>To make the setting permanent, add the <code>export</code> lines to <code>~/.bashrc</code> or <code>~/.zshrc</code>. Alternatively, put them in the <code>env</code> block of <code>~/.claude/settings.json</code>:</p>
<pre><code>{
  "env": {
    "ANTHROPIC_BASE_URL": "https://aidiscount.ai",
    "ANTHROPIC_AUTH_TOKEN": "sk-..."
  }
}</code></pre>
<p>If you have previously logged in to Claude Code with an account, run <code>/logout</code> first so it uses the token from the environment.</p>

<h2 id="codex-cli">Codex CLI</h2>
<p>Add a provider to <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>Then set the key and start Codex:</p>
<pre><code>export AIDISCOUNT_API_KEY="sk-..."
codex</code></pre>
<p>With models that Codex does not know, it prints <code>Model metadata for ... not found. Defaulting to fallback metadata</code>. Requests still work. The warning means Codex does not know the model's context size. Tell it, so it compacts long sessions at the right point. For a model with a 200K-token context:</p>
<pre><code>model_context_window = 200000
model_auto_compact_token_limit = 160000</code></pre>
<p>Put these two lines at the top of <code>config.toml</code>. Use the context size shown on the model's page in the marketplace.</p>

<h2 id="opencode">OpenCode</h2>
<p>Add a provider to <code>opencode.json</code> (in your project, or in <code>~/.config/opencode/</code> for all projects):</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>The <code>@ai-sdk/openai</code> package uses the Responses API. If a model gives errors there, change the package to <code>@ai-sdk/openai-compatible</code>, which uses Chat Completions. The same key works for both.</p>

<h2 id="check-that-it-works">Check that it works</h2>
<ol>
<li>Ask the agent something small, such as "What files are in this folder?"</li>
<li>Open the Usage page in your AIDiscount dashboard. The request should appear with the model name and the amount charged.</li>
</ol>
<p>If nothing shows up, the agent is still using its previous provider. Check that the environment variables are set in the same terminal where you started the agent.</p>

<h2 id="choosing-a-model-for-agents">Choosing a model for agents</h2>
<p>Agents make many tool calls in a row and resend the conversation each time, so they use a lot of input tokens. A strong model makes fewer mistakes and needs fewer steps. A cheaper model costs less per step. A practical approach is to use a strong model for planning and hard bugs, and a cheaper one for routine edits. Prices for some lower-cost options:</p>
<table><tr><th>Model</th><th>Input / 1M tokens</th><th>Output / 1M tokens</th><th>vs. official price</th></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr></table><p class="meta">Prices are read from the live <a href="https://aidiscount.ai/models">model marketplace</a> when this page is generated and may change. The marketplace always shows the current rate.</p>
<p>For more on keeping agent costs down, see <a href="https://aidiscount.ai/blog/reduce-ai-api-costs">How to cut AI API costs</a>.</p>
]]></content:encoded></item><item><title>How to Stream AI API Responses in Python and Node.js</title><link>https://aidiscount.ai/blog/stream-ai-api-responses</link><guid isPermaLink="true">https://aidiscount.ai/blog/stream-ai-api-responses</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>How token streaming works over an OpenAI-compatible API, with working Python and Node.js code for server-sent events, and how to handle a dropped connection.</description><category>Streaming</category><category>Python</category><category>Node.js</category><category>API</category><content:encoded><![CDATA[<p>Streaming sends a model's answer as it is generated, instead of waiting for the full response. The app can show words as they arrive, like a chat interface typing them out. It also lets long answers start rendering immediately instead of waiting until the whole thing is done.</p>

<h2 id="how-it-works">How it works</h2>
<p>A normal API call returns one JSON object after the model finishes. A streaming call keeps the HTTP connection open and sends a sequence of small events using <strong>server-sent events (SSE)</strong>: each event is a line starting with <code>data: </code>, followed by a JSON chunk, ending with a line <code>data: [DONE]</code>. Every chunk carries a small piece of the answer (a "delta"), not the full text so far, so your code appends each piece to a buffer.</p>
<p>To turn streaming on with an OpenAI-compatible API, set <code>"stream": true</code> in the request body.</p>

<h2 id="python-with-the-openai-sdk">Python with the 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-with-raw-sse-no-sdk">Python with raw SSE (no 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-with-the-openai-sdk">Node.js with the 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-with-fetch-no-sdk">Node.js with fetch (no 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-format">Anthropic Messages format</h2>
<p>The event shape is different: each SSE event has a named <code>event:</code> line, and text arrives in <code>content_block_delta</code> events.</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="handling-a-dropped-connection">Handling a dropped connection</h2>
<p>A streaming request can fail partway through, after some text has already been shown. Tokens generated before the drop are usually still billed, so avoid retrying in a tight loop. In your UI, catch the error, keep whatever text arrived, and show a retry action instead of silently restarting from the beginning. If you do retry, send the same request again; a fresh request starts a fresh stream.</p>
<p>Behind a proxy or load balancer, make sure the connection is not buffered or closed early. Nginx needs <code>proxy_buffering off;</code> for routes that stream, and client timeouts should be long enough for a slow model to finish (streaming responses count as active traffic, not an idle connection, so most clients do not need special timeout handling for them).</p>

<h2 id="streaming-with-tool-calls">Streaming with tool calls</h2>
<p>When the model streams a tool call, the function name and arguments arrive in pieces too, split across multiple chunks. Buffer the <code>tool_calls</code> deltas by index and concatenate the <code>arguments</code> string until the stream ends, then parse it as JSON. Most SDKs do this buffering for you.</p>
]]></content:encoded></item><item><title>How to Cut AI API Costs: Model Choice, Context Size and Output Limits</title><link>https://aidiscount.ai/blog/reduce-ai-api-costs</link><guid isPermaLink="true">https://aidiscount.ai/blog/reduce-ai-api-costs</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>Practical ways to lower your AI API bill: pick the right model for each task, send less context, cap output length, reuse cached prompts and track spending per request.</description><category>Cost</category><category>Tokens</category><category>Pricing</category><content:encoded><![CDATA[<p>AI APIs bill by the token. A token is a few characters of text. You pay for the tokens you send (input) and the tokens the model writes back (output). Output tokens usually cost several times more than input tokens. Every saving comes from one of three things: a cheaper rate per token, fewer input tokens, or fewer output tokens.</p>

<h2 id="1-use-the-smallest-model-that-does-the-job">1. Use the smallest model that does the job</h2>
<p>Prices between models differ by more than ten times. Many tasks do not need the strongest model:</p>
<ul>
<li><strong>Small, fast models</strong> handle classification, extraction, short summaries, translation and autocomplete well.</li>
<li><strong>Large models</strong> are worth it for hard reasoning, long multi-step coding tasks and work where a wrong answer is expensive.</li>
</ul>
<p>Some lower-cost models and their current prices:</p>
<table><tr><th>Model</th><th>Input / 1M tokens</th><th>Output / 1M tokens</th><th>vs. official price</th></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr></table><p class="meta">Prices are read from the live <a href="https://aidiscount.ai/models">model marketplace</a> when this page is generated and may change. The marketplace always shows the current rate.</p>
<p>A common pattern is routing: send each request to a small model first, and only escalate to a large model when the task is hard or the small model's answer fails a check. Because an OpenAI-compatible API uses the same request format for every model, routing only means changing the <code>model</code> field.</p>

<h2 id="2-send-less-context">2. Send less context</h2>
<p>Input tokens add up quickly, because chat apps and agents resend the whole conversation with every message.</p>
<ul>
<li><strong>Start new conversations</strong> for new topics instead of continuing a long thread.</li>
<li><strong>Trim the history.</strong> Keep the system prompt and the last few turns, and replace older turns with a short summary.</li>
<li><strong>Send only the relevant parts</strong> of documents and code. Retrieval (search first, then send the matching chunks) is usually cheaper than pasting whole files.</li>
<li><strong>Shorten the system prompt.</strong> It is sent with every request, so every word in it is paid for many times.</li>
</ul>

<h2 id="3-cap-output-length">3. Cap output length</h2>
<p>Set <code>max_tokens</code> (or <code>max_output_tokens</code> for the Responses API) so a runaway answer cannot cost more than you expect. Ask for the format you need: "Answer in one sentence" or "Return JSON only" cuts output tokens directly.</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>Reasoning models also spend tokens thinking before they answer, and that thinking is billed as output. Use them where the reasoning helps, not for simple lookups.</p>

<h2 id="4-reuse-cached-prompts">4. Reuse cached prompts</h2>
<p>Many models offer prompt caching: when a request starts with the same text as a recent request, the repeated part is billed at a lower cache-read rate. To benefit, put the fixed parts (system prompt, tool definitions, long reference documents) at the start, and the parts that change at the end. Where a model has cache prices, its page in the <a href="https://aidiscount.ai/models">marketplace</a> lists them.</p>

<h2 id="5-do-not-pay-for-the-same-answer-twice">5. Do not pay for the same answer twice</h2>
<p>If your app asks the same question often, such as a product FAQ, store the answer in your own cache and return it without calling the API.</p>

<h2 id="6-batch-small-jobs">6. Batch small jobs</h2>
<p>Instead of one request per item, put several short items in one request and ask for a list of results. The instructions are sent once instead of many times. Keep batches small enough that one bad item does not force you to redo the whole batch.</p>

<h2 id="7-measure-per-request">7. Measure per request</h2>
<p>You cannot reduce what you do not measure. Every API response includes a <code>usage</code> field with the input and output token counts:</p>
<pre><code>print(resp.usage.prompt_tokens, resp.usage.completion_tokens)</code></pre>
<p>In AIDiscount, the Usage page in the dashboard lists the model, token counts and amount charged for every request. Use separate API keys for separate apps or team members to see which one is spending the most.</p>

<h2 id="8-compare-the-price-per-token">8. Compare the price per token</h2>
<p>The same model can cost different amounts from different providers. AIDiscount shows the price per million tokens and, where it applies, how it compares with the official list price, on each model's page. Check the current rate in the <a href="https://aidiscount.ai/models">marketplace</a> before you choose, because prices change.</p>
]]></content:encoded></item><item><title>Reasoning Effort: When to Use Thinking Models and What They Cost</title><link>https://aidiscount.ai/blog/reasoning-effort-cost-guide</link><guid isPermaLink="true">https://aidiscount.ai/blog/reasoning-effort-cost-guide</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>How reasoning models bill hidden reasoning tokens, how the reasoning effort setting changes cost and speed, and when a normal model is the better choice.</description><category>Reasoning</category><category>Cost</category><category>Tokens</category><category>API</category><content:encoded><![CDATA[<p>Reasoning models (also called thinking models) work through a problem step by step before they write the answer. That extra thinking makes them better at math, multi-step logic, planning and hard coding tasks. It also costs more, because the thinking is made of tokens, and you pay for them.</p>

<h2 id="how-reasoning-is-billed">How reasoning is billed</h2>
<p>Reasoning tokens are billed as <strong>output tokens</strong>, at the model's output rate, even when the API does not show you the reasoning text. A short final answer can still use thousands of reasoning tokens behind it. Check the <code>usage</code> field to see the real count:</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>On AIDiscount, the Usage page in the dashboard shows the output tokens charged for each request, reasoning included.</p>

<h2 id="the-reasoning-effort-setting">The reasoning effort setting</h2>
<p>Most reasoning models let you choose how hard they think. Lower effort means fewer reasoning tokens, a faster first token and a lower bill. Higher effort helps on hard problems and wastes money on easy ones.</p>
<p>OpenAI-compatible format:</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>The accepted values differ by model. Some accept <code>low</code>, <code>medium</code> and <code>high</code>, some add <code>xhigh</code> or <code>max</code>, and some accept <code>none</code> to turn thinking off. A model's page in the <a href="https://aidiscount.ai/models">marketplace</a> lists the values it supports.</p>
<p>Anthropic Messages format uses a thinking budget in tokens on models that support it:</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>The budget must be smaller than <code>max_tokens</code>, because thinking and the answer share the same output limit. Some newer Claude models use an effort setting instead of a token budget; the model page shows which one applies.</p>

<h2 id="when-to-use-which">When to use which</h2>
<table>
<tr><th>Task</th><th>Suggested setting</th></tr>
<tr><td>Classification, extraction, translation, short summaries</td><td>A normal model, or reasoning off or low</td></tr>
<tr><td>Chat and writing</td><td>Low or medium</td></tr>
<tr><td>Multi-step coding, debugging, data analysis</td><td>Medium or high</td></tr>
<tr><td>Hard math, proofs, complex planning</td><td>High or above</td></tr>
</table>
<p>Start low and raise the effort only when answers are wrong. Test on a sample of your real requests. The right setting depends on the task far more than on the model.</p>

<h2 id="things-to-watch">Things to watch</h2>
<ul>
<li><strong>Leave room in <code>max_tokens</code>.</strong> If the limit is too small, the model can spend it all on thinking and return an empty or cut-off answer.</li>
<li><strong>Expect slower first tokens.</strong> The model thinks before it writes. Use streaming so users see progress, and set client timeouts long enough for high effort.</li>
<li><strong>Some parameters are fixed while thinking.</strong> Several models reject a custom <code>temperature</code> when reasoning is on. Leave it at the default.</li>
<li><strong>Do not ask for "step by step" on top.</strong> A reasoning model already does this internally. Asking for visible steps adds output tokens without improving the answer.</li>
</ul>

<h2 id="current-prices">Current prices</h2>
<p>Since reasoning is billed as output, compare models by their output price when you plan to use high effort:</p>
<table><tr><th>Model</th><th>Input / 1M tokens</th><th>Output / 1M tokens</th><th>vs. official price</th></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr></table><p class="meta">Prices are read from the live <a href="https://aidiscount.ai/models">model marketplace</a> when this page is generated and may change. The marketplace always shows the current rate.</p>
]]></content:encoded></item><item><title>Prompt Caching: How It Works and How to Save Money With It</title><link>https://aidiscount.ai/blog/prompt-caching-save-money</link><guid isPermaLink="true">https://aidiscount.ai/blog/prompt-caching-save-money</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>How prompt caching bills input tokens at a lower rate on repeated requests, how to structure a prompt so the cache actually hits, and current cache prices.</description><category>Prompt caching</category><category>Pricing</category><category>Tokens</category><category>API</category><content:encoded><![CDATA[<p>Prompt caching lets a model skip re-processing the part of a prompt it has already seen recently. When a new request starts with the same text as a request from the last few minutes, the repeated prefix is billed at a lower <strong>cache-read</strong> rate instead of the normal input rate. The first request that creates the cache usually costs slightly more (a <strong>cache-write</strong> rate), and every matching request after that is cheaper.</p>

<h2 id="why-it-matters">Why it matters</h2>
<p>Many real apps resend a large block of fixed text with every request: a system prompt, a set of tool definitions, a long document the user is asking questions about, or a codebase's worth of context for a coding agent. Without caching, you pay the full input rate for that block every single time. With caching, you pay once and then pay the cache-read rate, which is typically a fraction of the normal input price, on every later request that reuses it.</p>

<h2 id="how-to-structure-a-prompt-for-cache-hits">How to structure a prompt for cache hits</h2>
<p>The cache matches a prefix: the identical text from the start of the prompt up to some point. Put content in this order:</p>
<ol>
<li><strong>Fixed content first</strong>: system prompt, tool definitions, long reference documents, few-shot examples. This should be byte-for-byte identical across requests.</li>
<li><strong>Variable content last</strong>: the user's current message, the latest turn of a conversation, anything that changes on every call.</li>
</ol>
<p>If you change even one character in the fixed part, the cache misses from that point on, and the request falls back to the normal input rate for everything after the change. Common ways people accidentally break the cache: inserting a timestamp into the system prompt, reordering tool definitions, or re-serializing JSON with different key order or whitespace.</p>

<h2 id="example-a-long-system-prompt">Example: a long system prompt</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>Because <code>SYSTEM_PROMPT</code> is identical on every call and comes first, the second and later calls within the cache window bill that block at the cache-read rate.</p>

<h2 id="checking-whether-the-cache-actually-hit">Checking whether the cache actually hit</h2>
<p>The response's <code>usage</code> field reports cached tokens separately, so you can confirm caching is working instead of assuming it:</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>If <code>cached_tokens</code> stays at 0 across repeated calls with the same prefix, something in the fixed part is changing between requests, or the gap between requests is longer than the cache's retention window.</p>

<h2 id="anthropic-messages-format">Anthropic Messages format</h2>
<p>Anthropic's format marks the cache boundary explicitly with <code>cache_control</code> on a content block, rather than relying only on prefix matching from the start:</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="what-does-and-doesn-t-benefit">What does and doesn't benefit</h2>
<ul>
<li><strong>Good fit</strong>: a chatbot with a long fixed system prompt and short user turns; a coding agent that resends the same large file; a document Q&amp;A app with one document and many questions.</li>
<li><strong>Little benefit</strong>: short one-off prompts with no shared prefix between requests; prompts where the only large part is the part that changes every time.</li>
<li><strong>Multi-turn chat</strong>: each new message extends the previous conversation, so the growing history itself becomes the cached prefix if the earlier turns are not modified. Avoid editing earlier messages in place if you want the cache to keep working.</li>
</ul>

<h2 id="current-cache-prices">Current cache prices</h2>
<p>Cache pricing is per model; not every model offers it. Where a model supports caching, its page in the <a href="https://aidiscount.ai/models">marketplace</a> lists the read and write rates alongside the normal input and output price.</p>
<table><tr><th>Model</th><th>Input / 1M tokens</th><th>Output / 1M tokens</th><th>vs. official price</th></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr></table><p class="meta">Prices are read from the live <a href="https://aidiscount.ai/models">model marketplace</a> when this page is generated and may change. The marketplace always shows the current rate.</p>
]]></content:encoded></item><item><title>What Is an OpenAI-Compatible API? How to Switch the Base URL</title><link>https://aidiscount.ai/blog/openai-compatible-api-base-url</link><guid isPermaLink="true">https://aidiscount.ai/blog/openai-compatible-api-base-url</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>An OpenAI-compatible API accepts the same requests as the OpenAI API. Here is how to point the OpenAI SDK, curl and common tools at a different provider by changing two settings.</description><category>OpenAI-compatible</category><category>API</category><category>Python</category><category>Node.js</category><content:encoded><![CDATA[<p>Most AI tools and SDKs were written against the OpenAI API. Many other providers accept the same request format, so the same code can talk to them. These providers are called <strong>OpenAI-compatible</strong>. Moving between them usually means changing two settings: the <strong>base URL</strong> and the <strong>API key</strong>.</p>

<h2 id="what-openai-compatible-means">What "OpenAI-compatible" means</h2>
<p>A provider is OpenAI-compatible when it serves the same paths with the same JSON shapes. The most common ones are:</p>
<table>
<tr><th>Endpoint</th><th>Used for</th></tr>
<tr><td><code>POST /v1/chat/completions</code></td><td>Chat and most tools. The most widely supported format.</td></tr>
<tr><td><code>POST /v1/responses</code></td><td>OpenAI's newer interface, used by Codex CLI and the Agents SDK.</td></tr>
<tr><td><code>GET /v1/models</code></td><td>Lists the model IDs your key can use.</td></tr>
<tr><td><code>POST /v1/images/generations</code></td><td>Image generation.</td></tr>
<tr><td><code>POST /v1/embeddings</code></td><td>Text embeddings.</td></tr>
</table>
<p>Compatibility covers the request and response format. Each provider still decides which models it offers, so the <code>model</code> value must be a model ID that the provider lists.</p>

<h2 id="the-two-settings-you-change">The two settings you change</h2>
<ul>
<li><strong>Base URL.</strong> The address that comes before <code>/chat/completions</code>. For OpenAI it is <code>https://api.openai.com/v1</code>. For AIDiscount it is <code>https://aidiscount.ai/v1</code>.</li>
<li><strong>API key.</strong> The provider's own key, sent as <code>Authorization: Bearer sk-...</code>. A key from one provider does not work at another.</li>
</ul>
<p>Keep the key in an environment variable instead of in code:</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-official-openai-sdk">Python (official 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>The SDK also reads <code>OPENAI_BASE_URL</code> and <code>OPENAI_API_KEY</code> from the environment. If you set both, you can switch providers without touching the code at all.</p>

<h2 id="node-js-official-openai-sdk">Node.js (official 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="streaming-works-the-same-way">Streaming works the same way</h2>
<p>Add <code>stream=True</code> (Python) or <code>stream: true</code> (Node.js). The provider sends server-sent events in the same format as OpenAI.</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="find-the-model-ids-you-can-use">Find the model IDs you can use</h2>
<pre><code>curl https://aidiscount.ai/v1/models \
  -H "Authorization: Bearer $AIDISCOUNT_API_KEY"</code></pre>
<p>The <a href="https://aidiscount.ai/models">model marketplace</a> shows the same IDs with their current prices.</p>

<h2 id="common-mistakes">Common mistakes</h2>
<ul>
<li><strong>404 Not Found.</strong> The base URL is missing <code>/v1</code>, or the tool adds <code>/v1</code> itself and you added it again. Try the other form.</li>
<li><strong>401 Unauthorized.</strong> The key belongs to a different provider, has a typo, or was deleted.</li>
<li><strong>Model not found.</strong> The model name is one the provider does not offer. Copy the exact ID from <code>/v1/models</code>.</li>
</ul>
<p>More fixes are in <a href="https://aidiscount.ai/blog/fix-ai-api-errors-401-403-404-429">How to fix common AI API errors</a>.</p>

<h2 id="what-about-the-anthropic-format">What about the Anthropic format?</h2>
<p>Some tools speak the Anthropic Messages API instead (<code>POST /v1/messages</code> with an <code>x-api-key</code> header). AIDiscount accepts that format too. For the Anthropic SDK, use the base URL <code>https://aidiscount.ai</code> without <code>/v1</code>, because the SDK adds <code>/v1/messages</code> itself. The <a href="https://aidiscount.ai/docs#anthropic">API docs</a> have full examples.</p>
]]></content:encoded></item><item><title>Using LangChain and the Vercel AI SDK with a Custom API Provider</title><link>https://aidiscount.ai/blog/langchain-vercel-ai-sdk-custom-provider</link><guid isPermaLink="true">https://aidiscount.ai/blog/langchain-vercel-ai-sdk-custom-provider</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>How to point LangChain (Python and JS) and the Vercel AI SDK at an OpenAI-compatible endpoint by changing the base URL and key, with working examples.</description><category>LangChain</category><category>Vercel AI SDK</category><category>API</category><category>Node.js</category><category>Python</category><content:encoded><![CDATA[<p>LangChain and the Vercel AI SDK both talk to models through adapters that already support OpenAI-compatible APIs. Switching providers inside either framework means configuring the base URL and key on the OpenAI-compatible client, not changing how you call the framework itself.</p>

<h2 id="langchain-python">LangChain (Python)</h2>
<p><code>ChatOpenAI</code> accepts a custom base URL through <code>base_url</code> (or the <code>OPENAI_BASE_URL</code> environment variable):</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>Streaming, tool binding with <code>llm.bind_tools(...)</code> and LangChain Expression Language chains all work unchanged, since they go through the same underlying client.</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="langchain-with-the-anthropic-messages-format">LangChain with the Anthropic Messages format</h2>
<p>Use <code>ChatAnthropic</code> with its own base URL option instead of <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>The <code>@ai-sdk/openai</code> provider accepts a <code>baseURL</code> when you create it with <code>createOpenAI</code>, instead of using the default <code>openai</code> export:</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>Streaming works the same way through <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>For the Anthropic Messages format, use <code>createAnthropic</code> from <code>@ai-sdk/anthropic</code> with <code>baseURL: "https://aidiscount.ai"</code> the same way.</p>

<h2 id="using-tools-through-these-frameworks">Using tools through these frameworks</h2>
<p>Both frameworks convert their own tool definitions into the same JSON Schema shape the underlying API expects, so tool calling works without extra configuration once the base URL is set. LangChain uses <code>llm.bind_tools([...])</code> or an agent executor; the Vercel AI SDK passes a <code>tools</code> object to <code>generateText</code> or <code>streamText</code>. See the <a href="https://aidiscount.ai/blog/function-calling-tool-use-guide">function calling guide</a> for the request and response shape underneath.</p>

<h2 id="common-mistakes">Common mistakes</h2>
<ul>
<li><strong>Setting the base URL on the wrong object.</strong> In LangChain JS, the base URL is nested under <code>configuration</code>, not a top-level field.</li>
<li><strong>Mixing a Chat Completions base URL with an Anthropic-format model name or vice versa.</strong> Each adapter targets one API shape; use <code>ChatOpenAI</code>/<code>createOpenAI</code> for OpenAI format and <code>ChatAnthropic</code>/<code>createAnthropic</code> for Anthropic format, matching the base URL to the right one.</li>
<li><strong>Leaving the default <code>openai</code> export from the Vercel AI SDK.</strong> That export always points at OpenAI's own API; you need <code>createOpenAI</code> to set a different base URL.</li>
</ul>

<h2 id="picking-a-model">Picking a model</h2>
<p>Any model ID from the <a href="https://aidiscount.ai/models">marketplace</a> works as the <code>model</code> argument once the base URL and key are set; nothing else in your LangChain or Vercel AI SDK code needs to change when you switch models.</p>
]]></content:encoded></item><item><title>Getting Reliable JSON Output from AI Models</title><link>https://aidiscount.ai/blog/json-structured-output-guide</link><guid isPermaLink="true">https://aidiscount.ai/blog/json-structured-output-guide</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>How to make an AI API reliably return valid JSON: response_format JSON mode, JSON Schema for a fixed shape, and a fallback for when a model still gets it wrong.</description><category>JSON</category><category>Structured output</category><category>API</category><category>Python</category><content:encoded><![CDATA[<p>Many apps need a model's answer in a fixed shape: a JSON object with specific fields, not a paragraph of text. Asking nicely in the prompt ("reply in JSON") usually works, but not always: the model can add a sentence before the JSON, wrap it in a markdown code block, or leave out a field. There are three levels of reliability, from weakest to strongest.</p>

<h2 id="level-1-ask-in-the-prompt">Level 1: Ask in the prompt</h2>
<p>Works most of the time, fails occasionally. Use it only for low-stakes cases, or combine it with one of the stronger options below.</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="level-2-json-mode">Level 2: JSON mode</h2>
<p>Setting <code>response_format={"type": "json_object"}</code> forces the output to be syntactically valid JSON. It does not enforce which fields are present, so mention the exact field names in the prompt.</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 mode requires the word "JSON" to appear somewhere in the conversation, usually in the system or user message; some models return an error otherwise.</p>

<h2 id="level-3-json-schema-recommended">Level 3: JSON Schema (recommended)</h2>
<p>Setting <code>response_format</code> to a JSON Schema constrains both the syntax and the shape: required fields, types, and enums are enforced during generation, not just checked afterward.</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>Keep the schema as small as the task needs. A schema with many optional fields and nested objects is harder for a model to fill in correctly than a flat schema with a few required fields.</p>

<h2 id="anthropic-messages-format">Anthropic Messages format</h2>
<p>The Messages API does not have a dedicated JSON mode; the reliable way is to describe the schema in the system prompt and ask the model to call a tool, since tool-call arguments already follow a JSON Schema strictly.</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="a-fallback-for-when-parsing-still-fails">A fallback for when parsing still fails</h2>
<p>Even with a schema, treat the response as untrusted input: a long context, a weird edge case, or a model limitation can still produce broken output. Wrap the parse in a retry:</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>Also validate the parsed object against your schema in code (with a library such as <code>pydantic</code> or <code>jsonschema</code>) before using it, even when the API enforced the schema server-side. Treat any field the model fills in as untrusted input, the same as user input, before it reaches a database query, a shell command, or a file path.</p>

<h2 id="model-support">Model support</h2>
<p>JSON Schema support varies by model; check the capabilities list on a model's page in the <a href="https://aidiscount.ai/models">marketplace</a> before relying on <code>strict: true</code>. A few models with structured output support:</p>
<table><tr><th>Model</th><th>Input / 1M tokens</th><th>Output / 1M tokens</th><th>vs. official price</th></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr></table><p class="meta">Prices are read from the live <a href="https://aidiscount.ai/models">model marketplace</a> when this page is generated and may change. The marketplace always shows the current rate.</p>
]]></content:encoded></item><item><title>Function Calling and Tool Use: A Working Guide</title><link>https://aidiscount.ai/blog/function-calling-tool-use-guide</link><guid isPermaLink="true">https://aidiscount.ai/blog/function-calling-tool-use-guide</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>How function calling works over an OpenAI-compatible API and Anthropic Messages, with a complete multi-turn example that calls a function and returns the result.</description><category>Function calling</category><category>Tool use</category><category>API</category><category>Python</category><content:encoded><![CDATA[<p>Function calling (also called tool use) lets a model ask your code to run a function instead of answering directly: it looks up a weather API, queries a database, or performs a calculation, then uses the result to finish its answer. The model never runs anything itself; it only returns a request to call a function with certain arguments, and your code decides whether to actually run it.</p>

<h2 id="the-request-shape">The request shape</h2>
<p>You describe each available function as a JSON Schema: a name, a description, and the shape of its arguments.</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>The model's description and the parameter descriptions are what it uses to decide when and how to call the function, so write them the way you would explain the function to another person, not just a type signature.</p>

<h2 id="full-multi-turn-example">Full multi-turn example</h2>
<p>A tool call is not the end of the conversation. The model pauses, you run the function, and you send the result back in a new message so the model can continue.</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>Key points this example relies on: append the assistant's tool-call message before the tool result, match each <code>tool_call_id</code> to the call it answers, and send <code>content</code> as a string (encode objects with <code>json.dumps</code>).</p>

<h2 id="multiple-tool-calls-in-one-turn">Multiple tool calls in one turn</h2>
<p>A model can request several tool calls at once, for example looking up the weather in three cities. Loop over <code>msg.tool_calls</code> and append one <code>"role": "tool"</code> message per call, each with its own <code>tool_call_id</code>, before calling the model again.</p>

<h2 id="anthropic-messages-format">Anthropic Messages format</h2>
<p>The shapes differ: each tool's schema goes in <code>input_schema</code> instead of <code>function.parameters</code>, a tool call arrives as a <code>tool_use</code> content block, and the result is sent back as a <code>tool_result</code> content block inside a user message.</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="forcing-or-disabling-tool-use">Forcing or disabling tool use</h2>
<p>By default the model decides whether to call a tool. To force one specific tool, pass <code>tool_choice={"type": "function", "function": {"name": "get_weather"}}</code> (OpenAI format) or <code>tool_choice={"type": "tool", "name": "get_weather"}</code> (Anthropic format). To stop the model from calling tools for one request while keeping the definitions, set <code>tool_choice="none"</code> (OpenAI format) or <code>tool_choice={"type": "none"}</code> (Anthropic format).</p>

<h2 id="common-mistakes">Common mistakes</h2>
<ul>
<li><strong>Returning the tool result as the wrong role.</strong> OpenAI format expects <code>"role": "tool"</code>; it will not accept the result as a normal user or assistant message.</li>
<li><strong>Forgetting to send the assistant's tool-call message back.</strong> The model needs to see its own tool call in history to connect it to the result.</li>
<li><strong>Sending the raw Python object instead of a JSON string</strong> in <code>content</code>. Always serialize with <code>json.dumps</code>.</li>
<li><strong>Not validating arguments before running the function.</strong> Treat tool-call arguments as untrusted input from the model; validate types and ranges before acting on them, especially before using them in a database query or shell command.</li>
</ul>

<h2 id="picking-a-model">Picking a model</h2>
<p>Most current models on AIDiscount support tool calling; a model's page in the <a href="https://aidiscount.ai/models">marketplace</a> lists it under capabilities. Current prices for a few tool-capable models:</p>
<table><tr><th>Model</th><th>Input / 1M tokens</th><th>Output / 1M tokens</th><th>vs. official price</th></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr><tr><td><a href="https://aidiscount.ai/models/kimi-k3">Kimi K3</a><br><code>kimi-k3</code></td><td>$1.714</td><td>$8.571</td><td>42.9% off</td></tr><tr><td><a href="https://aidiscount.ai/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% off</td></tr></table><p class="meta">Prices are read from the live <a href="https://aidiscount.ai/models">model marketplace</a> when this page is generated and may change. The marketplace always shows the current rate.</p>
]]></content:encoded></item><item><title>How to Fix Common AI API Errors: 401, 403, 404, 429 and 5xx</title><link>https://aidiscount.ai/blog/fix-ai-api-errors-401-403-404-429</link><guid isPermaLink="true">https://aidiscount.ai/blog/fix-ai-api-errors-401-403-404-429</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>What each HTTP error from an AI API means and how to fix it, with retry code for rate limits and temporary server errors.</description><category>Errors</category><category>Troubleshooting</category><category>API</category><content:encoded><![CDATA[<p>When an AI API request fails, the HTTP status code tells you where to look. This guide lists the codes you are most likely to see from an OpenAI- or Anthropic-compatible API, what causes them, and what to do.</p>

<h2 id="quick-reference">Quick reference</h2>
<table>
<tr><th>Status</th><th>Meaning</th><th>Retry?</th></tr>
<tr><td>400</td><td>The request body is invalid.</td><td>No. Fix the request.</td></tr>
<tr><td>401</td><td>The key is missing, wrong or deleted.</td><td>No. Fix the key.</td></tr>
<tr><td>403</td><td>The key is valid but not allowed, often because the balance is empty.</td><td>No. Top up or change plan.</td></tr>
<tr><td>404</td><td>Wrong path or base URL, or an unknown model.</td><td>No. Fix the URL or model.</td></tr>
<tr><td>429</td><td>Too many requests, or a usage cap was reached.</td><td>Yes, with backoff.</td></tr>
<tr><td>500, 502, 503, 504</td><td>A temporary server or upstream error.</td><td>Yes, with backoff.</td></tr>
</table>

<h2 id="400-bad-request">400 Bad Request</h2>
<p>The server could not accept the request. Read the error message in the response body; it usually names the field. Common causes:</p>
<ul>
<li>Malformed JSON, often from unescaped quotes in a shell command.</li>
<li>A <code>messages</code> list that is empty or has an invalid <code>role</code>.</li>
<li><code>max_tokens</code> larger than the model allows, or a prompt longer than the context window.</li>
<li>An Anthropic-format request without <code>max_tokens</code>, which that format requires.</li>
</ul>

<h2 id="401-unauthorized">401 Unauthorized</h2>
<p>The API does not recognize the key.</p>
<ul>
<li>Check the header. OpenAI format uses <code>Authorization: Bearer sk-...</code>. Anthropic format uses <code>x-api-key: sk-...</code>.</li>
<li>Check for spaces or line breaks copied with the key.</li>
<li>Check that the environment variable is set in the shell or process that makes the request. <code>echo $AIDISCOUNT_API_KEY</code> should print the key.</li>
<li>A key from one provider does not work at another. If you switched the base URL, switch the key too.</li>
<li>If the key was deleted on the API Keys page, create a new one.</li>
</ul>
<p>On AIDiscount the error code is <code>INVALID_API_KEY</code>.</p>

<h2 id="403-forbidden">403 Forbidden</h2>
<p>The key is valid, but the request is not allowed. On AIDiscount the most common code is <code>INSUFFICIENT_BALANCE</code>: top up your balance or buy a plan on the Pricing page. A 403 can also mean the model is not available to your key's group. Check the model list for your key:</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>Almost always a base URL problem.</p>
<ul>
<li>OpenAI format: the full path is <code>https://aidiscount.ai/v1/chat/completions</code>. SDKs and most tools want the base URL <code>https://aidiscount.ai/v1</code>.</li>
<li>Anthropic SDK and Claude Code: the base URL is <code>https://aidiscount.ai</code> without <code>/v1</code>, because they add <code>/v1/messages</code> themselves.</li>
<li>Some apps add <code>/v1</code> automatically. If you also typed it, the path becomes <code>/v1/v1/...</code>. Try the base URL with and without <code>/v1</code>.</li>
<li>A misspelled model ID can also return 404 or "model not found". Copy the ID from the <a href="https://aidiscount.ai/models">marketplace</a>.</li>
</ul>

<h2 id="429-too-many-requests">429 Too Many Requests</h2>
<p>You sent requests faster than allowed, or reached a usage cap such as a plan's weekly limit. Slow down and retry with exponential backoff. If the response has a <code>Retry-After</code> header, wait at least that long. If the cap is a plan quota, wait for it to reset or switch to pay-as-you-go balance.</p>

<h2 id="5xx-server-errors">5xx server errors</h2>
<p>500, 502, 503 and 504 usually mean a temporary problem upstream. Retry with backoff. Long requests can also time out on your side, so for long outputs use streaming, which keeps the connection active.</p>

<h2 id="retry-code">Retry code</h2>
<p>The official OpenAI SDKs already retry 429 and 5xx errors twice by default. You can raise the limit:</p>
<pre><code>from openai import OpenAI
client = OpenAI(base_url="https://aidiscount.ai/v1", max_retries=5, timeout=120)</code></pre>
<p>Without an SDK, a simple backoff loop works:</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>Do not retry 400, 401, 403 or 404. The same request will fail the same way.</p>

<h2 id="still-stuck">Still stuck?</h2>
<p>Note the time of the request and the request ID from the response headers, and contact support through the link in the site footer. Never include your API key in a support message.</p>
]]></content:encoded></item><item><title>How to Use a Custom OpenAI-Compatible API in Cursor, Cline and Continue</title><link>https://aidiscount.ai/blog/cursor-cline-continue-custom-api</link><guid isPermaLink="true">https://aidiscount.ai/blog/cursor-cline-continue-custom-api</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>Step-by-step setup for using your own API key and base URL in Cursor, Cline and Continue, with the settings to check when a model does not respond.</description><category>Cursor</category><category>Cline</category><category>Continue</category><category>Coding tools</category><content:encoded><![CDATA[<p>Cursor, Cline and Continue can all send requests to any OpenAI-compatible API. You need three things:</p>
<ul>
<li><strong>Base URL:</strong> <code>https://aidiscount.ai/v1</code></li>
<li><strong>API key:</strong> a key that starts with <code>sk-</code>, created on the API Keys page after you <a href="https://aidiscount.ai/register">sign up</a></li>
<li><strong>Model ID:</strong> copied exactly from the <a href="https://aidiscount.ai/models">model marketplace</a>, for example <code>deepseek-v4.1-flash</code> or <code>glm-5.3</code></li>
</ul>

<h2 id="cline-vs-code">Cline (VS Code)</h2>
<ol>
<li>Open the Cline panel and click the settings (gear) icon.</li>
<li>Set <strong>API Provider</strong> to <strong>OpenAI Compatible</strong>.</li>
<li>Set <strong>Base URL</strong> to <code>https://aidiscount.ai/v1</code>.</li>
<li>Paste your key into <strong>API Key</strong>.</li>
<li>Enter the model ID in <strong>Model ID</strong>.</li>
<li>Save, then send a short task such as "List the files in this folder".</li>
</ol>
<p>Cline uses tool calls heavily. Pick a model whose marketplace page lists tool calling support.</p>
<p>Cline also has an <strong>Anthropic</strong> provider with a custom base URL option. If you prefer the Anthropic format, use the base URL <code>https://aidiscount.ai</code> (without <code>/v1</code>).</p>

<h2 id="continue-vs-code-and-jetbrains">Continue (VS Code and JetBrains)</h2>
<p>Continue reads models from its config file. Open it from the Continue panel (gear icon, then the config file), and add a model entry:</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>Replace <code>YOUR_MODEL_ID</code> with an ID from the marketplace. You can paste the key directly into <code>apiKey</code> instead of using a secret, but then do not commit the file to a repository.</p>
<p>Autocomplete needs a fast, cheap model. If you set up a separate model with the <code>autocomplete</code> role, choose a small model to keep costs down.</p>

<h2 id="cursor">Cursor</h2>
<ol>
<li>Open <strong>Cursor Settings</strong> and go to <strong>Models</strong>.</li>
<li>Under <strong>API Keys</strong>, turn on <strong>OpenAI API Key</strong> and paste your AIDiscount key.</li>
<li>Turn on <strong>Override OpenAI Base URL</strong> and enter <code>https://aidiscount.ai/v1</code>.</li>
<li>Click <strong>Verify</strong>.</li>
<li>Add the model ID with <strong>Add model</strong>, enable it, and select it in the chat panel.</li>
</ol>
<p>Two limits are worth knowing:</p>
<ul>
<li>Requests from Cursor go through Cursor's servers before they reach the base URL. This is why the URL must be publicly reachable, and why a local address such as <code>localhost</code> does not work.</li>
<li>Some Cursor features, such as Tab completion, always use Cursor's own models. A custom key applies to chat and to the models you add.</li>
</ul>
<p>Cursor's menus move between versions. If the labels above do not match, look for the OpenAI key and base URL settings under Models.</p>

<h2 id="if-the-model-does-not-respond">If the model does not respond</h2>
<table>
<tr><th>Symptom</th><th>Likely cause</th></tr>
<tr><td>404 or "Not Found"</td><td>The base URL is missing <code>/v1</code>, or <code>/v1</code> is doubled.</td></tr>
<tr><td>401 or "Invalid API key"</td><td>Wrong key, extra spaces when pasting, or the key was deleted.</td></tr>
<tr><td>"Model not found"</td><td>The model ID has a typo or uses a different provider's naming. Copy it from the marketplace.</td></tr>
<tr><td>403 "Insufficient balance"</td><td>Top up your balance or buy a plan.</td></tr>
<tr><td>Agent stops or loops on tool calls</td><td>The model is weak at tool use. Try a larger model.</td></tr>
</table>
<p>See <a href="https://aidiscount.ai/blog/fix-ai-api-errors-401-403-404-429">How to fix common AI API errors</a> for more detail.</p>

<h2 id="keep-an-eye-on-cost">Keep an eye on cost</h2>
<p>Coding agents send the whole conversation and many file contents with every step, so they use far more input tokens than a normal chat. Check the Usage page in your dashboard after a few sessions. <a href="https://aidiscount.ai/blog/reduce-ai-api-costs">How to cut AI API costs</a> covers ways to bring the bill down.</p>
]]></content:encoded></item><item><title>Add a Custom API Provider to Cherry Studio, Chatbox, LobeChat and Open WebUI</title><link>https://aidiscount.ai/blog/chat-apps-custom-api-provider</link><guid isPermaLink="true">https://aidiscount.ai/blog/chat-apps-custom-api-provider</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>How to connect desktop and web chat apps to an OpenAI-compatible API: where to enter the base URL and key, how to add models, and how to fix the usual 404.</description><category>Cherry Studio</category><category>Chatbox</category><category>LobeChat</category><category>Open WebUI</category><category>Chat apps</category><content:encoded><![CDATA[<p>Chat apps such as Cherry Studio, Chatbox, LobeChat and Open WebUI let you bring your own API key. With an OpenAI-compatible provider you can use many models from different vendors in one app, and pay only for what you use instead of a monthly subscription per vendor.</p>
<p>Every app asks for the same three things:</p>
<ul>
<li><strong>API host or base URL:</strong> <code>https://aidiscount.ai/v1</code> (or <code>https://aidiscount.ai</code> if the app adds <code>/v1</code> itself)</li>
<li><strong>API key:</strong> your <code>sk-...</code> key from the API Keys page</li>
<li><strong>Model IDs:</strong> from the <a href="https://aidiscount.ai/models">model marketplace</a>, or fetched by the app</li>
</ul>

<h2 id="cherry-studio">Cherry Studio</h2>
<ol>
<li>Open <strong>Settings</strong>, then <strong>Model Provider</strong>, and click <strong>Add</strong>.</li>
<li>Enter a name such as AIDiscount and choose the <strong>OpenAI</strong> provider type.</li>
<li>Paste your key into <strong>API Key</strong>.</li>
<li>Set <strong>API Host</strong> to <code>https://aidiscount.ai</code>. Cherry Studio adds <code>/v1</code> itself.</li>
<li>Click <strong>Manage</strong> to fetch the model list, or add model IDs by hand.</li>
<li>Click <strong>Check</strong> to test the connection.</li>
</ol>

<h2 id="chatbox">Chatbox</h2>
<ol>
<li>Open <strong>Settings</strong> and add a custom provider.</li>
<li>Choose the OpenAI API compatible mode.</li>
<li>Set the API host to <code>https://aidiscount.ai/v1</code>. If the test request fails with 404, remove <code>/v1</code>.</li>
<li>Paste your key and add a model ID.</li>
</ol>

<h2 id="lobechat">LobeChat</h2>
<p>For the hosted or desktop app, open <strong>Settings</strong>, then <strong>AI Service Provider</strong>, and either edit the OpenAI provider or add a custom one. Set the API proxy address to <code>https://aidiscount.ai/v1</code>, paste the key, and fetch or add models.</p>
<p>For a self-hosted Docker deployment, set the environment variables instead:</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>Sign in as an admin and open <strong>Admin Panel</strong>, then <strong>Settings</strong>, then <strong>Connections</strong>.</li>
<li>Under OpenAI API, add a connection with the URL <code>https://aidiscount.ai/v1</code> and your key.</li>
<li>Save. Open WebUI calls <code>/v1/models</code> and lists the models your key can use.</li>
</ol>
<p>For Docker, you can set the connection at start-up:</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="the-usual-problem-404">The usual problem: 404</h2>
<p>A 404 almost always means the <code>/v1</code> part is wrong. Some apps expect the address with <code>/v1</code> and some add it themselves. If one form fails, try the other:</p>
<ul>
<li><code>https://aidiscount.ai/v1</code></li>
<li><code>https://aidiscount.ai</code></li>
</ul>
<p>Other errors are covered in <a href="https://aidiscount.ai/blog/fix-ai-api-errors-401-403-404-429">How to fix common AI API errors</a>.</p>

<h2 id="keep-your-key-safe">Keep your key safe</h2>
<p>Desktop apps store the key on your computer. A shared, self-hosted web app stores it on the server, and everyone using that instance spends from the same balance. If you think a key has leaked, delete it on the API Keys page. It stops working immediately. Then create a new one.</p>
]]></content:encoded></item><item><title>API Key Security: Storing, Scoping and Rotating Keys Safely</title><link>https://aidiscount.ai/blog/api-key-security-best-practices</link><guid isPermaLink="true">https://aidiscount.ai/blog/api-key-security-best-practices</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>Practical rules for handling AI API keys: environment variables, never shipping a key to the browser, per-project keys, and what to do after a leak.</description><category>API keys</category><category>Security</category><category>Best practices</category><content:encoded><![CDATA[<p>An API key is a bearer credential: whoever holds it can spend against your balance. Treat it like a password, not like a config value that is safe to leave lying around.</p>

<h2 id="store-keys-as-environment-variables-not-in-code">Store keys as environment variables, not in code</h2>
<p>Never write a key as a literal string in a source file. Read it from the environment instead:</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>For local development, put the variable in a <code>.env</code> file and add <code>.env</code> to <code>.gitignore</code> <em>before</em> creating the file, so a tired <code>git add .</code> never catches it. In CI/CD and hosting platforms, set the key through the platform's secrets feature (GitHub Actions secrets, your host's environment variable settings), never in a committed workflow file or Dockerfile.</p>

<h2 id="never-put-a-key-in-frontend-or-mobile-code">Never put a key in frontend or mobile code</h2>
<p>Anything shipped to a browser or a mobile app is public, no matter how it is obfuscated or minified. A key embedded in client-side JavaScript, a mobile app binary, or a browser extension will be extracted within hours of release; this is routinely automated by scrapers that specifically scan public repositories and shipped app bundles for key-shaped strings. If a feature needs an AI call from the browser, add a small backend endpoint that holds the key server-side and forwards the request, so the browser only ever talks to your own server.</p>

<h2 id="use-a-separate-key-per-project-or-environment">Use a separate key per project or environment</h2>
<p>One key for everything means one leak affects everything, and a spike in usage from a single key doesn't tell you which app caused it. Create a separate key for each application, and separate keys for development, staging and production, from the API Keys page in the dashboard. If a leak happens, you can revoke the one affected key without breaking everything else, and the Usage page shows you exactly which key is spending.</p>

<h2 id="give-each-key-only-what-it-needs">Give each key only what it needs</h2>
<p>If a key only needs a subset of models or a lower rate limit, scope it that way instead of issuing a key with full access everywhere. A narrower key limits how much damage a leak can do.</p>

<h2 id="what-happens-when-a-key-leaks">What happens when a key leaks</h2>
<p>Leaked keys are found quickly, mostly by automated scanners, not by someone manually reading your code: public GitHub repositories, pastebins, browser extension source, client-side JavaScript bundles, and even screenshots or screen recordings posted online are all scraped continuously for key-shaped strings. Once found, a key is typically abused within minutes for automated bulk usage, run until the balance is exhausted or the key is revoked.</p>
<p>If you suspect a key leaked:</p>
<ol>
<li><strong>Revoke it immediately</strong> from the API Keys page. This takes effect right away.</li>
<li><strong>Create a new key</strong> and update every place the old one was used.</li>
<li><strong>Check the Usage page</strong> for the time window to see what was actually run on it.</li>
<li><strong>Find how it leaked</strong> before you consider it resolved: search your git history (not just the latest commit; <code>git log -p</code> past commits can still contain a key you later removed), check CI logs, and check any public repository or gist.</li>
</ol>
<p>A key already committed to git history is not fixed by deleting the line in a new commit; the old commit still contains it. Either rewrite history (<code>git filter-repo</code> or BFG Repo-Cleaner) on a repository you control, or treat the key as burned and rotate it, which is usually faster and safer than rewriting history on a shared repository.</p>

<h2 id="rotate-keys-on-a-schedule-not-only-after-a-leak">Rotate keys on a schedule, not only after a leak</h2>
<p>Rotating a key periodically, even with no known leak, limits how long a key that leaked silently (and was never noticed) stays useful to whoever has it. Issue the new key, update your app, confirm it works, then revoke the old one, rather than revoking first and debugging an outage under pressure.</p>

<h2 id="checklist">Checklist</h2>
<ul>
<li>Key lives in an environment variable or secrets manager, never in a committed file.</li>
<li><code>.env</code> is in <code>.gitignore</code> before the file is created.</li>
<li>No key appears in any frontend, mobile, or browser extension code.</li>
<li>Separate keys per app and per environment (dev/staging/production).</li>
<li>A plan exists for "what do I do if this leaks", written down before it happens, not improvised afterward.</li>
</ul>
]]></content:encoded></item><item><title>Using the Official Anthropic SDK with a Different API Provider</title><link>https://aidiscount.ai/blog/anthropic-sdk-custom-base-url</link><guid isPermaLink="true">https://aidiscount.ai/blog/anthropic-sdk-custom-base-url</guid><pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate><description>How to point the official Anthropic Python, TypeScript and Claude Code clients at a different Messages API endpoint, with the right base URL to use.</description><category>Anthropic</category><category>Claude Code</category><category>API</category><category>Python</category><category>Node.js</category><content:encoded><![CDATA[<p>The official Anthropic SDKs talk to the Messages API (<code>/v1/messages</code>). Any server implementing the same request and response shape can sit behind them by changing the base URL and the key; the SDK itself does not need to know it is not talking to Anthropic's own servers.</p>

<h2 id="the-base-url-is-the-account-root-not-the-full-path">The base URL is the account root, not the full path</h2>
<p>The most common mistake: the Anthropic SDK adds <code>/v1/messages</code> itself, so the base URL should be <code>https://aidiscount.ai</code>, without <code>/v1</code>. Adding <code>/v1</code> yourself produces a 404 on <code>/v1/v1/messages</code>.</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>The base URL can also be set with the <code>ANTHROPIC_BASE_URL</code> environment variable instead of passing <code>base_url</code>, which is convenient when you don't want to touch existing code that constructs the client without arguments.</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 reads the same two settings from the environment:</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> sends the key as a bearer token. Claude Code also accepts <code>ANTHROPIC_API_KEY</code>, but it may then ask you to confirm the key on first start. Set only one of the two.</p>

<h2 id="curl-for-comparison">curl, for comparison</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>Note the header name: <code>x-api-key</code>, not <code>Authorization: Bearer</code>. The SDKs set this header for you from <code>api_key</code>; only build it by hand when calling the API directly.</p>

<h2 id="streaming-and-tools">Streaming and tools</h2>
<p>Both work exactly as with Anthropic's own API once the base URL points elsewhere, since the SDK's streaming and tool-use code does not depend on which server is on the other end. See the <a href="https://aidiscount.ai/blog/stream-ai-api-responses">streaming guide</a> and the <a href="https://aidiscount.ai/blog/function-calling-tool-use-guide">tool use guide</a> for the Anthropic-format examples.</p>

<h2 id="model-names">Model names</h2>
<p>Pass any model ID that supports the Anthropic Messages protocol from the <a href="https://aidiscount.ai/models">marketplace</a> as the <code>model</code> field; model names are not tied to Anthropic specifically once the base URL has changed.</p>

<h2 id="common-mistakes">Common mistakes</h2>
<ul>
<li><strong>Keeping <code>/v1</code> in the base URL.</strong> Results in a 404 on <code>/v1/v1/messages</code>.</li>
<li><strong>Using <code>Authorization: Bearer</code> with a raw <code>fetch</code> call.</strong> The Messages API expects <code>x-api-key</code>; the SDK handles this, but hand-written requests must set it explicitly.</li>
<li><strong>Omitting <code>anthropic-version</code>.</strong> Required on every direct HTTP request; the official SDKs set it automatically.</li>
<li><strong>Forgetting <code>max_tokens</code>.</strong> The Messages API requires it on every request; there is no default.</li>
</ul>
]]></content:encoded></item></channel></rss>
