What an API call is
An API (application programming interface) is a way for one program to ask another for something. A model API is a web address. Your program sends a request over HTTPS with a secret API key; the provider checks the key, its serving engine runs prefill and decode, and the answer comes back as JSON, together with a count of the tokens you will pay for.
- Your programBuilds the messages and sends them with your key
- The provider’s front doorChecks the key, your balance and your rate limits
- RouterPicks a copy of the model, ideally one that already has your prompt cached
- Serving enginePrefill, then decode, one token at a time
- The replyJSON with the text, why it stopped, and the token counts
curl https://api.deepseek.com/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $DEEPSEEK_API_KEY" \
-d '{
"model": "deepseek-flash",
"messages": [
{"role": "system", "content": "You are a patient maths teacher. Answer in two sentences."},
{"role": "user", "content": "Why can we not divide by zero?"}
],
"thinking": {"type": "disabled"},
"max_tokens": 200,
"temperature": 0.7
}'
$DEEPSEEK_API_KEYreads the key from an environment variable, so it never appears in your code.messagesis the whole conversation. The roles aresystem(instructions),user,assistant(the model’s earlier replies) andtool(results of tool calls, in the next lesson).max_tokenscaps the reply.temperatureis the sampling setting from the sampling lesson.- DeepSeek’s models think by default. This request turns thinking off to keep the reply short and cheap.
{
"model": "deepseek-flash",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "Dividing asks how many times one number fits into another…"
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 31,
"completion_tokens": 48,
"total_tokens": 79,
"prompt_cache_hit_tokens": 0,
"prompt_cache_miss_tokens": 31
}
}
finish_reasonsays why the model stopped:stop(it finished),length(it hitmax_tokens, so the text is cut off),tool_calls(it wants to use a tool) orcontent_filter.usageis your bill: prompt tokens at the input price, completion tokens at the output price. DeepSeek also says how many prompt tokens were cache hits. The counts here are examples.
Quick check
The API forgets everything
A chat API is stateless: every request stands alone, and the server keeps no memory of your last one. To continue a conversation, your program sends all of it again: the system prompt, every earlier message, every earlier reply, and then the new message. The model reads the whole thing again on every turn.
turn k sends: system + k messages + (k − 1) repliesEach turn repeats everything before it.
20 turns: 20 × 2,000 + 200 × (1 + 2 + … + 20) + 500 × (1 + 2 + … + 19)A 2,000-token system prompt, 200-token messages and 500-token replies.
= 40,000 + 42,000 + 95,000 = 177,000 input tokensYet only 15,500 of them are new: exactly the size of the last turn.
input over N turns grows like N²A chat twice as long sends about four times as many input tokens.
Start with the defaults: 20 turns at DeepSeek Flash’s peak prices. Caching makes the chat about 3.7 times cheaper, and most of what is left is output. Now choose 30,000 tokens for the system prompt and tools, as a coding agent might have, and 40 turns: repeats are now almost everything, and caching saves more than ten times. Then switch the price list and watch the same chat go from cents to dollars.
This interactive part needs JavaScript.
Quick check
Prompt caching: paying less for the same start
Providers keep the KV cache (from the KV cache lesson) of prompts they have just processed. When a new request starts with exactly the same tokens, the server loads the saved keys and values instead of running prefill on them again. That part of the input is a cache hit, and you pay a small fraction of the normal price for it.
| DeepSeek | Claude (Anthropic) | GPT (OpenAI) | |
|---|---|---|---|
| Turning it on | Always on | Mark the prompt with cache_control, or turn on automatic caching | Always on |
| A cache hit costs | 2 % of the normal input price (Flash), 3.3 % (V4 Pro) | 10 % on most models; 5 % or 2.5 % on some newer ones | 10 % on the newest models; 5 % on one |
| Writing to the cache | No extra charge | 1.25 times the input price for a 5-minute cache, 2 times for 1 hour | 1.25 times the input price on the newest models |
| How long it lasts | Hours to days, best effort | 5 minutes, renewed each time it is used; or 1 hour | From minutes to 24 hours, depending on the model |
| Where it is kept | On disk | In memory only | Not stated |
| Where the reply shows it | prompt_cache_hit_tokens | cache_read_input_tokens | cached_tokens |
From each provider’s documentation on 20 October 2026. OpenAI’s newest models cache prompts of 1,024 tokens or more. Writing once and reading once costs 1.25 + 0.1 = 1.35 times the normal price, against 2 times for sending the same prompt twice with no cache.
Five rules get you more hits:
- Same start, token for token. The match begins at the very first token. Change one token and everything after it is a miss.
- Stable things first, changing things last: system prompt, then tool definitions, then documents, then the conversation, then the new message.
- Nothing that changes at the top. A clock time, a random ID or the user’s name in the first line of the system prompt makes every request different from its first tokens.
- Only add, never edit. Reordering tools or rewriting an earlier message breaks the match from that point on.
- Check the reply. The usage fields in the table tell you how many tokens hit. If the number stays at zero, something near the start keeps changing.
Quick check
Paying less when you can wait
If nobody is waiting for the answer, you can trade speed for price. A batch API takes a file of requests and returns all the answers later, for half price at both OpenAI and Anthropic. It suits evaluations, translating a whole website, labelling data, or anything else that can run overnight.
| OpenAI | Anthropic | |
|---|---|---|
| Discount | 50 % | 50 % |
| Answers within | 24 hours, often sooner | 24 hours; most batches finish within 1 hour |
| Largest batch | 50,000 requests, or a 200 MB file | 100,000 requests, or 256 MB |
| Rate limits | A separate, much higher pool | Separate batch limits |
{"custom_id": "review-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "…", "max_tokens": 5, "messages": [{"role": "user", "content": "Positive or negative? Review: …"}]}}
- A batch file has one request per line (JSON Lines).
custom_idlets you match each answer to its question, because answers can come back in any order. - At Anthropic the discounts stack: batch requests that share a long start can also be cache hits.
DeepSeek prices by the clock instead. Its peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday to Friday. Every other hour, including whole weekends and Chinese public holidays, costs half.
Standard list prices on 20 October 2026. Input costs 3 to 5 times less than output. OpenAI charges twice as much for input on long prompts. A hundredfold spread: always test whether a cheaper model is good enough for your task.
| Saving | The catch | |
|---|---|---|
| Cache hits | 90–98 % off the repeated input | Only exact repeats of the start |
| Batch API | 50 % off everything | Answers within 24 hours, not seconds |
| Off-peak hours (DeepSeek) | 50 % off everything | Only at certain hours |
| A smaller model | Often 10 times cheaper, or more | Weaker on hard problems; test it on your task |
| Shorter answers, less thinking | Output is the most expensive token | Ask for brevity; lower the thinking effort |
| Your own computer (last lesson) | No bill per token | You pay for the hardware and the electricity |
Quick check
Thinking tokens and streaming
Reasoning models think before they answer (the reasoning lesson). Those thinking tokens are output tokens: billed at the output price, and counted against max_tokens and the context window. A two-line answer can cost thousands of tokens.
- Set the effort. DeepSeek takes
reasoning_effort(low,highormax), or turns thinking off with{"thinking": {"type": "disabled"}}. Other providers have similar settings. - Leave room. If
max_tokensis small, thinking can use all of it, and you getfinish_reason: "length"with an empty answer. - Send the thinking back when tools are involved. DeepSeek returns its thinking in
reasoning_content. When a request includes tools, you must pass that thinking back in later turns, or the API answers with error 400. Without tools, it is ignored. - Some thinking is hidden. OpenAI’s Responses API returns reasoning encrypted: you pay for it and pass it back, but you cannot read it.
Without streaming, you wait for the whole answer. With "stream": true, the server sends every few tokens the moment decode makes them, as server-sent events: lines that begin with data:. The first words appear after the time to first token, not after the whole reply.
data: {"choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}
data: {"choices":[{"index":0,"delta":{"content":"Dividing"}}]}
data: {"choices":[{"index":0,"delta":{"content":" asks how"}}]}
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
- Each
deltacarries the next piece of text, and your program joins them up. Thinking models stream their thinking first (at DeepSeek, inreasoning_content). - The token counts come at the end. With OpenAI-style APIs you may need to add
"stream_options": {"include_usage": true}to get them in a last chunk.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["DEEPSEEK_API_KEY"], base_url="https://api.deepseek.com")
stream = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": "Explain the KV cache in three sentences."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
- The official
openailibrary works with any OpenAI-compatible server: onlybase_urland the key change. - While the model thinks,
delta.contentstays empty, so this prints only the answer.
Quick check
JSON you can trust
Programs need data, not prose. If your code expects {"sentiment": "positive"} and the model first writes “Sure! Here is the JSON:”, the program breaks. There are three levels of help.
Ask in the prompt
- Describe the format and give an example
- Usually works; sometimes breaks
- Works with any model
JSON mode
"response_format": {"type": "json_object"}- Always valid JSON, but in any shape
- You must still ask for JSON in the prompt
Structured outputs
- A JSON Schema with
"strict": true - Always valid JSON, in exactly your shape
- Not every provider has it: DeepSeek offers JSON mode
How can a model be forced to follow a schema? With constrained decoding, which changes sampling, not the model:
- The engine turns your schema into a grammar: a machine that knows which characters may come next.
- Before each token is sampled, it checks the vocabulary and marks the tokens that would keep the text valid.
- Every other token’s score is set to minus infinity, so its probability becomes zero (the sampling lesson).
- Sampling picks from what is left. The text is valid by construction: a wrong character can never be chosen.
import json
from openai import OpenAI
# vLLM from the serving lesson: vllm serve Qwen/Qwen3-8B
client = OpenAI(base_url="http://localhost:8000/v1", api_key="none")
schema = {
"type": "object",
"properties": {
"reasoning": {"type": "string"},
"sentiment": {"type": "string", "enum": ["positive", "negative", "mixed"]},
},
"required": ["reasoning", "sentiment"],
"additionalProperties": False,
}
reply = client.chat.completions.create(
model="Qwen/Qwen3-8B",
messages=[{"role": "user", "content": "Review: great battery, but the screen cracked in a week."}],
response_format={"type": "json_schema",
"json_schema": {"name": "review", "schema": schema, "strict": True}},
)
print(json.loads(reply.choices[0].message.content)["sentiment"])
enumlimits the answer to three words;additionalProperties: Falseforbids extra keys.- Order matters. The model writes the keys in order, so putting
reasoningbeforesentimentlets it think in words before it commits to an answer. OpenAI’s own examples put the steps before the final answer for the same reason. - The same request works with OpenAI’s API, and with llama-server, which also accepts JSON schemas.
Quick check
Limits, errors and retries
Providers limit how much you can send. Limits are counted in requests per minute, in tokens per minute (Anthropic counts input and output separately) or, at DeepSeek, in requests at the same time: 2,500 for Flash and 500 for V4 Pro. Go over and you get error 429. Anthropic’s limits refill continuously, like water running into a bucket, rather than resetting each minute, and for most of its models cache hits do not count towards the input limit at all.
| What it means | What to do | |
|---|---|---|
| 400 | The request is malformed | Fix it; sending it again will fail again |
| 401 | The API key is wrong or missing | Check the key |
| 402 | No balance left (DeepSeek) | Top up |
| 422 | A parameter is invalid (DeepSeek) | Fix the parameter |
| 429 | Too many requests, or too many tokens | Wait, then retry; obey the Retry-After header if there is one |
| 500 | Something broke on the server | Retry after a short wait |
| 503 | The model is overloaded | Retry after a longer wait |
Codes from DeepSeek’s documentation; OpenAI and Anthropic use the same meanings for the shared ones. A 429 can also mean you reached a spend limit you set yourself, and then waiting does not help.
import random, time
from openai import OpenAI, RateLimitError, InternalServerError, APIConnectionError
client = OpenAI(max_retries=0) # this code does the retrying itself
def ask(messages, tries=6):
for attempt in range(tries):
try:
return client.chat.completions.create(model="…", messages=messages)
except (RateLimitError, InternalServerError, APIConnectionError):
if attempt == tries - 1:
raise
# wait 1, 2, 4, 8 … seconds (at most 60), times a random 0.5 to 1
time.sleep(min(60, 2 ** attempt) * random.uniform(0.5, 1))
- Exponential backoff: wait twice as long after each failure, so a struggling server gets room to recover.
- Jitter: the random factor stops a thousand clients from retrying at the same instant and knocking the server over again. In AWS’s 2015 simulations with 100 competing clients, jitter cut the number of calls by more than half.
- The official OpenAI and Anthropic libraries already retry 429, 5xx and connection errors twice by default, with a short backoff. Raise
max_retriesfor long batch scripts, and never retry a 400 or a 401. - A 429 may carry
Retry-After: the number of seconds to wait. Treat it as the minimum.
Retry, or fix something first? Put each problem where it belongs.
-
429: too many requests this minute
Answer: Wait and retry
-
503: the model is overloaded
Answer: Wait and retry
-
The connection dropped halfway
Answer: Wait and retry
-
500: server error
Answer: Wait and retry
-
401: wrong API key
Answer: Fix something first
-
400: invalid request body
Answer: Fix something first
-
402: insufficient balance
Answer: Fix something first
-
429 after reaching your own spend limit
Answer: Fix something first
One format, many providers
OpenAI’s chat format became the common language of AI APIs. DeepSeek, Alibaba’s Model Studio (Qwen, and also DeepSeek, Kimi, GLM and MiniMax models), OpenRouter (one key for hundreds of models from many providers) and every local server in the last lesson accept it. Change the address, the key and the model name, and the same code talks to a different model. DeepSeek also accepts Anthropic’s format, so tools built for Claude can run on DeepSeek.
| base_url | |
|---|---|
| OpenAI | https:// |
| DeepSeek | https:// |
| DeepSeek, Anthropic format | https:// |
| Alibaba Model Studio, Singapore | https://{WorkspaceId}. |
| OpenRouter | https:// |
| vLLM on your machine | http:// |
| llama-server with --port 8080 | http:// |
| Ollama | http:// |
| LM Studio | http:// |
Model Studio’s address includes your workspace ID and region; Beijing, Virginia, Hong Kong and Tokyo have their own.
import os
from openai import OpenAI
deepseek = OpenAI(base_url="https://api.deepseek.com", api_key=os.environ["DEEPSEEK_API_KEY"])
router = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"])
at_home = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") # the key is ignored
for client, model in [(deepseek, "deepseek-flash"), (router, "deepseek/deepseek-r1"), (at_home, "gpt-oss:20b")]:
r = client.chat.completions.create(model=model, messages=[{"role": "user", "content": "Say hello in Urdu."}])
print(model, r.choices[0].message.content)
- OpenRouter names models as
maker/model. Ollama uses the names fromollama list.
OpenAI-style Chat Completions
- The system prompt is the first message
max_tokensis optional- The text is in
choices[0].message.content - Spoken by DeepSeek, Qwen, OpenRouter, vLLM, llama.cpp and Ollama
Anthropic Messages
- The system prompt is its own
systemfield max_tokensis required- The reply is a list of blocks: text, thinking, tool use
- Spoken by Claude, and by DeepSeek at its /anthropic address
Quick check
Remember
- An API call sends messages (system, user, assistant, tool) with your key. The reply holds the text, a finish_reason and the token usage you pay for.
- APIs are stateless: every turn resends the whole chat, so the input of a long chat grows with the square of its length.
- Prompt caching reuses the KV cache of an identical start, for 2–10 % of the normal price. Put stable things first, and never change the top of the prompt.
- Batch APIs halve the price when you can wait up to a day; DeepSeek halves it off-peak.
- Thinking tokens are billed as output. Streaming sends tokens as server-sent events the moment they are made.
- Structured outputs use constrained decoding: tokens that would break the schema get zero probability, so the JSON always fits.
- Retry 429 and 5xx errors with exponential backoff and jitter; fix 400 and 401. One OpenAI-compatible format reaches DeepSeek, Qwen, OpenRouter and your own computer.
Words to know
- API
- A way for one program to ask another for something. A model API is a web address that answers with text.
- API key
- A secret string that proves who you are and lets the provider charge you.
- Base URL
- The web address your requests go to, such as https://api.deepseek.com.
- Stateless
- Keeping no memory between requests. Each chat request must carry the whole conversation.
- Prompt caching
- Reusing the saved KV cache of a prompt’s start, so repeated tokens cost less and the reply starts sooner.
- Cache hit
- Input tokens that matched a saved start and were billed at the cheaper cached price.
- Batch API
- A way to send many requests at once and collect the answers later, for half price.
- Streaming
- Receiving the reply a few tokens at a time as it is made, instead of all at the end.
- Server-sent events (SSE)
- A simple web format for streaming: the server sends lines that start with “data:”.
- Structured outputs
- A setting that forces the reply to match a JSON schema you give.
- Constrained decoding
- Sampling in which every token that would break the required format gets zero probability.
- Rate limit
- The most requests or tokens a provider lets you send in a given time.
- Exponential backoff
- Waiting longer after each failed try: 1 second, then 2, 4, 8 and so on, with a little randomness.
- OpenAI-compatible
- Accepting the same request format as OpenAI’s Chat Completions API, so the same code works.
Go to the source
This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.
-
DeepSeek API: Models & Pricing
Flash and V4 Pro prices, cache-hit prices, peak hours and limits, as used in this lesson.
-
DeepSeek API: Context Caching
How the disk cache matches the start of a prompt, with worked examples.
-
Claude API: Prompt caching
Cache writes and reads, lifetimes, and how to mark what to cache.
-
OpenAI API: Prompt caching
Automatic caching, the 1,024-token minimum, and the maths of when caching pays.
-
OpenAI API: Batch
Batch files, the 24-hour window and batch limits.
-
Prompt Cache: Modular Attention Reuse for Low-Latency Inference
The research idea behind prompt caching: compute the attention states of text that many prompts share once, and reuse them.
-
Auditing Prompt Caching in Language Model APIs
Timing tests that found caches shared by all users at 7 of 17 providers, and why that can leak prompts.
-
Efficient Guided Generation for Large Language Models
The Outlines paper: a schema or a pattern becomes a state machine that masks tokens.
-
XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models
Fast grammar-constrained decoding that runs alongside the GPU.
-
Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models
The study that found strict formats can hurt reasoning. Read it together with the reply below.
-
Say What You Mean: A Response to ‘Let Me Speak Freely’
The reply from the team behind Outlines: with the same prompt, structured output scores as well or better.
-
Exponential Backoff And Jitter
Simulations showing why random jitter makes retries work. Still how AWS builds its own client libraries.
Check yourself
5 questions. Tap the answer you think is right.
0 of 5 answered
Lesson complete
Answer every question above to complete this lesson.
Your progress is saved on this device only.
Next lessonTool calling: giving a model hands