1. What this handbook is for

What you should be able to do afterwards

This is the first hands-on handbook for a reader who has never called an LLM API. After reading it you should be able to get a working request against the DeepSeek API with a single curl command, point at any field in the response and explain what it means, turn a call that "works" into one that will still work next week, and finally decide on your own which model to use, which parameters to set, and where to put constraints.

Three things are deliberately out of scope: deploying models on your own servers, training or fine-tuning, and production-grade high-concurrency architecture. Other articles on this site cover those. This handbook does exactly one thing — explain how to use the API properly. A lot of readers arrive here in this state: the code runs, the output looks fine, but nothing feels solid. Is this actually success? How do I know it was not silently truncated? Why was this call cheap and that one expensive? Why is the same prompt giving different results? Would switching models fix it?

If any of those questions sound familiar, this handbook was written for you.

How this differs from the other DeepSeek articles here

ArticleWhat it solvesRead it when
id=110 "DeepSeek API from zero to production"Builds a complete product (customer service, RAG, streaming)You can already call the API and want a full application
id=57 "DeepSeek API in practice"Engineering wrappers and deploymentYour code is going into production
id=100 "API cost optimization: 98% saved with cache hits"Bill optimization and cache strategyYour call volume grew and the bill hurts
id=106 "JSON Mode structured output"Schema design and advanced structured outputYou need the model to emit parseable data reliably
This article (id=206)The complete mental model, from first call to stable outputYou are new to DeepSeek, or you changed SDKs and started hitting errors again

In other words: those four are specialist training, this one is the foundation course. Read this first, then jump to whichever specialist topic you need.

The path through this handbook

Fourteen sections, arranged as a dependency chain. Sections 2 to 4 get you running and reading the response. Section 5 covers the traps. Sections 6 and 7 cover where the money goes. Sections 8 to 11 turn a working call into a stable one. Section 12 is the decision tree. Sections 13 and 14 are the troubleshooting path and the pre-launch checklist. Every section can be read on its own, but the code in section 3 is the foundation for everything after it.

2. Before you start: three things you must have

First: get an API key and confirm the account has credit

Log in to the DeepSeek open platform and create a key. The secret is shown in full exactly once, so put it in an environment variable or a secret manager immediately and never commit it to Git. The remedy for a leaked key is simple and brutal: revoke it, generate a new one, and write off the calls made during the exposure window.

The second thing people forget: creating a key does not mean the account has credit. The official API is prepaid, and a request with an empty balance fails immediately. Beginners often read that as "my key is wrong". The fastest diagnosis is to send one minimal curl request and read the error body instead of guessing from the SDK traceback.

Second: install one SDK, do not build a framework yet

The official DeepSeek API is OpenAI-compatible, so the OpenAI SDK works out of the box and is the least effort: package management, upgrades, and the ecosystem all come for free. Do not reach for a small third-party "deepseek" client package; those tend to lag behind, and they will not pick up new models, new parameters, or new response fields.

# Python: one package is enough
pip install openai

# Node.js
npm install openai

Use the current stable release. Since the 1.x line, the OpenAI Python SDK exposes base_url, timeout and max_retries as client-level options, and those three cover most of the pitfalls later in this handbook. Use them directly instead of rolling your own.

Third: confirm the network can reach api.deepseek.com

Before writing any application code, verify connectivity with curl. This cleanly separates "my code is wrong" from "the network is wrong" and saves a lot of pointless debugging later.

# Snippet 1: connectivity self-check (no inference quota consumed)
curl -sS -o /dev/null -w "%{http_code}\n" \
  https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-chat","messages":[{"role":"user","content":"hi"}]}'

# Expected: 401 (network fine, host fine, just no key attached)
# 000 or a timeout -> network / DNS / proxy problem, not a code problem
# 404 -> base_url or path is malformed

If you sit behind a corporate network you may need HTTP_PROXY / HTTPS_PROXY. Containers do not inherit proxy settings from the host, which is another common cause of "it works locally but not in deployment".

3. The first call: from nothing to seeing your first token

Minimal curl: no extra parameters

Start with curl instead of an SDK. You get to see exactly what the request and the response look like without a wrapper in the way, and a curl command is the easiest thing in the world to reproduce or paste into a ticket.

# Snippet 2: the minimal working request
curl https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-chat",
    "messages": [
      {"role": "user", "content": "Explain prefix caching in one sentence"}
    ]
  }'

Only three things are required in the body: model, messages, plus the Authorization header. No system prompt, no temperature, no max_tokens. Get the simplest version working first, then add parameters one at a time, so that whenever something breaks you know exactly which addition broke it.

Minimal Python call

# Snippet 3: minimal Python call
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],      # never hardcode it
    base_url="https://api.deepseek.com",         # the line beginners get wrong
    timeout=30.0,                                # default of 10 minutes is far too long
    max_retries=2,                                # let the SDK retry 429 / 5xx
)

resp = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Explain prefix caching in one sentence"}],
)

print(resp.choices[0].message.content)
print(resp.usage)

On timeout: the SDK default is very long (often ten minutes), which means one hung request pins your thread for ten minutes. Set it explicitly in production — 30 to 60 seconds is usually plenty. Too short and network jitter kills healthy requests; too long and you amplify the blast radius of an outage.

On max_retries: the official docs recommend deciding with openai.Timeout, APIConnectionError, APIStatusError and RateLimitError. The built-in retry handles 429 and 5xx well enough. But if you write your own retry logic you must separate "connection failed" from "bad parameters": the first is worth retrying, the second will fail a million times just the same.

