Call an LLM API from Python: OpenAI and Anthropic, step by step
A beginner's guide to calling OpenAI and Claude from Python in 2026: keys in env vars, first call, streaming, JSON output, retries, timeouts and cost logs.
Chatting with a model in a browser and calling it from code are different jobs. In code, the model becomes a function: text goes in, text (or JSON) comes out, and a loop can run it over a thousand support tickets while you get coffee. This post walks through that function for the two SDKs most people start with, OpenAI's openai package and Anthropic's anthropic package, side by side.
It covers install, API keys, the first call, system prompts, streaming, structured JSON output, errors with retries and timeouts, and a token and cost log. Every code block below ran against the SDK versions listed in the next section. No real API keys were used: the calls went to a small local fake server that speaks both wire formats. The section "How this code was tested" says exactly what ran where, so you know which outputs are real model text and which are canned.
What happens on one call#
your script SDK client provider API
----------- ---------- ------------
prompt, model, settings ---> adds API key header, --HTTPS--> /v1/responses (OpenAI)
builds JSON body, /v1/messages (Anthropic)
retries 429/5xx,
enforces timeout
answer text, usage <--- parses JSON into <--JSON--- output + token usage
typed Python objects
The SDK is a thin HTTP client with good defaults. Knowing that helps when something breaks: an "authentication" error is a header problem, a timeout is the HTTP layer, and a wrong answer is the prompt. They need different fixes.
Set up the project#
Make a folder and a virtual environment so the packages stay out of your system Python.
mkdir llm-hello && cd llm-hello
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install openai anthropic
pip list | grep -iE "^(openai|anthropic|pydantic) "
On 24 November 2026 that printed:
anthropic 2.13.0
openai 3.58.0
pydantic 2.14.4
Both SDKs move fast. If a parameter in this post fails on your machine, compare your version with the one above before anything else. Pydantic comes in as a dependency and is used later for structured output.
Keep the key out of your code#
Create a key in the OpenAI dashboard or the Claude Console. Each key is shown once, so copy it into a password manager straight away.
Then put it in an environment variable. Never paste it into a .py file: files get committed, shared in screenshots and pasted into chat windows, and a leaked key is spending money for someone else within hours. OpenAI's key safety guide says the same.
export OPENAI_API_KEY="sk-..." # macOS / Linux, current shell only
export ANTHROPIC_API_KEY="sk-ant-..."
To keep keys across sessions, put those lines in a .env file, add .env to .gitignore, and load it with python-dotenv or your shell. Both clients read their variable automatically when you create them with no arguments.
If the variable is missing, you find out at different moments. The OpenAI client fails as soon as you construct it:
openai.OpenAIError: Missing credentials. Please pass an `api_key`, `workload_identity`, `admin_api_key`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.
The Anthropic client constructs fine and fails on the first request:
TypeError: "Could not resolve authentication method. Expected one of api_key, auth_token, or credentials to be set. Or for the `Authorization` header to be explicitly omitted"
Both messages came from the installed SDKs with the variable unset. If you see either one, check echo $OPENAI_API_KEY in the same terminal that runs Python. A key exported in one terminal tab does not exist in another.
Pick a model#
Model names change every few months, so take them from the official pages, not from a tutorial (including this one) or from a model's memory. As of 24 November 2026:
| Model ID | Provider | Input / output price per 1M tokens | Use it for |
|---|---|---|---|
gpt-6-luna |
OpenAI | $0.10 / $0.50 | cheap, high-volume work |
gpt-6.2-sol |
OpenAI | $2 / $10 | everyday default |
claude-haiku-5-5 |
Anthropic | $0.10 / $0.50 (prompts up to 100k tokens) | cheap, high-volume work |
claude-sonnet-5-5 |
Anthropic | $2 / $10 | everyday default |
Prices are standard tier, from the OpenAI pricing page, the OpenAI models page, Anthropic's models overview and Anthropic's pricing page. Haiku 5.5 costs $0.50 / $2.50 once a prompt goes over 100,000 tokens. The examples use the two cheap models, because a learning script should cost fractions of a cent.
The first call, with a system prompt#
OpenAI's current interface is the Responses API (client.responses.create), and its quickstart uses it. The older client.chat.completions.create still works, and you will see it in older code. Anthropic's interface is the Messages API (client.messages.create).
from openai import OpenAI
from anthropic import Anthropic
QUESTION = "Explain recursion in one sentence for a beginner."
SYSTEM = "You are a patient Python tutor. Answer in plain English, no code."
openai_client = OpenAI() # reads OPENAI_API_KEY from the environment
anthropic_client = Anthropic() # reads ANTHROPIC_API_KEY from the environment
r = openai_client.responses.create(
model="gpt-6-luna",
instructions=SYSTEM,
input=QUESTION,
max_output_tokens=200,
)
print("OpenAI: ", r.output_text)
m = anthropic_client.messages.create(
model="claude-haiku-5-5",
max_tokens=200,
system=SYSTEM,
messages=[{"role": "user", "content": QUESTION}],
)
print("Anthropic:", m.content[0].text)
Output against the local fake server (the sentence is canned text, not a model's answer):
OpenAI: Recursion is a function that calls itself on a smaller input until it hits a base case.
Anthropic: Recursion is a function that calls itself on a smaller input until it hits a base case.
The two calls look alike, and the differences are where beginners trip.
- The system prompt. OpenAI takes it as
instructions. Anthropic takes it as a top-levelsystemargument, not as a message with"role": "system"in the list. - The output cap.
max_tokensis required on Anthropic's call; the Python SDK raisesTypeError: Missing required argumentsbefore anything is sent. On OpenAI the cap is optional and namedmax_output_tokens. - Reading the answer. OpenAI's response has an
output_textshortcut that joins all text parts. Anthropic returns a list of content blocks;m.content[0].textis fine for a plain question, but once you use tools or thinking the first block may not be text, so loop overm.contentand pickblock.type == "text". - Input shape. OpenAI's
inputcan be a plain string or a list of messages. Anthropic always wants the list.
For a multi-turn chat, you keep the history yourself and send it every time. Append the assistant's reply and the next user message to the list, then call again. That growing list is also why long chats get expensive: every turn pays for all the turns before it. The post on prompting Claude with fewer tokens covers how to trim it.
Stream the answer as it is written#
A 500-token answer can take several seconds. With streaming, the first words show up within a second and the rest follow, which matters for any chat UI. Both SDKs have a stream helper that runs as a context manager and gives you the full response at the end.
from openai import OpenAI
from anthropic import Anthropic
QUESTION = "Explain recursion in one sentence for a beginner."
print("OpenAI: ", end="")
with OpenAI().responses.stream(model="gpt-6-luna", input=QUESTION) as stream:
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
final = stream.get_final_response()
print(f"\n [{final.usage.output_tokens} output tokens]")
print("Anthropic: ", end="")
with Anthropic().messages.stream(
model="claude-haiku-5-5",
max_tokens=200,
messages=[{"role": "user", "content": QUESTION}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print(f"\n [{final.usage.output_tokens} output tokens]")
Output (fake server, sending one word every 50 ms over server-sent events):
OpenAI: Recursion is a function that calls itself on a smaller input until it hits a base case.
[19 output tokens]
Anthropic: Recursion is a function that calls itself on a smaller input until it hits a base case.
[21 output tokens]
OpenAI's stream yields typed events, and you filter for response.output_text.delta (the streaming guide lists the rest). Anthropic's helper gives you text_stream, which yields only the text. Under the hood it handles message_start, content_block_delta and the other events described in Anthropic's streaming docs.
One real gotcha showed up while building the fake server. The OpenAI stream helper raised RuntimeError: Received a content event for output index 0 before receiving its output item until the server sent response.output_item.added and response.content_part.added before the text deltas. The real API always sends those, so you will not hit this in production, but it shows the helper checks event order strictly. If you write your own proxy or mock, send the full event sequence.
To stream to a browser rather than a terminal, you need server-sent events from your own backend. Building a production LLM API with FastAPI does that end to end.
Get JSON you can trust#
Asking for JSON in the prompt works most of the time. "Most of the time" breaks a pipeline that processes ten thousand rows. Both providers now support schema-constrained output, and both Python SDKs accept a Pydantic model directly and hand back a validated object.
from typing import Literal
from pydantic import BaseModel
from openai import OpenAI
from anthropic import Anthropic
class Review(BaseModel):
sentiment: Literal["positive", "neutral", "negative"]
product: str
refund_requested: bool
TEXT = "The earbuds died after two days. I want my money back."
PROMPT = f"Extract the fields from this customer review:\n{TEXT}"
r = OpenAI().responses.parse(model="gpt-6-luna", input=PROMPT, text_format=Review)
print("OpenAI: ", repr(r.output_parsed))
m = Anthropic().messages.parse(
model="claude-haiku-5-5",
max_tokens=300,
messages=[{"role": "user", "content": PROMPT}],
output_format=Review,
)
print("Anthropic:", repr(m.parsed_output))
Output (fake server returns a fixed JSON string when a schema is present):
OpenAI: Review(sentiment='negative', product='earbuds', refund_requested=True)
Anthropic: Review(sentiment='negative', product='earbuds', refund_requested=True)
The fake server cannot show the model obeying a schema, but it can show what each SDK sends. It logged the request bodies, and the parts that differ are these:
OpenAI text.format = {"type": "json_schema", "strict": true, "name": "Review",
"schema": {..., "required": ["sentiment", "product", "refund_requested"],
"additionalProperties": false}}
Anthropic output_config = {"format": {"type": "json_schema",
"schema": {..., "required": [...], "additionalProperties": false}}}
So responses.parse turns your class into a strict JSON schema under text.format, and messages.parse sends it under output_config.format, as Anthropic's structured outputs page describes. OpenAI's version is covered in its structured outputs guide. Keep schemas flat and small at first. Every field needs a type, and optional fields need care, because strict mode wants every property listed in required.
A schema guarantees shape, not truth. The model can still return "product": "headphones" for earbuds. Check values that matter against the source text, and test on a few dozen labelled examples before you trust a batch run. If you want the model to call your own functions instead of returning JSON, that is tool calling, covered in function calling in LLMs, end to end.
Handle errors, retries and timeouts#
Remote APIs fail in a few predictable ways. Here is how each one shows up in Python:
| What went wrong | HTTP status | Exception (same name in both SDKs) | Retry? |
|---|---|---|---|
| Bad or missing key | 401 | AuthenticationError |
No, fix the key |
| Bad request (unknown param, invalid value) | 400 | BadRequestError |
No, fix the code |
| Too many requests | 429 | RateLimitError |
Yes, with backoff |
Out of credit (OpenAI: credit_balance_exhausted) |
429 | RateLimitError |
No, add credit |
| Provider overloaded (Anthropic only) | 529 | anthropic.OverloadedError |
Yes |
| Server error | 5xx | InternalServerError |
Yes |
| No answer in time | none | APITimeoutError |
Maybe |
DNS, network, wrong base_url |
none | APIConnectionError |
Yes, a few times |
Sources: OpenAI error codes and Anthropic errors. The OpenAI credit case is a trap: it is a 429 like a rate limit, but retrying will never help.
You do not need to write backoff loops. Both SDKs retry connection errors, 408, 409, 429 and 5xx responses on their own, with exponential backoff that starts at 0.5 seconds, caps at 8 seconds and respects the server's retry-after header. The defaults, read from the installed packages' _constants.py, are 2 retries and a 600-second timeout (5 seconds to connect). Ten minutes is far too long for a web request, so set your own values on the client:
import time
import openai
import anthropic
from openai import OpenAI
from anthropic import Anthropic
def ask_openai(client, model, prompt):
try:
return client.responses.create(model=model, input=prompt).output_text
except openai.APITimeoutError:
return "gave up: request timed out"
except openai.RateLimitError as e:
return f"gave up: still rate limited after retries ({e.status_code})"
except openai.APIConnectionError:
return "gave up: could not reach the API"
except openai.APIStatusError as e: # any other 4xx/5xx
return f"gave up: HTTP {e.status_code}"
def ask_anthropic(client, model, prompt):
try:
m = client.messages.create(model=model, max_tokens=200,
messages=[{"role": "user", "content": prompt}])
return m.content[0].text
except anthropic.APITimeoutError:
return "gave up: request timed out"
except anthropic.RateLimitError as e:
return f"gave up: still rate limited after retries ({e.status_code})"
except anthropic.APIConnectionError:
return "gave up: could not reach the API"
except anthropic.APIStatusError as e:
return f"gave up: HTTP {e.status_code}"
patient = OpenAI(max_retries=3, timeout=20.0)
t = time.perf_counter()
print("flaky, 3 retries :", ask_openai(patient, "flaky", "hi")[:40], f"({time.perf_counter() - t:.1f}s)")
impatient = Anthropic(max_retries=0, timeout=1.0)
print("slow, 1s timeout :", ask_anthropic(impatient, "slow", "hi"))
dead = OpenAI(base_url="http://127.0.0.1:9/v1", max_retries=1, timeout=2.0)
print("wrong host :", ask_openai(dead, "gpt-6-luna", "hi"))
The fake server treats the model name flaky as "return 429 with retry-after: 1 twice, then succeed", and slow as "wait 3 seconds". Output:
flaky, 3 retries : Recursion is a function that calls itsel (2.1s)
slow, 1s timeout : gave up: request timed out
wrong host : gave up: could not reach the API
The first line took 2.1 seconds: two waits of one second each, as the server asked, then a success. Your code never saw the 429s. The second line shows a 1-second timeout firing on a 3-second response. The third points the client at a port where nothing is listening.
Catch order matters. APITimeoutError is a subclass of APIConnectionError, and RateLimitError is a subclass of APIStatusError, so the specific ones go first. Two more habits pay off:
- Set
timeoutbased on output length. A 2,000-token answer from a large model can take well over 20 seconds, so stream long answers rather than raising the timeout to minutes. - Do not stack your own retry loop on top of the SDK's. Three of yours times three of the SDK's is nine calls per failure, and during an outage that turns into a bill and a pile-up.
Log tokens and cost on every call#
Every response carries a usage object. Log it from the first call. This version writes one JSON line per call; the LLM cost and latency tracker post turns logs like this into per-feature reports.
import json, time
from openai import OpenAI
from anthropic import Anthropic
# USD per 1M tokens, standard tier, copied from the official pricing pages on 2026-11-24.
PRICES = {
"gpt-6-luna": {"input": 0.10, "output": 0.50},
"claude-haiku-5-5": {"input": 0.10, "output": 0.50}, # prompts up to 100k tokens
}
def log_call(provider, model, input_tokens, output_tokens, seconds, path="llm_calls.jsonl"):
p = PRICES[model]
cost = (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
row = {"ts": round(time.time()), "provider": provider, "model": model,
"in": input_tokens, "out": output_tokens,
"usd": round(cost, 8), "latency_s": round(seconds, 2)}
with open(path, "a") as f:
f.write(json.dumps(row) + "\n")
return row
t = time.perf_counter()
r = OpenAI().responses.create(model="gpt-6-luna", input="Explain recursion in one sentence.")
print(log_call("openai", "gpt-6-luna", r.usage.input_tokens, r.usage.output_tokens, time.perf_counter() - t))
t = time.perf_counter()
m = Anthropic().messages.create(model="claude-haiku-5-5", max_tokens=200,
messages=[{"role": "user", "content": "Explain recursion in one sentence."}])
print(log_call("anthropic", "claude-haiku-5-5", m.usage.input_tokens, m.usage.output_tokens, time.perf_counter() - t))
Output (the token counts are numbers the fake server made up; the arithmetic is real):
{'ts': 1795488587, 'provider': 'openai', 'model': 'gpt-6-luna', 'in': 24, 'out': 19, 'usd': 1.19e-05, 'latency_s': 0.1}
{'ts': 1795488587, 'provider': 'anthropic', 'model': 'claude-haiku-5-5', 'in': 22, 'out': 21, 'usd': 1.27e-05, 'latency_s': 0.01}
The price lookup uses the model name you asked for, not r.model from the response. The model field the API sends back is not guaranteed to match your string exactly, and a mismatch would raise KeyError in the middle of a batch. Check the first row by hand: 24 × $0.10 / 1M + 19 × $0.50 / 1M = $0.0000024 + $0.0000095 = $0.0000119.
Now scale it. Say you classify 1,000 reviews, each prompt is about 300 tokens and each answer about 60:
| Model | Input cost | Output cost | Total for 1,000 reviews |
|---|---|---|---|
gpt-6-luna or claude-haiku-5-5 |
300,000 × $0.10/M = $0.03 | 60,000 × $0.50/M = $0.03 | $0.06 |
gpt-6.2-sol or claude-sonnet-5-5 |
300,000 × $2/M = $0.60 | 60,000 × $10/M = $0.60 | $1.20 |
The bigger model costs 20 times more for this job. Try the small one first and move up only if your test set shows it failing. Two caveats keep the estimate honest. Each provider has its own tokenizer, so the same review produces a different token count on each side (what tokens are explains why); Anthropic notes that its tokenizer since Claude Opus 4.7 produces roughly 30% more tokens for the same text. And output tokens cost five times input on all four models, so a prompt that says "answer in one word" saves more than trimming the prompt does.
The Anthropic usage object also has cache_read_input_tokens and cache_creation_input_tokens, and OpenAI's has input_tokens_details.cached_tokens. Once you add prompt caching, log those too, or your cost numbers will be wrong in the direction that looks good.
How this code was tested#
No real keys were available, so the scripts above never reached OpenAI or Anthropic.
- A local fake server. About 70 lines of standard-library
http.serverthat answersPOST /v1/responsesandPOST /v1/messages, both plain JSON and server-sent-event streams, in the wire format each SDK expects. Both SDKs read a base URL from the environment, so the scripts in this post ran unchanged:
bash
export OPENAI_API_KEY=fake OPENAI_BASE_URL=http://127.0.0.1:8765/v1
export ANTHROPIC_API_KEY=fake ANTHROPIC_BASE_URL=http://127.0.0.1:8765
python first_call.py
This exercises the real SDK code: request building, header handling, retries, timeouts, stream parsing and Pydantic validation. It does not test model quality, and the answer text and token counts are canned.
- Ollama, as a free option for you. Ollama exposes an OpenAI-compatible endpoint that includes
/v1/responses, and an Anthropic-compatible one at/v1/messages. Pointbase_urlathttp://localhost:11434/v1(OpenAI) orhttp://localhost:11434(Anthropic) with any string as the key, and the same code talks to a local model for free. An attempt to run these scripts against a local Ollama model for this post timed out because the shared GPU was busy, so this route is described from Ollama's docs and was not tested here. It is a good way to practise without a bill, but local models are smaller, and compatibility is partial (tool-choice controls, for example, are not fully supported on the Anthropic side).
The same trick gives you a test suite for your own code. Start the fake server in a pytest fixture, set the two base URL variables, and assert on what your code does with a 429, a timeout or a malformed answer. A demo never exercises those paths, and production exercises them every day.
Where to go next#
You now have a working client for both providers, a schema for clean JSON, sane timeouts and a cost log. The next steps are:
- letting the model call your own Python functions: function calling in LLMs
- putting this behind an HTTP service with rate limits and streaming: a production LLM API with FastAPI
- cutting the token bill once usage grows: prompting Claude with fewer tokens
Sources#
- OpenAI, Developer quickstart
- OpenAI, Responses API reference
- OpenAI, Streaming API responses
- OpenAI, Structured outputs
- OpenAI, Error codes
- OpenAI, Pricing and Models
- OpenAI, Best practices for API key safety
- OpenAI, openai-python on GitHub and PyPI
- Anthropic, Get started
- Anthropic, Messages API
- Anthropic, Streaming messages
- Anthropic, Structured outputs
- Anthropic, Errors
- Anthropic, Models overview and Pricing
- Anthropic, anthropic-sdk-python on GitHub and PyPI
- Ollama, OpenAI compatibility and Anthropic compatibility