Availit World How AI really works, in your language

Lesson 30 of 4634 minFacts checked October 20, 2026

APIs: using a model over the internet

Most people reach the biggest models through an API: your program sends text to a provider’s servers, a serving engine like the ones in the last lessons runs the model, and you pay for every token. This lesson takes a real request and reply apart, shows why a long chat costs far more than its length suggests, and cuts the bill with caching, batch jobs and the clock. It also covers thinking tokens, streaming, JSON you can trust, rate limits and errors, and the one format that lets the same code talk to DeepSeek, Qwen, Claude, GPT or the model on your own computer.

In this lesson you will

  • Read every field of a chat request and its reply
  • Explain why the API forgets, and what that does to the cost of a long chat
  • Cut costs with prompt caching, batch jobs and off-peak hours
  • Know what thinking tokens and streaming change
  • Get JSON that always matches your schema, and know how constrained decoding does it
  • Handle rate limits and errors, and switch providers by changing one line
On this page
  1. What an API call is
  2. The API forgets everything
  3. Prompt caching: paying less for the same start
  4. Paying less when you can wait
  5. Thinking tokens and streaming
  6. JSON you can trust
  7. Limits, errors and retries
  8. One format, many providers
  9. Remember
  10. Check yourself

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.

One request, start to finish
  1. Your programBuilds the messages and sends them with your key
  2. The provider’s front doorChecks the key, your balance and your rate limits
  3. RouterPicks a copy of the model, ideally one that already has your prompt cached
  4. Serving enginePrefill, then decode, one token at a time
  5. The replyJSON with the text, why it stopped, and the token counts
A complete requestbash
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_KEY reads the key from an environment variable, so it never appears in your code.
  • messages is the whole conversation. The roles are system (instructions), user, assistant (the model’s earlier replies) and tool (results of tool calls, in the next lesson).
  • max_tokens caps the reply. temperature is 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.