Minimal Node call

// Snippet 4: minimal Node.js call
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DEEPSEEK_API_KEY,
  baseURL: "https://api.deepseek.com",
  timeout: 30_000,
  maxRetries: 2,
});

const resp = await client.chat.completions.create({
  model: "deepseek-chat",
  messages: [{ role: "user", content: "Explain prefix caching in one sentence" }],
});

console.log(resp.choices[0].message.content);
console.log(resp.usage);

The Node version maps one to one onto the Python one, with three differences: camelCase field names (baseURL, maxRetries), timeout in milliseconds rather than seconds, and a top-level await that needs an async function or an ESM module. Chinese text does not get mangled in Node, because the Content-Type header already declares UTF-8.

What a successful first call looks like

You get a body whose id starts with chatcmpl-, a choices array with one element, the model's answer in choices[0].message.content, and a set of token numbers in usage. If instead you get {}, an empty string, or a Python traceback, do not start rewriting code — walk through the three traps in section 5 one by one.

4. Reading the response field by field

Top-level fields: id, object, created, model, system_fingerprint

FieldMeaningHow to use it
idUnique request identifier, shaped like chatcmpl-xxxxLogging. Quote it in a support ticket and the server side can find the exact record
objectObject type: chat.completion for full responses, chat.completion.chunk for streamsTells you whether you are holding a complete response or a stream fragment
createdUnix timestamp in seconds, generated server-sideLatency math and time alignment. It is server time, not the moment you sent the request
modelThe model identifier that actually served the requestImportant: if you passed an alias or a retired name, this shows where it really landed. It is your defence against "I thought I was running A but it was actually B"
system_fingerprintFingerprint of the serving configurationUseful when the same prompt yields different results: if the fingerprint changed, the backend configuration changed

created is in seconds, so multiply by 1000 before handing it to JavaScript's Date. Another classic small trap.

choices[0].message: content versus reasoning_content

Two fields in message matter for most applications:

  • message.content — the final answer, the text you show to the user.
  • message.reasoning_content — the chain of thought. Only reasoning models return it; on ordinary chat models it is null or absent entirely.

The most common beginner mistake is concatenating reasoning_content into the final output. The user then sees a long internal monologue ("first I need to consider… then…"), which is a poor experience. The rule is simple: content goes to the user, reasoning_content goes to logs and debug panels.

# Snippet 5: unpacking correctly
message = resp.choices[0].message
answer = message.content or ""                  # content may be None
thinking = getattr(message, "reasoning_content", None)  # absent on chat models

if thinking:
    logger.debug("reasoning: %s", thinking)      # logs only, never the UI
print(answer)

The second common mistake is assuming message.content always exists. It can be None — when the model decides to call a tool, the body is empty and everything lives in tool_calls. Skip the null check and the tool branch raises AttributeError.

The values of finish_reason, and what each one means

finish_reason is the most important and most frequently ignored field in the whole response. It answers "why did the model stop", not "what did the model say".

ValueMeaningWhat to do
stopNormal end: the model finished, or hit a stop sequence you suppliedHappy path, use the result
lengthThe output hit the max_tokens ceiling and was cut offHandle it. The output is incomplete and usually ends mid-sentence. Raise max_tokens or generate in sections
tool_callsThe model wants to call a tool; the body is empty and arguments live in tool_callsRun the tool, feed the result back, continue
content_filterBlocked by a safety policyReword the input or change model tier; blind retries will not help
insufficient_system_resourceServer-side load was insufficient, request did not completeRetryable: back off and try again

The classic failure mode is grabbing content and using it without ever looking at finish_reason. You end up with half a JSON document or a summary cut off mid-thought, displayed perfectly happily — until the downstream parser throws and you spend an afternoon tracing it back to length. The check is one line long, and it catches more than half of production incidents.

usage: skip it for now, but know where it lives

usage is the billing summary; section 6 takes it apart field by field. For now you only need to know that it sits at the top level next to choices, that it holds token counts, and that it arrives late — the model only knows how many tokens it used after the whole answer is out. That is why usage normally appears only on the final chunk of a streaming response.

5. The three traps beginners fall into

Trap 1: a wrong base_url — missing /v1, a stray slash, a missing https

The official base_url is https://api.deepseek.com. Many tutorials write it with /v1. Both work, but mixing them causes trouble.

ValueEffective request pathSymptom
https://api.deepseek.com/chat/completionsWorks
https://api.deepseek.com/v1/v1/chat/completionsWorks (the official endpoint also serves this)
https://api.deepseek.com/v1//v1//chat/completionsDouble slash; some gateways return 404
https://api.deepseek.com/v1/chat/v1/chat/completionsLooks right, but combined with other SDK path rules becomes /v1/chat/chat/completions
https://api.deepseek.com/chat/completions/chat/completions/chat/completions404. The most common mistake of all: pasting the full endpoint as base_url
api.deepseek.comNo scheme before the SDK appends the pathThe SDK throws a connection-level error (missing http/https protocol), not a 401 — easy to misread as a network problem
https://chat.deepseek.comHits the web chat host404 or HTML back, never JSON

The rule is short: base_url stops at the host (optionally with /v1) and must never include an endpoint path such as /chat/completions. The OpenAI SDK appends /chat/completions itself.

There is a subtler variant: many development environments already export OPENAI_BASE_URL. An explicit base_url argument wins, so nothing breaks — but if you forget to pass it, the request silently goes to OpenAI or to some proxy. You get a perfectly well-formed response with nonsense content. Print the effective configuration when debugging:

# Snippet 6: print the effective client configuration
print("base_url:", client.base_url)
print("api_key :", client.api_key[:6] + "..." + client.api_key[-4:])   # head/tail only
# head/tail printing is enough to spot a wrong key without leaking it into logs

Trap 2: a wrong model name — the string must match exactly

Model names are case-sensitive strings, and different providers (the official platform, third-party gateways, self-hosted vLLM) use completely different naming. A wrong name usually shows up as a 400 with a body saying the model does not exist or is not accessible.

What you probably wantModel page IDContextNotes
General chat workhorsedeepseek-chat (official alias)Depends on the serving configThe usual general entry point on the official API
Latest lightweight modeldeepseek-v4-1-flash1M tokens, up to 384K outputReleased 2026-09-10. 552B MoE, asymmetric CED architecture, only 8B active on the input side, accepts image input
Previous lightweight modeldeepseek-v4-flash1M tokensRetired on 2026-09-10; requests are absorbed by V4.1-Flash
Coding and agent workdeepseek-v3-2160K tokensSWE-bench 55.0%, strong price/performance
Deep reasoningdeepseek-reasoner / deepseek-r1128K tokensReturns reasoning_content; higher cost and latency
Code onlydeepseek-coder-v2128K tokensBest value when the task is pure code generation

There are several naming schemes because of history and deployment differences: the official platform uses aliases like deepseek-chat and deepseek-reasoner, while model pages and some deployments use versioned IDs. The only reliable way to confirm is to ask the server, not to guess:

# Snippet 7: ask the server which models are live
models = client.models.list()
for m in models:
    print(m.id)

# Or read it back from a response:
# send a name you are sure about and check resp.model

Related to "wrong model name" is model retirement. V4 Flash was retired on 10 September 2026, and the official endpoint routes its traffic to V4.1-Flash automatically, billed at the Flash tier. That is good news for old code — nothing breaks — but you must know it: the model you think you are running is not the model running. When you compare output quality or run a benchmark, this alone can invert your conclusion. The check is reading resp.model.

Trap 3: max_tokens and the context window squeeze each other

The context window is one shared budget for input and output. Roughly:

input tokens (system + history + current message) + output tokens <= model context window

Two classic mistakes, one on the "too long" side and one on the "too short" side:

  • You omit max_tokens and the output gets cut. The server then applies a default (historically 4096 on DeepSeek; the ceiling is set by the model configuration). Ask for a 3,000-character analysis, hit the default ceiling, and the answer stops dead at token 2048 — with HTTP status 200 and a content string that looks perfectly complete. You cannot tell it was truncated unless you read finish_reason.
  • You set max_tokens huge on a long input and the request is rejected. 900K input tokens plus a 384K output request exceeds the 1M window, so the server refuses the request with a context-length error. Here the failure is at least explicit.

Another beginner trap: max_tokens is not "how much to keep", it is "the maximum allowed". It is a ceiling, not a quota. If the model finishes early it uses only part of the budget; the rest is wasted, which does not affect billing (you pay for tokens actually generated) but also means a huge value will not make the model say more.

# Snippet 8: what truncation looks like
resp = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Write a 3000-character technical plan"}],
    max_tokens=200,                       # deliberately small, to force truncation
)

if resp.choices[0].finish_reason == "length":
    print("truncated, produced", resp.usage.completion_tokens, "/ 200")
    # Fix: raise max_tokens, or make the model generate in sections (section 13)

The safe move is to set max_tokens explicitly to a value you believe is enough, and to always check finish_reason. That turns truncation into a state you can handle instead of silent data corruption.

A general troubleshooting order for the three traps

When any call fails, walk these steps in order without skipping:

  1. Send one minimal request with curl. Success means the bug is in your code; failure means it is the network or the key.
  2. It connects but returns 4xx: read the error code and message in the body, and suspect base_url and the model name first.
  3. It returns 200 but the result is wrong: look at finish_reason, resp.model, and usage.
  4. All of that is fine and the result is still wrong: now it is a prompting or model-capability problem, which is where section 8 onward begins.

6. Reading usage: where the money goes

prompt_tokens, completion_tokens, total_tokens

Three basic fields: tokens consumed by the input, tokens consumed by the output, and their sum. Billing is based on actual usage, so these three numbers are your invoice in miniature.

Tokens are not characters. One Chinese character is roughly 0.6 to 1 token depending on the tokenizer, and about four English characters make one token. The same 2,000-character Chinese document and 2,000-word English article differ by close to three times in token count. A rough estimator is "Chinese characters × 0.7 + English words × 1.3", but read the real numbers back from usage instead of computing them yourself.

prompt_cache_hit_tokens and prompt_cache_miss_tokens

These two fields are the ledger for DeepSeek's context cache, and the place where this handbook connects to the site's cost-optimization article.

FieldMeaningBilling consequence
prompt_cache_hit_tokensInput tokens served from the cached prefixBilled at the cache-hit price: ¥0.02 per million tokens on V4.1-Flash
prompt_cache_miss_tokensInput tokens that had to be computedBilled at the standard input price: ¥1 per million tokens on V4.1-Flash
prompt_tokensTotal inputApproximately the sum of the two above (a small rounding difference is possible)

That is a 50x gap between hit and miss price. This is the entire point of prefix caching: put the part that is identical every time — system prompt, long document, retrieved knowledge — at the very front and keep it byte-identical, so you pay the full price once and the discounted price forever after. Section 7 covers the layout.

