◆ AI All-in-One

Level 2 Agentic Coding · Building with AI

Using LLM APIs

How to call a language model from your own code. API keys, the messages format, system prompts and parameters, streaming, counting tokens and working out the cost, rate limits, retries and error handling, with Anthropic's and OpenAI's official Python SDKs.

Level
●●●●● Easy
Reading
14 min
To learn it well
1 hour to read, an afternoon to build something
↗ Plan a path here

Read first

Python for AILarge Language Models, Explained Simply

This leads to

Evaluating LLM ApplicationsEmbeddings and Semantic SearchStructured Output and JSONTool Use and Function Calling
The full path from zero — 4 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Large Language Models, Explained Simply
  5. Using LLM APIs

Read them roughly in this order. See it on the concept map →

Why it matters

Chat apps are where most people meet language models, but almost every AI product is built on an API (application programming interface): a way for your program to send a request over the internet to the provider's servers and get the model's reply back as data. Classifying support tickets, extracting data from invoices, a chatbot on your website, a question-answering system over your documents, an agent that writes code: each is ordinary code plus calls to an LLM API.

The basics take ten minutes to learn. The details decide whether your app is cheap or expensive, fast or sluggish, robust or flaky: tokens and cost, streaming, rate limits and retries. This chapter covers both, using the official Python SDKs (software development kits: libraries that wrap the raw HTTP calls) from Anthropic and OpenAI. Other providers' APIs, and local servers such as Ollama, follow the same shape.

The intuition

Think of the model as a brilliant consultant you reach by post, who has total amnesia. Each letter you send must contain everything: who they are working for and the house rules (the system prompt), the whole conversation so far, and the new question. They write back a reply, plus an invoice listing how many words they read and how many they wrote. If you send another letter, they remember nothing of the first unless you include it again.

That is exactly how a chat API works:

  • Stateless. The API keeps no memory between calls. "Conversation memory" is your program re-sending the earlier messages every time.
  • Metered by the token. You pay for every token read (input) and every token written (output). Re-sending a long history means paying to read it again. Context Engineering and Memory is largely about managing that.
  • Rate-limited. Each account may send only so many requests and tokens per minute. Exceed that and calls are refused for a while.
Request (you send) Response (you get back) model: "claude-sonnet-5-5" max_tokens: 1024 ← hard cap on the reply system: "You are a concise gardening assistant." messages: the full conversation user: "When should I prune apples?" assistant: "In late winter, while…" user: "And plum trees?" ← new the API remembers nothing between calls, so earlier turns are re-sent (and re-billed) LLM API server content: [ blocks ] text: "Plums are pruned in summer, not winter, to…" (may also hold thinking or tool_use blocks) stop_reason: "end_turn" or "max_tokens" = cut off! usage (your bill) input_tokens: 62 output_tokens: 95 cost = (62 × $2 + 95 × $10) ÷ 1,000,000 ≈ $0.0011
Fig. 1 An API call. The request carries the model name, a token limit, the system prompt and the full list of messages. The response carries content blocks with the reply, a stop reason saying why the model stopped, and a usage record of the input and output tokens you are billed for.

Key idea An LLM API call sends the whole conversation and gets back the next reply plus a token count. Everything else (memory, cost control, reliability) is code you write around that one call.

How it works

Keys and environment variables

To use an API you create an account in the provider's console and generate an API key, a long secret string that identifies you and is billed for every call. Anyone with your key can spend your money.

Never write the key in your code. Put it in an environment variable, a named value that the operating system passes to your program:

export ANTHROPIC_API_KEY="sk-ant-..."     # macOS / Linux; add to your shell profile
export OPENAI_API_KEY="sk-..."
pip install anthropic openai

Both SDKs read these variables automatically. For projects, many people keep keys in a .env file loaded by the python-dotenv package. Either way, add that file to .gitignore. Keys pushed to public GitHub repositories are found by scanners within minutes.

The request

Here is a complete call with Anthropic's SDK, using the Messages API:

import anthropic

client = anthropic.Anthropic()                 # reads ANTHROPIC_API_KEY

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    system="You are a concise assistant for a gardening website.",
    messages=[
        {"role": "user", "content": "When should I prune apple trees?"},
    ],
)
  • model picks the model by its exact id. As of late 2026 Anthropic's current models are claude-opus-5-5 (most capable of the everyday models), claude-sonnet-5-5 (balanced) and claude-haiku-5-5 (fastest and cheapest). Ids change with every release, so read them from the provider's models page and keep them in one config setting, not scattered through your code.
  • max_tokens is the max tokens limit: a hard cap on how many tokens the reply may contain. It protects you from runaway costs. If the model hits it, the reply is cut off mid-sentence. On models that think before answering (Chain-of-Thought and Reasoning Prompts), thinking counts towards it, so leave room.
  • system is the system prompt (see Prompt Engineering).
  • messages is the conversation: alternating user and assistant turns, starting with user.

