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
- Builds on
- 4 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 4 concepts before this one
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.
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?"},
],
)
modelpicks the model by its exact id. As of late 2026 Anthropic's current models areclaude-opus-5-5(most capable of the everyday models),claude-sonnet-5-5(balanced) andclaude-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_tokensis 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.systemis the system prompt (see Prompt Engineering).messagesis the conversation: alternatinguserandassistantturns, starting withuser.
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, ...
contentis a list of content blocks. Usually there is a text block, and there may be others:thinkingblocks from reasoning, ortool_useblocks 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_reasonis the stop reason: why generation ended.end_turnmeans the model finished.max_tokensmeans it was cut off, so your answer is incomplete.tool_usemeans it is waiting for a tool result.refusalmeans it declined. Check this every time: a truncated reply that your code treats as complete is a classic silent bug.usagereports 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
temperaturebetween 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 astemperature, and reasoning models in general control randomness themselves. If you seetemperaturein 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:
where and are the input and output token counts, and and 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 . The average answer is 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 ascreateand returnsinput_tokenswithout running the model. Each provider has its own tokenizer, so counts from one don't transfer to another. - Log
usageon 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.
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 atmax_tokenslooks like a normal reply to code that doesn't check. Check it, and either raisemax_tokensor 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
- Structured Output and JSON: getting validated JSON back instead of free text.
- Tool Use and Function Calling: letting the model call your functions, the step from chatbot to agent.
- Embeddings and Semantic Search: the other API you will use constantly, embeddings.
- Context Engineering and Memory: managing what goes into each request, including prompt caching.
- Evaluating LLM Applications: testing prompts and models systematically before you ship.
- Running Models Locally: the same API shape served from your own machine.
- Building AI Products: latency, cost and reliability as product decisions.
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
- Make your first call: ask a model to explain what an API is in two sentences. Print
stop_reasonandusage, and compute the cost with thecostfunction above.- Set
max_tokens=20and ask for a long answer. What isstop_reasonnow? Write a check that raises an error when the reply was truncated.- 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.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Claude API documentation
The official reference for the Messages API: authentication, request and response shapes, streaming, errors, rate limits and every feature.
Anthropic Courses
Notebook courses on the Claude API, prompt engineering, real-world prompting, prompt evaluations and tool use.
OpenAI developer quickstart
Set up a key, install the SDK and make a first Responses API call, with links to every other API guide.
Anthropic Python SDK
The official anthropic package, with a README full of examples for messages, streaming, retries, timeouts and error types.
OpenAI Python SDK
The official openai package, with examples for the Responses API, streaming, async use, retries and errors.
Claude Cookbooks
Runnable notebooks for real tasks with Claude: RAG, contextual retrieval, structured JSON, tool use, prompt caching, sub-agents and more.
OpenAI Cookbook
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