Where reasoning_tokens hides

The thinking produced by a reasoning model is billed as output. In the OpenAI-compatible response this usually appears as usage.completion_tokens_details.reasoning_tokens. It is the money you pay for thinking: the model splits its output budget into "used for reasoning" and "said to you", and the total is completion_tokens.

The practical consequence is that a reasoning request can cost several times more than it looks. If you only need one short sentence, a reasoning model is pure waste; if you need a hard judgement, those tokens are well spent. The deciding factor is task difficulty, not model reputation.

Do the arithmetic on a real request

Rather than memorising a price table, write a small helper that prints the cost of each call. This is the only reliable way to understand cost — especially when you are unsure whether to change models or to change the prompt.

# Snippet 9: per-call cost report
PRICE_IN_MISS = 1.00      # CNY / 1M tokens, V4.1-Flash miss (check official pricing)
PRICE_IN_HIT  = 0.02      # CNY / 1M tokens, V4.1-Flash cache hit
PRICE_OUT     = 4.00      # CNY / 1M tokens, V4.1-Flash output

def report(resp):
    u = resp.usage
    hit = getattr(u, "prompt_cache_hit_tokens", 0) or 0
    miss = getattr(u, "prompt_cache_miss_tokens", None)
    if miss is None:                       # older servers may omit this field
        miss = u.prompt_tokens - hit

    cost = (hit / 1e6 * PRICE_IN_HIT
            + miss / 1e6 * PRICE_IN_MISS
            + u.completion_tokens / 1e6 * PRICE_OUT)
    print(f"in(hit)={hit} in(miss)={miss} out={u.completion_tokens} -> {cost:.6f} CNY")
    return cost

Always take prices from the official price list, and remember that DeepSeek pricing floats by time of day — V4.1-Flash output doubles at peak hours. Once the constants work, replace them with today's numbers from the pricing page and add a date comment, so that in a month you at least know which line to update.

7. Context caching: when it hits and how to use it

How the cache works: block-by-block prefix matching

DeepSeek's context cache is disk-based and caches the request prefix. The matching rule is not "the content is the same somewhere" but "the tokens are identical from position one onwards". The server chops the prefix into blocks and compares them one by one; once a block differs, every later block is invalidated, even if the text later on would have matched.

That single rule explains every caching trick in this section, and explains why some layouts hit almost every time while others never do.

Which prompt shapes hit naturally

Input shapeHit rateWhy
Fixed system prompt + varying user messageHighThe system part is byte-identical every time, so it lives in the cache
Fixed long document + fixed few-shot examples + varying questionHighStable prefix, only the tail changes
Multi-turn chat with appended historyHighTurn N's input is turn N-1's prefix plus one new message, so it is reused naturally
Timestamp or random ID embedded in the user messageNoneToken one already differs, so everything after it is wasted
System prompt generated dynamically (with the current time)NoneSame reason — it breaks the prefix at the very front
Large document appended to the user message, different every timeNoneThe prefix changes every request, so nothing can be reused
Few-shot examples placed after the user messageNoneExamples behind dynamic content put the cache out of reach

The whole heuristic in one sentence: put what never changes first, and what changes last. Anything that varies per request — timestamps, request IDs, user names, random numbers — must not live in the prefix region.

Three layouts that guarantee a cache miss

All three are extremely common in real projects, and nothing in the code looks wrong. You only notice them on the invoice.

  1. A timestamp inside the system prompt. "Today is 2026-11-18, answer with the latest information" changes once a day and is fine. But "current time: {datetime.now()}" changes on every request and the hit rate is exactly zero.
  2. Chat history that gets reordered or filtered before each call. Even a rule like "drop messages older than 30 days" occasionally changes the prefix length, and the whole cached prefix is invalidated.
  3. The system prompt moved into the user message. If that message is always identical and sits first, it still hits. But as soon as a personalised prefix, a user ID, or retrieved results are placed in front of it, the cache is dead.

A template that turns the system prompt into a shared prefix

# Snippet 10: a cache-friendly call structure
STATIC_SYSTEM = """You are a technical assistant for deepseekmodel.com.
Rules:
1. Only answer questions about DeepSeek and AI application development.
2. If you do not know, say so. Never invent facts.
3. Keep every answer under 300 characters.
"""

def ask(question: str) -> str:
    resp = client.chat.completions.create(
        model="deepseek-v4-1-flash",
        messages=[
            {"role": "system", "content": STATIC_SYSTEM},   # byte-identical, always the prefix
            {"role": "user", "content": question},           # everything that varies goes last
        ],
    )
    return resp.choices[0].message.content

# Two calls in a row: the second should show a large prompt_cache_hit_tokens

To verify a hit, print usage.prompt_cache_hit_tokens. The first call is usually 0 (the server has just built the cache); from the second call onward, provided the system part is long enough to form a cache unit, the hit count should approach the token length of the system prompt.

One thing worth stressing: the cache saves money on the input side only. If your workload produces long outputs from short inputs, prefix caching buys you almost nothing — what you should optimise there is output length, or a cheaper model tier. Do not apply the wrong optimisation.

8. From "it works" to "it is stable": setting the boundaries of the system prompt

What the system prompt is for, and what it is not for