The response

for block in response.content:
    if block.type == "text":
        print(block.text)
print(response.stop_reason)         # "end_turn"
print(response.usage)               # input_tokens=31, output_tokens=87, ...
  • content is a list of content blocks. Usually there is a text block, and there may be others: thinking blocks from reasoning, or tool_use blocks when the model wants to call one of your functions (Tool Use and Function Calling). Always check the block type rather than assuming the first block is text.
  • stop_reason is the stop reason: why generation ended. end_turn means the model finished. max_tokens means it was cut off, so your answer is incomplete. tool_use means it is waiting for a tool result. refusal means it declined. Check this every time: a truncated reply that your code treats as complete is a classic silent bug.
  • usage reports input tokens (what was read) and output tokens (what was written, including any thinking). This is your bill.

Multi-turn conversations

To continue a conversation, append the reply and the next question, then send the whole list again:

messages = [{"role": "user", "content": "When should I prune apple trees?"}]
reply = client.messages.create(model="claude-sonnet-5-5", max_tokens=1024,
                               messages=messages)
messages.append({"role": "assistant", "content": reply.content})
messages.append({"role": "user", "content": "And plum trees?"})
reply = client.messages.create(model="claude-sonnet-5-5", max_tokens=1024,
                               messages=messages)

Appending reply.content (the full list of blocks, not just the text) keeps any thinking or tool blocks the API needs to see again.

Parameters worth knowing

  • Effort. On current reasoning models this is the main quality-versus-cost knob: output_config={"effort": "low"} for simple, high-volume tasks, "high" for hard ones. See Chain-of-Thought and Reasoning Prompts.
  • Temperature. Older models accept a temperature between 0 and 1 or 2 that controls randomness in decoding: low for consistent output, high for variety. As of late 2026, Anthropic's newest models no longer accept sampling parameters such as temperature, and reasoning models in general control randomness themselves. If you see temperature in an old tutorial, check your model's documentation before copying it.
  • Stop sequences. A list of strings that end generation when produced, for example stop_sequences=["</answer>"].
  • Metadata and timeouts. Both SDKs let you set a per-request timeout and attach a user id for abuse monitoring.

Tokens and cost

Providers price per million tokens, with output tokens several times dearer than input tokens. As of November 2026 Anthropic's list prices are:

Model Input $ per 1M tokens Output $ per 1M tokens
claude-opus-5-5 4.00 20.00
claude-sonnet-5-5 2.00 10.00
claude-haiku-5-5 0.10 0.50

The cost of one call is:

cost=nin×pin+nout×pout1,000,000\text{cost} = \frac{n_{\text{in}} \times p_{\text{in}} + n_{\text{out}} \times p_{\text{out}}}{1{,}000{,}000}

where ninn_{\text{in}} and noutn_{\text{out}} are the input and output token counts, and pinp_{\text{in}} and poutp_{\text{out}} are the prices per million.

Worked example. A support bot has a 1,000-token system prompt, and the average question adds 500 tokens, so nin=1,500n_{\text{in}} = 1{,}500. The average answer is nout=300n_{\text{out}} = 300 tokens. On Sonnet: $(1{,}500 \times 2 + 300 \times 10) / 1{,}000{,}000 = (3{,}000 + 3{,}000)/1{,}000{,}000 = $0.006$ per call. At 100,000 questions a month that is $600. On Haiku it is $0.0003 per call, or $30 a month. On Opus, $1,200. The cheapest model that passes your tests can save 95% of the bill.

Three habits keep costs predictable:

  • Estimate tokens. For English text, one token is roughly 4 characters or three-quarters of a word, so 1,000 words is about 1,300 tokens. For exact counts, ask the API: Anthropic's client.messages.count_tokens(...) takes the same arguments as create and returns input_tokens without running the model. Each provider has its own tokenizer, so counts from one don't transfer to another.
  • Log usage on every call. Real token counts beat estimates, and they reveal surprises such as long thinking or bloated histories.
  • Use the discounts. A batch API processes requests asynchronously, within 24 hours and often much sooner (Anthropic says most batches finish in under an hour), at 50% of the normal price on both Anthropic and OpenAI. Use it for anything nobody is waiting for: nightly classification, evaluations, backfills. Prompt caching makes a repeated prompt prefix much cheaper to re-read (see Context Engineering and Memory).

Streaming

A long answer can take many seconds to generate. Without streaming, the user stares at a spinner until the last token is ready. With streaming, the API sends tokens as they are produced, and you display them immediately. The total time is the same, but the time to first token, which is what users perceive as speed, drops to a second or so.