The reply, shortenedjson
{
  "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_reason says why the model stopped: stop (it finished), length (it hit max_tokens, so the text is cut off), tool_calls (it wants to use a tool) or content_filter.
  • usage is 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

A reply ends with "finish_reason": "length". What happened?

Show the answer

Answer: The reply reached max_tokens and was cut off “length” means the token limit was reached in the middle of the answer. Raise max_tokens, or ask for a shorter answer.

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.

Why long chats cost more than they look
turn k sends: system + k messages + (k − 1) replies

Each 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 tokens

Yet 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.

Try itWhy long chats get expensive

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

On turn 30 of a chat, what does the model read?

Show the answer

Answer: The whole conversation, sent again by your app The API is stateless. Unless your app shortens the history, every turn carries all the turns before it, which is why caching matters so much.

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.

Caching at three providers
DeepSeekClaude (Anthropic)GPT (OpenAI)
Turning it onAlways onMark the prompt with cache_control, or turn on automatic cachingAlways on
A cache hit costs2 % of the normal input price (Flash), 3.3 % (V4 Pro)10 % on most models; 5 % or 2.5 % on some newer ones10 % on the newest models; 5 % on one
Writing to the cacheNo extra charge1.25 times the input price for a 5-minute cache, 2 times for 1 hour1.25 times the input price on the newest models
How long it lastsHours to days, best effort5 minutes, renewed each time it is used; or 1 hourFrom minutes to 24 hours, depending on the model
Where it is keptOn diskIn memory onlyNot stated
Where the reply shows itprompt_cache_hit_tokenscache_read_input_tokenscached_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

Your system prompt begins “Current time: 14:03:27”. What does that do to caching?

Show the answer

Answer: Almost every request misses, because each one starts differently The match starts at the very first token. Move the time to the end of the prompt, and everything before it can be a hit.

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.

Batch APIs
OpenAIAnthropic
Discount50 %50 %
Answers within24 hours, often sooner24 hours; most batches finish within 1 hour
Largest batch50,000 requests, or a 200 MB file100,000 requests, or 256 MB
Rate limitsA separate, much higher poolSeparate batch limits
One line of a batch file (OpenAI format)json
{"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_id lets 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.

Output price, US dollars per million tokens
  • GPT, smallest 0.5
  • Claude Haiku 0.5
  • DeepSeek Flash, off-peak 0.6
  • DeepSeek Flash, peak 1.2
  • DeepSeek V4 Pro, peak 3.96
  • Claude Sonnet 10
  • GPT, mid-size 10
  • Claude Opus 20
  • GPT, largest 50

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.

Ways to cut the bill
SavingThe catch
Cache hits90–98 % off the repeated inputOnly exact repeats of the start
Batch API50 % off everythingAnswers within 24 hours, not seconds
Off-peak hours (DeepSeek)50 % off everythingOnly at certain hours
A smaller modelOften 10 times cheaper, or moreWeaker on hard problems; test it on your task
Shorter answers, less thinkingOutput is the most expensive tokenAsk for brevity; lower the thinking effort
Your own computer (last lesson)No bill per tokenYou pay for the hardware and the electricity

Quick check

You must label 200,000 product reviews by tomorrow morning. Which choice saves the most?

Show the answer

Answer: The batch API, with the same instructions at the start of every request Batch halves the price, and identical instructions at the start can also be cache hits. Streaming and temperature do not change the bill.

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, high or max), or turns thinking off with {"thinking": {"type": "disabled"}}. Other providers have similar settings.
  • Leave room. If max_tokens is small, thinking can use all of it, and you get finish_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.

What a stream looks liketext
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 delta carries the next piece of text, and your program joins them up. Thinking models stream their thinking first (at DeepSeek, in reasoning_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.
Streaming in Pythonpython
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 openai library works with any OpenAI-compatible server: only base_url and the key change.
  • While the model thinks, delta.content stays empty, so this prints only the answer.

Quick check

A thinking model writes 3,000 tokens of thinking and a 100-token answer. What do you pay for?

Show the answer

Answer: 3,100 output tokens Thinking tokens are output tokens, billed at the output price, even when you never see them.

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:

  1. The engine turns your schema into a grammar: a machine that knows which characters may come next.
  2. Before each token is sampled, it checks the vocabulary and marks the tokens that would keep the text valid.
  3. Every other token’s score is set to minus infinity, so its probability becomes zero (the sampling lesson).
  4. Sampling picks from what is left. The text is valid by construction: a wrong character can never be chosen.
Structured output from your own serverpython
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"])
  • enum limits the answer to three words; additionalProperties: False forbids extra keys.
  • Order matters. The model writes the keys in order, so putting reasoning before sentiment lets 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

Why put a "reasoning" field before the "answer" field in a schema?

Show the answer

Answer: The model writes in order, so the answer can build on reasoning it has already written Each token depends on the tokens before it. Reasoning written first can help the answer; reasoning written after it cannot.

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.

Errors you will meet
What it meansWhat to do
400The request is malformedFix it; sending it again will fail again
401The API key is wrong or missingCheck the key
402No balance left (DeepSeek)Top up
422A parameter is invalid (DeepSeek)Fix the parameter
429Too many requests, or too many tokensWait, then retry; obey the Retry-After header if there is one
500Something broke on the serverRetry after a short wait
503The model is overloadedRetry 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.

Retrying the right waypython
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_retries for 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.

0 of 8 sorted
  • 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.

Where to point the same code
base_url
OpenAIhttps://api.openai.com/v1
DeepSeekhttps://api.deepseek.com
DeepSeek, Anthropic formathttps://api.deepseek.com/anthropic
Alibaba Model Studio, Singaporehttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
OpenRouterhttps://openrouter.ai/api/v1
vLLM on your machinehttp://localhost:8000/v1
llama-server with --port 8080http://localhost:8080/v1
Ollamahttp://localhost:11434/v1
LM Studiohttp://localhost:1234/v1

Model Studio’s address includes your workspace ID and region; Beijing, Virginia, Hong Kong and Tokyo have their own.

Same code, three placespython
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 from ollama list.

OpenAI-style Chat Completions

  • The system prompt is the first message
  • max_tokens is 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 system field
  • max_tokens is required
  • The reply is a list of blocks: text, thinking, tool use
  • Spoken by Claude, and by DeepSeek at its /anthropic address

Quick check

Your app uses the openai Python library with DeepSeek. What must change to try a model running in Ollama on your laptop?

Show the answer

Answer: The base URL, the key and the model name Ollama serves the same format at http://localhost:11434/v1. Only the address, a placeholder key and the model name change.

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.

Check yourself

5 questions. Tap the answer you think is right.

0 of 5 answered

Why does turn 40 of a chat cost much more than turn 2?

Show the answer

Answer: Each turn resends the whole conversation, so the input keeps growing The API is stateless. Turn 40 carries the system prompt and all 39 earlier turns.

What makes a cache hit possible?

Show the answer

Answer: The new request starts with exactly the same tokens as one the server processed recently Caching reuses the KV cache of an identical start. Similar meaning is not enough: the tokens must match from the first one.

Which job suits a batch API?

Show the answer

Answer: Translating 30,000 product descriptions overnight Batch jobs can take up to 24 hours. Nobody is waiting, so half price is a good trade.

How does constrained decoding guarantee valid JSON?

Show the answer

Answer: It gives zero probability to every token that would break the format Before each token is sampled, the engine masks every token the grammar does not allow, so an invalid character can never be chosen.

You get error 429. What should your program do?

Show the answer

Answer: Wait, using Retry-After if it is given, then retry with growing, slightly random delays 429 means slow down. Exponential backoff with jitter lets the limit refill without every client retrying at the same moment.

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
Previous lesson All lessons

Choose your language