Many beginners treat the system prompt as the place to write down everything they want, end up with three thousand characters, and then complain that the output is inconsistent. The cause is a muddled job description. A system prompt should do three things and only three things:

  • Role and domain — who you are, what you specialise in, who you serve.
  • Hard constraints — what you must do, what you must never do, what contract the output has to satisfy.
  • Behaviour on failure — what to do when information is missing, uncertain, or out of scope.

It is not responsible for domain knowledge, current context, retrieved documents, or the user's actual question. Those belong in messages. Stuffing knowledge into the system prompt wastes the cache prefix and mixes instructions with material, so the model can no longer tell a rule from a fact.

A system prompt skeleton you can copy

# Snippet 11: system prompt template (adapt it freely)
You are {role}, serving {audience}.

## Scope
- Handle: {in_scope}
- Do not handle: {out_of_scope}. For those, say in one sentence that it is out of
  scope and suggest an alternative.

## Factual discipline
- Use only facts present in the input material. Do not complete or speculate.
- When unsure, say "unsure" and name what information is missing.
- Do not cite specific library versions, API prices, or release dates unless they
  appear in the input material.

## Output contract
- Format: {format}
- Length: {length_limit}
- Language: {language}
- Required fields: {required_fields}
- Forbidden phrasing: {forbidden_phrases}

## Refusal policy
When the task cannot be completed, output
{"error": "", "hint": ""}

The two most ignored blocks are also the highest-value ones: factual discipline directly reduces hallucination, and the refusal policy lets your calling code distinguish "the model answered" from "the model gave up". Those two situations need completely different handling downstream, and mixing them leaves your code with no branch to take.

Three rules that stop the output from improvising

  1. Translate "don't" into "do". "Do not write filler" works far worse than "lead with a one-sentence conclusion, then give at most two pieces of evidence". Negative constraints tend to make a model either over-cautious or simply ignore them.
  2. Give checkable acceptance criteria. "The answer must be professional" cannot be checked; "the answer must contain one runnable command or code snippet" can. Models respond better to checkable constraints, because a checkable constraint is itself a structure.
  3. Define the edge cases. Empty input, overlong input, contradictory input. The model will not invent policies for these; if you do not write them down, it improvises.

A counterintuitive lesson: a system prompt is not better for being long. Long instructions dilute each other, and instruction-following noticeably degrades in the middle and tail of a long system prompt. The test is whether every line constrains a specific behaviour. By the same rule as clean code: three sharp rules plus two concrete examples beat ten vague ones.

9. Making the output checkable: JSON and structured output

The json_object mode and its hard prerequisite

DeepSeek's JSON Output mode is enabled with the response_format parameter, set to {"type": "json_object"}. The official documentation states one hard prerequisite: the word json must appear somewhere in the messages (in the system or user message), otherwise the model does not switch into JSON mode. The requirement looks odd, but the mechanism is simple: the model learns output format from instructions, so the parameter supplies a tendency and the prompt supplies the command.

As for whether {"type": "json_schema", ...} — the schema-carrying form — is supported, that depends on your model and server version; the official docs and this site's id=106 article cover it in more depth. The verification is trivial: send one minimal request and look at whether the body is pure JSON or whether it contains explanatory prose. Prose means JSON mode did not engage.

Making the output checkable: schema, validation, one repair

There is a gap between "ask the model for JSON" and "guarantee a valid JSON object". The model may emit syntactically valid JSON with a missing field, a wrong type, or wrapped in a Markdown code fence. The complete approach has three parts: turn on JSON mode, validate against a schema, and feed validation errors back once.

# Snippet 12a: structured output plus local validation
import json
from jsonschema import Draft202012Validator   # pip install jsonschema

SCHEMA = {
    "type": "object",
    "properties": {
        "summary": {"type": "string"},
        "tags": {"type": "array", "items": {"type": "string"}, "maxItems": 5},
        "confidence": {"type": "number", "minimum": 0, "maximum": 1},
    },
    "required": ["summary", "tags"],
    "additionalProperties": False,
}

validator = Draft202012Validator(SCHEMA)

def extract(text: str) -> dict:
    """The model sometimes wraps the answer in a Markdown fence; strip it first."""
    text = text.strip()
    if text.startswith("```"):
        text = text.split("```")[1]
        if text.startswith("json"):
            text = text[4:]
    return json.loads(text)
def structured_call(question: str, retries: int = 1) -> dict:
    prompt = ("Summarise the following as JSON with the fields summary / tags / confidence."
              "Output json only, with no explanation.\n\nContent: " + question)

    for attempt in range(retries + 1):
        resp = client.chat.completions.create(
            model="deepseek-v4-1-flash",
            messages=[
                {"role": "system", "content": "You are a converter that only emits valid JSON."},
                {"role": "user", "content": prompt},
            ],
            response_format={"type": "json_object"},
            temperature=0,          # structured tasks want determinism
        )
        raw = resp.choices[0].message.content
        try:
            data = extract(raw)
        except json.JSONDecodeError:
            if attempt == retries:
                raise
            continue

        errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
        if not errors:
            return data

        if attempt == retries:
            raise ValueError("JSON schema validation failed: " + str([e.message for e in errors]))

        # Feeding the concrete validation error back fixes it in one round.
        prompt = ("The previous output did not match the schema. Errors: "
                  + str([e.message for e in errors])
                  + ". Output json only.\n\nOriginal content: " + question)
    raise RuntimeError("unreachable")

The key move is the last one: feed back the specific validation errors instead of merely saying "try again". "tags must be an array" or "additional properties are not allowed" gets a correct answer on the first retry; a vague "the format was wrong" gets you a fresh, equally wrong answer.