Without streaming With streaming user sees a spinner while the whole answer is generated all text arrives at once time to first token: text starts appearing almost at once each green bar = a chunk of tokens shown as soon as it is generated 0 8 s time (illustrative): total generation time is the same, the wait before anything appears is not
Fig. 2 Streaming versus waiting. Without streaming, nothing appears until the whole answer is generated. With streaming, text appears almost at once and grows as tokens are produced. The total generation time is the same.
with client.messages.stream(
    model="claude-sonnet-5-5",
    max_tokens=2048,
    messages=[{"role": "user", "content": "Write a short poem about compost."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    final = stream.get_final_message()     # full message, with usage
print("\n", final.usage.output_tokens, "output tokens")

Streaming is also needed for very long outputs: the SDKs refuse non-streaming requests whose max_tokens is so large they might hit an HTTP timeout.

Errors, rate limits and retries

Things go wrong in production. The main cases, with their HTTP status codes:

Code Meaning What to do
400 Bad request (malformed messages, unknown parameter) Fix the code. Don't retry.
401 / 403 Bad key or no permission Fix the key. Don't retry.
429 Rate limit exceeded Wait and retry. The retry-after header says how long.
500, 529 Server error, or overloaded (Anthropic's 529) Wait and retry.

Rate limits are set per organisation, in requests per minute and tokens per minute, and rise as your account's spending tier rises. When you hit one, retrying immediately just gets refused again. The standard fix is exponential backoff: wait, and double the wait after each failure (1 s, 2 s, 4 s…), plus a small random jitter so that many clients don't all retry at the same instant.

Both official SDKs already retry connection errors, 408, 409, 429 and 5xx responses with exponential backoff, twice by default. You can change that with anthropic.Anthropic(max_retries=5, timeout=30.0) (and the same arguments on openai.OpenAI). Catch the errors that survive the retries by type, most specific first:

try:
    response = client.messages.create(model="claude-sonnet-5-5", max_tokens=1024,
                                      messages=messages)
except anthropic.RateLimitError:
    ...                    # still rate-limited after retries: queue it for later
except anthropic.APIStatusError as e:
    if e.status_code >= 500:
        ...                # provider trouble: retry later or fail over
    else:
        raise              # a 4xx is a bug in our request
except anthropic.APIConnectionError:
    ...                    # network problem

The same thing with OpenAI

OpenAI's current interface is the Responses API. The shape differs slightly, the ideas are identical:

from openai import OpenAI

client = OpenAI()                                  # reads OPENAI_API_KEY
response = client.responses.create(
    model="gpt-6.2-sol",                           # check the models page for current ids
    instructions="You are a concise assistant for a gardening website.",
    input="When should I prune apple trees?",
    reasoning={"effort": "low"},
)
print(response.output_text)
print(response.usage.input_tokens, response.usage.output_tokens)

stream = client.responses.create(model="gpt-6.2-sol", input="A poem about compost.",
                                 stream=True)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)

instructions plays the role of the system prompt, and input can be a string or a list of role-tagged messages. OpenAI's older Chat Completions API (client.chat.completions.create) is still widely used in tutorials and by other providers that copy its format.

In code

The two pieces of API plumbing you will write yourself, runnable offline: a cost estimator, and exponential backoff with jitter around a fake API that fails twice with a 429 before succeeding.

import random
import time

# Prices in US dollars per million tokens (Anthropic list prices, late 2026).
PRICES = {"claude-opus-5-5":   (4.00, 20.00),
          "claude-sonnet-5-5": (2.00, 10.00),
          "claude-haiku-5-5":  (0.10, 0.50)}

def cost(model, input_tokens, output_tokens):
    p_in, p_out = PRICES[model]
    return (input_tokens * p_in + output_tokens * p_out) / 1_000_000

for model in PRICES:
    per_call = cost(model, input_tokens=1_500, output_tokens=300)
    print(f"{model:18s} ${per_call:.5f} per call, ${per_call * 100_000:,.0f} per 100k calls")

class RateLimited(Exception):
    pass

def flaky_api(calls=[0]):
    calls[0] += 1                        # fails twice, then succeeds
    if calls[0] < 3:
        raise RateLimited("429 Too Many Requests")
    return "ok"

def with_backoff(fn, max_tries=5, base=0.1):
    for attempt in range(max_tries):
        try:
            return fn()
        except RateLimited as e:
            if attempt == max_tries - 1:
                raise
            delay = base * 2 ** attempt + random.uniform(0, base)   # jitter
            print(f"attempt {attempt + 1} failed ({e}); waiting {delay:.2f}s")
            time.sleep(delay)

random.seed(0)
print(with_backoff(flaky_api))
# claude-opus-5-5    $0.01200 per call, $1,200 per 100k calls
# claude-sonnet-5-5  $0.00600 per call, $600 per 100k calls
# claude-haiku-5-5   $0.00030 per call, $30 per 100k calls
# attempt 1 failed (429 Too Many Requests); waiting 0.18s
# attempt 2 failed (429 Too Many Requests); waiting 0.28s
# ok

In real code you would usually rely on the SDK's built-in retries and keep a wrapper like this only for extra behaviour, such as falling back to another model. Put the cost function next to your logging, feed it response.usage, and you have a running bill per feature, per user or per day.

Common pitfalls

  • Ignoring stop_reason. A reply cut off at max_tokens looks like a normal reply to code that doesn't check. Check it, and either raise max_tokens or ask for shorter output.
  • Assuming the first content block is text. With thinking or tools enabled, it often isn't. Loop over blocks and check .type.
  • Re-sending ever-growing histories. Each turn re-reads the whole conversation, so a 50-turn chat pays for turn 1 fifty times. Trim, summarise or cache (see Context Engineering and Memory).
  • Retrying everything. Retrying a 400 just repeats the same mistake, and retrying 429s without backoff makes the rate limiting worse.
  • Hard-coding model ids everywhere. Models are retired on published schedules. Keep the id in one setting so an upgrade is a one-line change plus a test run.
  • Calling the API from a web page or mobile app. Code that runs on users' devices exposes your key to anyone who looks. Always call the LLM from your own server.

Danger A leaked API key is a blank cheque. Keep keys in environment variables or a secrets manager, never in code, notebooks, screenshots or front-end JavaScript. Set a monthly spend limit in the provider's console, and revoke any key you suspect has leaked straight away.

Where it leads

A bit of history

OpenAI opened the GPT-3 API in 2020 with a simple "completions" endpoint: send text, get a continuation. In March 2023 it introduced the Chat Completions format, with a list of role-tagged messages, alongside the gpt-3.5-turbo model. That format became a de facto standard that many other providers and local servers copied. Anthropic launched its API for Claude in 2023 and soon introduced the Messages API, with explicit content blocks. Streaming, function calling (Tool Use and Function Calling), JSON modes, batch processing and prompt caching followed over 2023 and 2024. In March 2025 OpenAI introduced the Responses API, designed around reasoning models and built-in tools. Prices per token fell sharply over the same years, so tasks that were too expensive to automate in 2022 cost fractions of a cent per call by 2025.

Try it

  1. Make your first call: ask a model to explain what an API is in two sentences. Print stop_reason and usage, and compute the cost with the cost function above.
  2. Set max_tokens=20 and ask for a long answer. What is stop_reason now? Write a check that raises an error when the reply was truncated.
  3. Build a tiny command-line chat loop: read a line, append it to messages, stream the reply, append the reply, repeat. Print the running total of input and output tokens after each turn, and watch the input count grow.

Hint for 3: the input tokens grow every turn because you re-send the whole history. That growth is the problem Context Engineering and Memory solves.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your code treats every reply as complete, but some summaries end mid-sentence. What should it check?

  2. A support bot sends 1,500 input tokens and gets 300 output tokens per call, on a model priced at $2 per million input and $10 per million output. What does one call cost?

  3. Your calls start failing with HTTP 429. What is the right response?

  4. You need to classify 200,000 old tickets overnight, and nobody is waiting for the results. What is the cheapest sensible option?

  5. Users complain your chatbot feels slow, though the total generation time is fine. What does streaming change?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

Claude API documentation

Anthropic · Beginner · Free

The official reference for the Messages API: authentication, request and response shapes, streaming, errors, rate limits and every feature.

Course

Anthropic Courses

Anthropic · Beginner · Free

Notebook courses on the Claude API, prompt engineering, real-world prompting, prompt evaluations and tool use.

Docs

OpenAI developer quickstart

OpenAI · Beginner · Free

Set up a key, install the SDK and make a first Responses API call, with links to every other API guide.

Tool

Anthropic Python SDK

Anthropic · Beginner · Free

The official anthropic package, with a README full of examples for messages, streaming, retries, timeouts and error types.

Tool

OpenAI Python SDK

OpenAI · Beginner · Free

The official openai package, with examples for the Responses API, streaming, async use, retries and errors.

Tutorial

Claude Cookbooks

Anthropic · Intermediate · Free

Runnable notebooks for real tasks with Claude: RAG, contextual retrieval, structured JSON, tool use, prompt caching, sub-agents and more.

Tutorial

OpenAI Cookbook

OpenAI · Intermediate · Free

Worked examples for common tasks with LLM APIs: embeddings, RAG, function calling, evals.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/using-llm-apis.md