When JSON mode cannot save you

There are four situations where turning on JSON mode changes nothing, and the fix lies elsewhere:

SymptomRoot causeWhat to do
String values inside the JSON are frequently emptyThe input lacks information; the model has nothing to fill inChange the input or the schema, not the output format
Field names are right but the values are offA schema constrains shape, not meaningDefine every field explicitly in the prompt, with an example
JSON is truncated when summarising a long documentThe output ceiling is too low, so the JSON stops mid-documentRaise max_tokens, or extract in sections instead of one pass
Structure breaks down past two levels of nestingThe nesting exceeds what the model reliably emitsSplit into several flat calls and assemble in code

How this divides the work with the site's JSON Mode article

This handbook stops at "make the output checkable": how to switch the mode on, how to validate, how to feed errors back once. For schema design, deep nesting, streaming JSON parsing and repair strategies for nested fields, read id=106 on this site, "JSON Mode structured output: from schema to production". The position taken here is that structured output is one means of making a model answer machine-consumable, not an end in itself. If your scenario is just "have the model talk to a human", JSON mode is over-engineering.

10. Giving the model tools: getting function calling right

Declaring tools: how to write the JSON Schema without traps

The model behind function calling never executes anything. You declare which functions exist and what their parameters look like; the model produces an intent to call; your code executes it and feeds the result back. This is the main mechanism for connecting an LLM to the real world.

Three frequent traps in tool declarations:

  • Vague parameter descriptions. "Query information" gives the model nothing to work with. Write "the city name, e.g. 'Hangzhou'; no province suffix". The model fills parameters from the description.
  • Everything in required. Listing optional parameters as required forces the model to invent values you never wanted. Only genuinely necessary fields belong in required.
  • Too many, too similar tools. When the model picks the wrong tool, the descriptions usually overlap. Merge similar tools once you have more than about ten.
# Snippet 13: tool declaration
TOOLS = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Look up the weather for a city on a given date. Use when the user asks about weather.",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name, full name, e.g. 'Hangzhou'. No province and no suffix.",
                },
                "date": {
                    "type": "string",
                    "description": "Query date as YYYY-MM-DD. Use 'today' for the current day.",
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "Temperature unit. Defaults to celsius.",
                },
            },
            "required": ["city"],
        },
    },
}]

The complete round trip

The tool loop has four steps and all four are required: send the request with tools, receive tool_calls, execute and feed the result back, and let the model answer from that result. Dropping the tool_call_id link in step three is the most common mistake.

# Snippet 14: the complete function calling loop
import json

def run_with_tools(question: str) -> str:
    messages = [{"role": "user", "content": question}]

    for _ in range(5):                       # guard against an infinite loop
        resp = client.chat.completions.create(
            model="deepseek-v4-1-flash",
            messages=messages,
            tools=TOOLS,
            tool_choice="auto",
        )
        msg = resp.choices[0].message

        # No tool calls means the model produced its final answer
        if not msg.tool_calls:
            return msg.content or ""

        # Put the model's intent back into the conversation verbatim
        messages.append({
            "role": "assistant",
            "content": msg.content or "",
            "tool_calls": [
                {
                    "id": tc.id,
                    "type": "function",
                    "function": {
                        "name": tc.function.name,
                        "arguments": tc.function.arguments,   # a JSON string, not an object
                    },
                } for tc in msg.tool_calls
            ],
        })

        # Execute each tool and attach the result by tool_call_id
        for tc in msg.tool_calls:
            args = json.loads(tc.function.arguments or "{}")   # must parse; may be empty
            result = call_tool(tc.function.name, args)
            messages.append({
                "role": "tool",
                "tool_call_id": tc.id,                    # without this the next turn fails
                "content": json.dumps(result, ensure_ascii=False),
            })
    raise RuntimeError("tool call rounds exceeded")

Four details to remember:

  1. function.arguments is a string, so it needs json.loads. It can also be an empty string, so guard with a default.
  2. When feeding results back you must include tool_call_id, matching the model's tc.id exactly.
  3. Do not stuff tool results into the assistant message; use a separate message with role: "tool".
  4. Always set a maximum number of rounds. A model can decide to call the same tool over and over, and without a ceiling that is a money-burning infinite loop.

Parallel versus serial tool calls

When one question needs the weather in three cities, the model may return three tool_calls in a single response, or go one at a time. Support parallelism explicitly: when you iterate msg.tool_calls, do not call the model again inside the loop. Execute every tool first, then send all the results back at once.

The price is that error handling gets harder — what if one of the three tools fails? The usual approach is to return an error message for the failure too, rather than skipping it, and let the model decide whether to retry, to correct the arguments, or to tell the user that it partially succeeded. That is more robust than making the decision in code on the model's behalf.

How to report tool errors

Error kindExampleWhat to send back
Missing argumentCity name is empty{"error": "missing_param", "field": "city"} — let it fill it in
Invalid argumentDate format is wrong{"error": "invalid_format", "expected": "YYYY-MM-DD"} — state the expected format
Call failedDownstream service timed out{"error": "upstream_timeout", "retryable": true} — let it decide whether to retry
No resultUnknown cityReturn an empty result or {"found": false}; never fabricate a value

The principle: report errors to the model in a structured way, with enough detail that it can correct itself. Return the single word "failed" and the model can only guess; return "the date format was wrong, use YYYY-MM-DD" and the next attempt is correct.

// Snippet 15: the tool loop in Node.js
const resp = await client.chat.completions.create({
  model: "deepseek-v4-1-flash",
  messages,
  tools: TOOLS,
  tool_choice: "auto",
});

const msg = resp.choices[0].message;
if (!msg.tool_calls) {
  console.log(msg.content);
} else {
  for (const tc of msg.tool_calls) {
    const args = JSON.parse(tc.function.arguments || "{}");
    const out = await callTool(tc.function.name, args);
    messages.push({
      role: "tool",
      tool_call_id: tc.id,
      content: JSON.stringify(out),
    });
  }
}

11. Stabilising the format: few-shot examples and model tiers

Few-shot: when it helps and when it is waste

Few-shot prompting is the most direct tool available, and also the most overused. It turns "I want this format" from an abstract description into concrete samples, and models copy samples far more reliably than they follow abstract descriptions.

But it has a fixed cost: every example consumes input tokens, and those tokens sit in the cached prefix region if you place the examples early. So:

SituationRecommendationReason
Complex output shape (many fields, some nesting)Use few-shotAbstract descriptions cannot express it; a sample can
Classification or labelling with a fixed label setUse few-shotLabel boundaries are best taught by examples
Simple question answeringDo not botherPure waste of tokens and attention
The shape is already fixed by a JSON schemaUsually not neededThe schema guarantees the shape; examples only need to carry meaning
Examples run to thousands of tokensCompress them firstBetter to sharpen the rules than to pile up examples

One practical technique: place the examples in the fixed prefix region, after the system prompt and before the real question. The examples then stay stable, share the cache, and sit early enough to be noticed. Stacking examples at the end of the user message, as many people do, loses both the cache and the stability.

A minimal, sane sampling configuration

A common beginner mistake is adding parameters until the output becomes strange. A sane default: temperature=0 for structured tasks; leave it at the default or around 0.7 for creative work; set nothing else. Adjusting top_p and temperature together is a classic error — with two sampling knobs in play the result is unpredictable and you cannot attribute anything.

If the same prompt gives different results each time, check temperature first. Even at 0 the model can still vary (floating-point ordering, batching, MoE routing), so "temperature 0 means identical output" is an expectation that does not hold. Real stability comes from constraints — schema, few-shot, system rules — not from sampling parameters.

When to change model tier

ModelContextAPI price (model page figures)Use it when
deepseek-v4-1-flash1M tokens, up to 384K output¥0.02/M cached hit, ¥1/M miss, ¥4/M output (off-peak; doubles at peak)The default choice. Long context, high concurrency, agent tool use, image input
deepseek-v4-flash1M tokens¥0.14/M input (¥0.02 cached), ¥0.56/M outputRetired. Requests route to V4.1-Flash. Do not use it in new code
deepseek-v3-2160K tokens$0.14/M input, $0.56/M outputCoding work, stronger agent behaviour, when the context need is modest
deepseek-r1 / reasoner128K tokens¥4/M input, ¥16/M outputHard reasoning: maths, logic, multi-step decisions. Several times the cost of Flash
deepseek-coder-v2128K tokensSee the model pagePure code generation and completion

Note that the two Flash rows do not carry the same price: V4 Flash is the archived price of a retired model, V4.1-Flash is the live price. Budget with the live model's price, and confirm against the official price list.

The decision rule fits in one sentence: ask first whether the failure came from a model that is not strong enough or from instructions that are not clear enough. The first calls for a different model, the second calls for a better prompt. Doing it the other way round burns money and keeps the bug.

12. The decision tree: how to configure each kind of task

Baseline configuration for four task types

TaskModelKey parametersConstraints you must add
Simple Q&Adeepseek-v4-1-flashOmit max_tokens or set 2048Bound the domain in the system prompt; short prompts with no reusable prefix gain little from caching
Long summarisationdeepseek-v4-1-flashmax_tokens = target length × 2Check finish_reason == "length"; summarise in sections rather than one shot
Structured outputdeepseek-v4-1-flashtemperature=0, response_format={"type":"json_object"}Put "json" in the prompt; validate with a schema and repair once
Tool usedeepseek-v4-1-flashtools, tool_choice="auto"Concrete parameter descriptions; return tool_call_id; cap the number of rounds
Hard reasoningreasoner familyKeep reasoning_content in logsThinking tokens are billed as output; only content is the answer

The decision tree

# Snippet 16: decision tree pseudocode
def choose(task, needs_tools=False, needs_json=False, needs_reasoning=False):
    if needs_reasoning:
        return "deepseek-reasoner"        # rule reasoning out first
    if task == "simple qa":
        return "deepseek-v4-1-flash"      # everything else starts at Flash
    if task == "long summarisation":
        # Long input -> Flash's 1M context is a real advantage
        return "deepseek-v4-1-flash"
    if needs_tools:
        return "deepseek-v4-1-flash"      # agent ability and tool use are Flash strengths
    if needs_json:
        return "deepseek-v4-1-flash"      # start with Flash plus validation
    return "deepseek-v4-1-flash"

The tree looks one-sided on purpose. Until you can name the precise reason a call failed, the default should be V4.1-Flash: a 1M context window, image input, strong agent behaviour, and low cost make it the best value in almost every scenario. There are exactly three signals that justify another tier:

  1. The task genuinely needs multi-step reasoning — maths, multi-constraint optimisation, hard debugging. That is the reasoner's home ground.
  2. Flash measurably fails your evaluation set (labelled data, a baseline score) rather than merely feeling insufficient.
  3. You need a specialised capability, for example a code-specialised model for pure code generation.

From the tree back to concrete parameters

Once the model is chosen you still need parameters. Start from these values and adjust from measurement:

# Snippet 17: a usable default configuration
BASE = dict(
    model="deepseek-v4-1-flash",
    timeout=60.0,
    max_retries=2,
)

# Simple Q&A
simple = dict(**BASE, messages=[...], max_tokens=1024)

# Long summarisation (twice the target length, to avoid truncation)
summary = dict(**BASE, messages=[...], max_tokens=4096)

# Structured output
structured = dict(**BASE, messages=[...], temperature=0,
                  response_format={"type": "json_object"})

# Tool use
agent = dict(**BASE, messages=[...], tools=TOOLS, tool_choice="auto")

13. Failure modes and how to trace them

Output was truncated: a three-step diagnosis

# Snippet 18: truncation triage
if resp.choices[0].finish_reason == "length":
    used = resp.usage.completion_tokens
    print(f"truncated after {used} tokens")
    # Step 1: raise max_tokens to used * 2 and retry
    # Step 2: still not enough -> the task itself is too long, split it
    # Step 3: outline first, then expand section by section, then merge

The logic is: rule out the simplest cause first, "the ceiling was just set too low". If doubling is still not enough, the output volume genuinely exceeds a reasonable range, which usually means the task is badly shaped — asking for a 3,000-character answer and asking for a 300-character outline plus three expansions are completely different tasks. The third step, generating in sections, is also the standard approach for long documents.

Unstable format: why editing the prompt sometimes does nothing

What you changedWhy it may not helpWhat works better
Added a requirement at the end of the system promptInstruction-following degrades in the middle and tail of a long system promptMove the key constraint to the front of the system prompt; delete redundant rules
Moved the requirement from user to systemA more specific instruction in the user message usually winsMake both consistent instead of contradicting
Added "you must strictly follow the format"Vague emphasis does not change behaviourGive one positive and one negative example, or switch on JSON mode
Lowered temperature to 0Floating point and batching still allow small differencesUse a schema for shape and few-shot for meaning
Changed the prompt and the parameters togetherSomething changed, but you cannot tell whatChange one variable at a time

There is also a class of "editing the prompt did nothing" where the cause is not in the prompt at all: the model was retired and traffic was rerouted, the serving configuration changed, or something unwanted leaked into the context. Rule those out first, then come back to the prompt.

The cache never hits

Check three things in order:

  1. Is there anything in the prefix that varies per request (timestamp, random ID, user identifier)? Move it to the end.
  2. Is the system prompt byte-identical every time? Compare with a hash in your logs rather than by eye.
  3. Is the prefix long enough? A very short prefix may not reach the minimum cache unit. You can pad the prefix with stable background material.
# Snippet 19: verify that the prefix is really stable
import hashlib, json

def fingerprint(messages):
    # Keep only up to the first user message: that is the part meant to be cached
    prefix = []
    for m in messages:
        prefix.append(m)
        if m["role"] == "user":
            break
    blob = json.dumps(prefix, ensure_ascii=False, sort_keys=True)
    return hashlib.sha256(blob.encode()).hexdigest()[:16]

# Two consecutive calls should produce identical fingerprints
print(fingerprint(m1), fingerprint(m2))

Timeouts, rate limits, and empty balances

SymptomLikely causeResponse
401Key invalid, revoked, or padded with stray whitespaceCheck the environment variable; note that Bearer is capitalised
402Account balance exhaustedTop up on the platform
429Rate limitedExponential backoff; the SDK's max_retries already covers this
400 + context lengthInput plus max_tokens exceeds the windowShorten the input or lower max_tokens
400 + model not foundWrong or retired model nameQuery GET /v1/models for the real list
Timeout, no responseNetwork, proxy, or server overloadSet an explicit timeout; check the proxy; add retries
HTML instead of JSONbase_url points at the web hostVerify base_url

One subtlety of retry policy: only retry errors that can succeed later. Connection errors, 429 and 5xx are worth retrying; 401, 402 and parameter errors are not. The SDK's built-in policy already draws that line.

14. The pre-launch checklist

Ten checks

#CheckHow to confirm it
1No API key hardcoded in sourcegrep the repository for strings starting with sk-
2base_url stops at the host, with no endpoint pathPrint client.base_url
3Model names came from the server, not from guessingclient.models.list()
4timeout is set explicitlyA timeout parameter exists in the code
5max_tokens is set explicitlyYou do not rely on a server-side default
6finish_reason is checkedThere is a == "length" branch
7resp.model is loggedYou can confirm which model really ran
8The system prompt prefix is byte-stableCompare fingerprints of two requests
9Tool loops have a hard round limitThere is an upper bound in the loop
10usage is recordedYou can total tokens and cost per day

The boundaries of this handbook

This article covers how to make a single call correct. It does not cover: multi-turn context management strategies (when to summarise history, when to start a new session), full streaming handling (incremental parsing, SSE reconnection, resuming after a disconnect), production-grade concurrency control and backoff, cache warming, the batch API, or the parameter differences of self-hosted deployments (vLLM, SGLang, Ollama). All of those belong to the category of "turning workable into operable", and other articles here cover them.

And one last sentence has to sit at the very end: prices, model availability and context limits all change. Every price figure, model ID and parameter ceiling in this article is a snapshot taken at the time of writing. Check the official documentation and the model list in the console, and verify them with the methods given in sections 7 and 13. That is more reliable than remembering any single number.