03.1 The Provider APIs and Your First Calls
Every product you build in this path, whether a chatbot, a RAG system, an agent or a voice assistant, sits on top of one operation: your code sends a request to a model provider's API and reads back the answer. This lesson takes that operation apart. You'll see that an LLM API call is an ordinary HTTPS request carrying JSON, then learn everything around it that real projects need: accounts, keys and how to keep them secret, a project setup that works the first time, the API families each provider offers and which one to use, correct first calls on all four providers (OpenAI, Anthropic, Google Gemini and OpenRouter), client configuration, the anatomy of every response object, the three kinds of versioning, and a free local stand-in you can practise against without an API key. Every later lesson in this module builds on what you set up here.
What you'll learn
- What an LLM API call is at the HTTP level, with the real endpoints, auth headers and JSON bodies of every API family, and the exact request each SDK sends
- What is different about LLM APIs compared with the REST APIs you may already know
- How to get access to each provider: accounts, billing, free options, organizations, projects and workspaces, scoped keys, spend limits
- How to handle API keys safely:
.envfiles,.gitignore, one key per environment, never in a browser, rotation, and the first hour after a leak - A
uvproject setup that works first time, which SDK versions the module was checked against, and thehttpx2change that broke many older examples - The API families (OpenAI Responses and Chat Completions, Anthropic Messages, Gemini
generate_contentand Interactions, OpenRouter's three endpoints) and which one to choose - Your first call on six API surfaces, first minimal and then production-minded (timeouts, output caps, finish-reason checks, usage and request-ID logging)
- How to configure clients (constructor arguments, environment variables, per-request options) and manage their lifecycle
- The anatomy of each provider's response object, convenience accessors and their traps, raw responses and headers, and request IDs
- The three kinds of versioning (API, model and SDK) and why people confuse them
- The Models APIs as calls, and how cloud platforms (Azure, Bedrock, Google Cloud) change the client
- How to practise every call for free against a small local model, and how to fix the first errors you'll hit
What you don't need
- Any API key. Every part has something you can run for free: wire captures, local-model calls and live calls to a public endpoint. Samples that need a key are clearly marked, and the OpenAI and Anthropic ones mostly run unchanged against the local stand-in in Part 12 (12.5 lists the exceptions; every Gemini sample is hosted-only, see 12.4).
- Previous experience with HTTP APIs. Part 1 explains requests, headers and JSON from zero.
- Knowledge of how models work inside. Module 02 covered that, and this lesson links back to it wherever it matters.
Setup
This lesson owns the setup steps for the whole of Module 03, so Part 4 walks through them in full. The project folder is called llm-apis, and lessons 03.1 to 03.9 all use it; 03.10 and 03.11 build packages of their own and start a new folder each. The short version, for Python 3.11+ (google-genai requires it):
uv init llm-apis --bare --python 3.13 # --python matters: see the box below
cd llm-apis
git init
uv add openai anthropic google-genai python-dotenv httpx
# or, without uv: pip install openai anthropic google-genai python-dotenv httpxThese commands name the packages without versions, so you get the newest release of each. The samples in this module were written and checked against openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0 as of November 2026. A newer major version may change names or defaults, and google-genai 3.x already does (a different default HTTP library and Gemini API version): 4.5 says what to expect and what to do, and the SDK's changelog is the place to look if a sample does not match. httpx is in the command because several samples import it and google-genai 3.x no longer installs it.
Put your keys in a .env file (never commit it, see 3.4):
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...No keys? Install Ollama, run ollama pull qwen2.5:0.5b, and follow Part 12. Once you've done the aliases in 12.3, the calls in Parts 1, 6, 7 and 8 run for real on your laptop at no cost (the OpenAI and Anthropic ones; Gemini has no local stand-in, see 12.4). Three things need a real account: every Gemini sample (google-genai and the Interactions API), the Gemini model list in 10.1, and the cloud-platform clients in Part 11.
The samples in Module 03 were written and checked against openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0, the latest releases on PyPI when the module was written (November 2026), and against tenacity 9.1.4 in 03.8. The install commands name the packages without versions, so you get the newest release of each. That matters most for google-genai: version 3.0.0 followed on 6 November 2026 with two breaking changes, a different default HTTP library and a different default Gemini API version, so a plain install now gives you 3.x. The dated note in 4.5 says what changes and what to do. The three SDKs (and tenacity) are the packages that matter most, because the lessons depend on their types and behaviour. Other packages are mentioned in a lesson's Setup with a version only where its output depends on it (for example pydantic 2.14 and fastapi); each lesson's Setup block is the authoritative list for that lesson, and a newer major version of any package may change a name or a default, so check its changelog if something does not match. The default models are gpt-6-luna, claude-haiku-5-5 and gemini-3.8-flash, plus their OpenRouter equivalents (lesson 02.9, Part 2).
What you must be able to do after this lesson#
- Make a first API call on at least one provider
- Explain why an LLM call is an HTTP request
- Store keys safely and set up a project that runs first time
- Choose between the API families
- Read the parts of a response
- Diagnose common first-call errors
Why this matters for an AI engineer#
The first call is easy to copy from a quickstart. The details around it are what separate a demo from a feature you can run in production, and they're what this lesson is about:
| You'll hear... | You'll understand it after... |
|---|---|
| "It's just a POST request, why do we need the SDK?" | 1.5 What SDKs add |
| "The call returned 200, but the answer is cut off." | Part 2: What is different about LLM APIs |
| "My very first call returns a 429 and I haven't done anything wrong." | 3.1b Your first key, step by step and 13.1 |
| "Someone pushed our OpenAI key to GitHub." | 3.7 When a key leaks: the first hour |
| "Can't we just call the API from the React app?" | 3.5 Never ship a key to a browser or mobile app |
"The old blog post's httpx timeout example doesn't work any more." |
4.5 The httpx2 switch |
| "Should we use Responses or Chat Completions?" | 5.1 OpenAI: Responses and Chat Completions |
"Google says generateContent is legacy now. Do we have to migrate?" |
5.3 Gemini: generate_content and Interactions |
| "This server is OpenAI-compatible, so everything will just work." | 5.5 OpenAI-compatible endpoints |
| "Our Gemini timeout is set to 30 and requests fail instantly." | 7.1 Constructor parameters |
"It's using the wrong Gemini key, but GEMINI_API_KEY is right!" |
7.2 Environment variables and precedence |
| "We create a new client for every request. Is that a problem?" | 7.5 Client lifecycle |
"output_text is empty, but we were billed." |
8.4 Convenience accessors and their traps |
| "Support wants the request ID." | 8.6 Request IDs: log them every time |
| "Pin the API version, the model version and the SDK version." | Part 9: Versioning |
"temperature gives a 400 on Claude now." |
9.1 API versions |
| "We're on AWS, so we call Claude through Bedrock." | Part 11: Cloud-platform clients |
| "I want to practise without paying for tokens." | Part 12: Practise for free |
Part 1: An LLM call is an HTTP request#
1.1 What actually happens#
When your Python code "calls GPT" or "asks Claude", nothing magical happens. Your program sends a message over the internet to a computer run by the provider, and that computer sends a message back. The format of those messages is HTTP (HyperText Transfer Protocol), the same protocol your browser uses to load web pages, and the content is JSON text.
So every LLM API call is:
- An HTTPS
POSTto an endpoint such as/v1/responses, - with an auth header carrying your API key,
- and a JSON body naming the model and your input,
- returning a JSON body with the model's output, the reason it stopped and the tokens you'll pay for, or, if you asked for it, a stream of small events as the text is generated (server-sent events, SSE, the subject of 03.3).
An API key is a long secret string that identifies your account (and usually one project inside it) and authorizes the provider to bill you. Whoever holds it can spend your money, which is why Part 3 spends so long on keeping it secret.
An SDK (software development kit) is a library, here openai, anthropic or google-genai, that builds these requests for you and turns the JSON replies into Python objects. Here's the whole round trip, through an SDK:
sequenceDiagram
participant App as Your Python code
participant SDK as SDK client
participant API as Provider API (HTTPS)
participant Model as Model servers
App->>SDK: client.responses.create(model, input, ...)
SDK->>SDK: build JSON body, add auth and version headers
SDK->>API: POST /v1/responses (JSON body, Authorization header)
API->>API: check key, project, rate limits, request shape
API->>Model: queue the request
Model-->>Model: read the input, generate tokens (seconds to minutes)
Model-->>API: output tokens plus usage counts
API-->>SDK: 200 OK, JSON body, request-id header
SDK-->>App: typed Response object (output, status, usage)
Note over App,API: On 408, 409, 429 or 5xx the openai and anthropic SDKs wait and retry (2 retries by default)Two things in that picture are worth fixing in your mind now. First, the provider checks your key, your project's rate limits (how many requests and tokens you may send per minute) and the shape of your request before any model runs, so many errors come back in milliseconds. Second, the model part can take seconds to minutes, so an LLM call is far slower than a typical web API call (Part 2).
1.2 The endpoints and auth headers of every API family#
Each provider has one or more API families: distinct request and response formats, each with its own endpoint. These are the ones this module uses, as of November 2026:
| Provider | API family | Method and endpoint | Auth header | Other required headers |
|---|---|---|---|---|
| OpenAI | Responses | POST https://api.openai.com/v1/responses |
Authorization: Bearer <key> |
— (optional OpenAI-Organization, OpenAI-Project, 3.2) |
| OpenAI | Chat Completions | POST https://api.openai.com/v1/chat/completions |
Authorization: Bearer <key> |
— |
| Anthropic | Messages | POST https://api.anthropic.com/v1/messages |
Authorization: Bearer <key> (what SDK 2.x sends), or the legacy x-api-key: <key> (still accepted for raw HTTP) |
anthropic-version: 2026-10-21 (9.1) |
| Gemini | generateContent | POST https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent |
x-goog-api-key: <key> |
— |
| Gemini | Interactions | POST https://generativelanguage.googleapis.com/v1beta/interactions (also /v1/interactions) |
x-goog-api-key: <key> |
— |
| OpenRouter | Chat Completions | POST https://openrouter.ai/api/v1/chat/completions |
Authorization: Bearer <key> |
— (optional attribution headers, 6.6) |
| OpenRouter | Responses | POST https://openrouter.ai/api/v1/responses |
Authorization: Bearer <key> |
— |
| OpenRouter | Anthropic Messages | POST https://openrouter.ai/api/v1/messages |
Authorization: Bearer <key> |
— |
Notice the pattern. The URL encodes the provider and API family. Gemini's generateContent is the odd one out: the model name sits in the URL path, and the action follows a colon (models/gemini-3.8-flash:generateContent), which is Google's style for its APIs. Every other API family puts "model" in the JSON body. Interactions also has GET, DELETE and POST .../{id}/cancel endpoints on /v1beta/interactions/{id} for the stored interactions it creates (03.2).
The same call as one curl command per provider (illustrative: each needs a key)
Each command sends the body that the SDK in 1.3 sends, and each reads its key from an environment variable. They're the fastest way to prove to yourself, or to a colleague from a PHP or Java team, that a key and a network path work, before any Python is involved. In PowerShell, write curl.exe (plain curl is an alias for a different command) or use the Python in 1.5.
# OpenAI Responses
curl https://api.openai.com/v1/responses \
-H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "gpt-6-luna", "input": "In one sentence, what is an API?", "max_output_tokens": 200}'
# Anthropic Messages (anthropic-version is required; Bearer is what SDK 2.x sends, x-api-key is the legacy form)
curl https://api.anthropic.com/v1/messages \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" -H "anthropic-version: 2026-10-21" -H "Content-Type: application/json" \
-d '{"model": "claude-haiku-5-5", "max_tokens": 200, "messages": [{"role": "user", "content": "In one sentence, what is an API?"}]}'
# Gemini generateContent (the model is in the URL, the key in x-goog-api-key)
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" -H "Content-Type: application/json" \
-d '{"contents": [{"parts": [{"text": "In one sentence, what is an API?"}]}], "generationConfig": {"maxOutputTokens": 200}}'
# Gemini Interactions
curl https://generativelanguage.googleapis.com/v1beta/interactions \
-H "x-goog-api-key: $GEMINI_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "gemini-3.8-flash", "input": "In one sentence, what is an API?"}'
# OpenRouter Chat Completions (the attribution headers are optional)
curl https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "anthropic/claude-haiku-5.5", "messages": [{"role": "user", "content": "In one sentence, what is an API?"}], "max_tokens": 200}'Anthropic's own documentation leads with this style of curl example. Each of the OpenAI, Anthropic and OpenRouter bodies above was also sent to Ollama, the local stand-in of Part 12, with only the URL changed, and every one was accepted. The two Gemini bodies have no local stand-in (12.4); they are illustrative and need a Gemini key.
1.3 Try it: see the wire#
This is the "it's just HTTP" moment. The script below makes the same one-line request through all four SDKs, but plugs in a mock transport: a fake network layer that hands each request to a Python function instead of sending it. The function prints the request and returns an empty canned reply. Nothing leaves your machine, and the keys are obvious fakes.
"""See the exact HTTP request each SDK builds, without sending anything (a mock transport)."""
import json
import anthropic
import httpx # google-genai 2.34.0's default HTTP library (3.x changes this: see 4.5)
import httpx2 # openai 3.x and anthropic 2.x use httpx2, Pydantic's fork of httpx
from google import genai
from google.genai import types
from openai import OpenAI
QUESTION = "In one sentence, what is an API?"
# An ALLOW-list: only these headers are printed as they are. Any header not on it (a key, a token, a cookie,
# one you've never heard of) prints as <redacted>. A deny-list fails open: a credential header it forgot gets printed.
# Lesson 03.10, 2.3 builds the same rule into a real logger.
SAFE = {"accept", "anthropic-version", "content-type", "http-referer", "user-agent", "x-openrouter-title",
"x-stainless-read-timeout", "x-stainless-retry-count", "x-stainless-timeout"}
# Headers every HTTP client sends, plus SDK telemetry (OS, CPU, Python version): hidden for brevity
BORING = {"accept-encoding", "connection", "content-length", "host", "x-stainless-arch",
"x-stainless-async", "x-stainless-lang", "x-stainless-os", "x-stainless-package-version",
"x-stainless-runtime", "x-stainless-runtime-version", "x-goog-api-client"}
def show(request: httpx.Request | httpx2.Request) -> None:
"""Print the method, URL, safe headers (everything else redacted) and JSON body."""
print(f"{request.method} {request.url}")
for name, value in sorted(request.headers.items()):
if name in BORING:
continue
if name not in SAFE: # fail closed: never print a value we haven't vouched for, not even part of a key
value = "Bearer <redacted>" if value.startswith("Bearer ") else "<redacted>"
print(f" {name}: {value}")
print(" body:", json.dumps(json.loads(request.content)), "\n")
def httpx2_mock(reply: dict) -> httpx2.Client:
"""An httpx2 client whose 'server' prints the request and returns `reply`."""
def handler(request: httpx2.Request) -> httpx2.Response:
show(request)
return httpx2.Response(200, json=reply)
return httpx2.Client(transport=httpx2.MockTransport(handler))
def httpx_mock(reply: dict) -> httpx.Client:
"""The same for google-genai, whose default HTTP client is plain httpx."""
def handler(request: httpx.Request) -> httpx.Response:
show(request)
return httpx.Response(200, json=reply)
return httpx.Client(transport=httpx.MockTransport(handler))
# --- OpenAI: Responses API, then Chat Completions ---------------------------------------
openai_client = OpenAI(api_key="sk-test", http_client=httpx2_mock({"output": []})) # fake key
print("=== OpenAI Responses ===")
openai_client.responses.create(model="gpt-6-luna", input=QUESTION, max_output_tokens=200)
print("=== OpenAI Chat Completions ===")
openai_client.chat.completions.create(
model="gpt-6-luna", messages=[{"role": "user", "content": QUESTION}], max_completion_tokens=200
)
# --- Anthropic: Messages API ------------------------------------------------------------
claude = anthropic.Anthropic(api_key="sk-ant-test", http_client=httpx2_mock({"content": []}))
print("=== Anthropic Messages ===")
claude.messages.create(
model="claude-haiku-5-5", max_tokens=200, messages=[{"role": "user", "content": QUESTION}]
)
# --- Gemini: generateContent, then the Interactions API ---------------------------------
gemini = genai.Client(
api_key="gemini-test",
http_options=types.HttpOptions(httpx_client=httpx_mock({"candidates": []})),
)
print("=== Gemini generateContent ===")
gemini.models.generate_content(
model="gemini-3.8-flash", contents=QUESTION,
config=types.GenerateContentConfig(max_output_tokens=200),
)
print("=== Gemini Interactions ===")
gemini.interactions.create(
model="gemini-3.8-flash", input=QUESTION, generation_config={"max_output_tokens": 200}
)
# --- OpenRouter: the openai SDK with a different base URL -------------------------------
router = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key="sk-or-test",
default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "My App"},
http_client=httpx2_mock({"choices": []}),
)
print("=== OpenRouter Chat Completions ===")
router.chat.completions.create(
model="anthropic/claude-haiku-5.5", messages=[{"role": "user", "content": QUESTION}], max_tokens=200
)=== OpenAI Responses ===
POST https://api.openai.com/v1/responses
accept: application/json
authorization: Bearer <redacted>
content-type: application/json
user-agent: OpenAI/Python 3.42.1
x-stainless-read-timeout: 600
x-stainless-retry-count: 0
body: {"model": "gpt-6-luna", "input": "In one sentence, what is an API?", "max_output_tokens": 200}
=== OpenAI Chat Completions ===
POST https://api.openai.com/v1/chat/completions
accept: application/json
authorization: Bearer <redacted>
content-type: application/json
user-agent: OpenAI/Python 3.42.1
x-stainless-read-timeout: 600
x-stainless-retry-count: 0
body: {"model": "gpt-6-luna", "messages": [{"role": "user", "content": "In one sentence, what is an API?"}], "max_completion_tokens": 200}
=== Anthropic Messages ===
POST https://api.anthropic.com/v1/messages
accept: application/json
anthropic-version: 2026-10-21
authorization: Bearer <redacted>
content-type: application/json
user-agent: Anthropic/Python 2.4.0
x-stainless-read-timeout: 600
x-stainless-retry-count: 0
x-stainless-timeout: 600
body: {"max_tokens": 200, "messages": [{"role": "user", "content": "In one sentence, what is an API?"}], "model": "claude-haiku-5-5"}
=== Gemini generateContent ===
POST https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent
accept: */*
content-type: application/json
user-agent: google-genai-sdk/2.34.0 gl-python/3.13.14
x-goog-api-key: <redacted>
body: {"contents": [{"parts": [{"text": "In one sentence, what is an API?"}], "role": "user"}], "generationConfig": {"maxOutputTokens": 200}}
=== Gemini Interactions ===
POST https://generativelanguage.googleapis.com/v1beta/interactions
accept: application/json
content-type: application/json
user-agent: google-genai-sdk/2.34.0 gl-python/3.13.14
x-goog-api-key: <redacted>
body: {"model": "gemini-3.8-flash", "generation_config": {"max_output_tokens": 200}, "input": "In one sentence, what is an API?"}
=== OpenRouter Chat Completions ===
POST https://openrouter.ai/api/v1/chat/completions
accept: application/json
authorization: Bearer <redacted>
content-type: application/json
http-referer: https://example.com
user-agent: OpenAI/Python 3.42.1
x-openrouter-title: My App
x-stainless-read-timeout: 600
x-stainless-retry-count: 0
body: {"model": "anthropic/claude-haiku-5.5", "messages": [{"role": "user", "content": "In one sentence, what is an API?"}], "max_tokens": 200} Read the output slowly, because it answers a dozen questions people ask about these SDKs:
- The SDK sends exactly what you passed, and nothing more. No hidden system prompt, no default
temperature. Parameters you don't set are left out, and the server applies its own defaults. - The same idea has different names. The output cap is
max_output_tokens(Responses),max_completion_tokens(Chat Completions),max_tokens(Anthropic and OpenRouter),maxOutputTokens(generateContent, in camelCase on the wire even though you wrotemax_output_tokensin Python) andgeneration_config.max_output_tokens(Interactions, snake_case on the wire). 03.2 has the full parameter-mapping table. - The input has different shapes. A plain string (
inputin Responses and Interactions), a list of role-tagged messages (Chat Completions, Anthropic), orcontentsmade ofparts(generateContent, where the SDK wrapped your string for you). - OpenRouter is the OpenAI wire format at a different address, plus its own optional headers.
- The script's header filter is an allow-list. It prints only the headers listed in
SAFE, and shows<redacted>for every other one, so a credential header it has never heard of can't leak. A deny-list (a set of header names to hide) fails the other way: it prints whatever it forgot. Lesson 03.10, 2.3 builds the same rule into a real logger. - Telemetry headers.
openaiandanthropicare generated by a company called Stainless, hence thex-stainless-*headers.x-stainless-retry-counttells the server which attempt this is (03.8), andx-stainless-read-timeout: 600shows the default 10-minute timeout (7.4).google-genaisends anx-goog-api-clientheader instead, hidden here. - The Anthropic SDK adds
anthropic-versionfor you. It's fixed by the SDK's major version (9.1).
1.4 Try it: a call with no SDK#
To prove there's nothing more to it, here's a real call with no SDK at all, using the httpx library directly. It goes to the free local model from Part 12 (Ollama serves the Chat Completions format on localhost:11434), so it runs for free once Ollama is installed:
"""An LLM call with no SDK at all: one HTTPS (here HTTP) POST of a JSON body."""
import json
import httpx
response = httpx.post(
"http://localhost:11434/v1/chat/completions", # Ollama's OpenAI-compatible endpoint
headers={"Authorization": "Bearer ollama"}, # Ollama ignores the key, but expects the shape
json={
"model": "qwen2.5:0.5b",
"messages": [{"role": "user", "content": "In one sentence, what is an API?"}],
"max_tokens": 60,
},
timeout=60.0,
)
print("HTTP status:", response.status_code)
print("Content-Type:", response.headers["content-type"])
print(json.dumps(response.json(), indent=2))HTTP status: 200
Content-Type: application/json
{
"id": "chatcmpl-695",
"object": "chat.completion",
"created": 1793758361,
"model": "qwen2.5:0.5b",
"system_fingerprint": "fp_ollama",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "An API stands for Application Programming Interface, which refers to the standard mechanism used in software development and communication between different systems or services on a web application or cloud platform."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 38,
"completion_tokens": 34,
"total_tokens": 72
}
}That JSON is the whole answer: an id, the model, a list of choices (each with a message and a finish_reason saying why it stopped), and usage, the token counts you'd be billed for on a hosted provider. A 0.5-billion-parameter local model writes clumsier sentences than a hosted frontier model, but the shape is identical. Part 8 maps every field of every provider's response.
1.5 The same call to a hosted provider, and what SDKs add#
Here's the same idea against OpenAI's Responses API with plain httpx. It needs a key, so its output is illustrative:
"""The same call to a hosted provider with plain httpx: everything the SDK would do, by hand."""
import os
import httpx
from dotenv import load_dotenv
load_dotenv() # reads OPENAI_API_KEY from .env
BASE_URL = os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1") # the SDK's own default
response = httpx.post(
f"{BASE_URL}/responses",
headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"},
json={"model": "gpt-6-luna", "input": "In one sentence, what is an API?", "max_output_tokens": 200},
timeout=httpx.Timeout(60.0, connect=5.0), # httpx's default is only 5 seconds: far too short
)
if response.status_code != 200:
# Errors are JSON too; the request ID is what support will ask for
print("error", response.status_code, response.headers.get("x-request-id"), response.text[:300])
raise SystemExit(1)
data = response.json()
# No .output_text convenience here: walk the output items yourself
text = "".join(
part["text"]
for item in data["output"] if item["type"] == "message"
for part in item["content"] if part["type"] == "output_text"
)
print("status: ", data["status"])
print("text: ", text)
print("usage: ", data["usage"]["input_tokens"], "in /", data["usage"]["output_tokens"], "out")
print("request id:", response.headers.get("x-request-id"))status: completed
text: An API is a defined set of rules that lets one piece of software request data or actions from another.
usage: 14 in / 24 out
request id: req_7b1e0c9f4a2d4e6b8c3a5f1d2e9b7a60This works, and for a one-off script it's fine. But look at what you had to write by hand, and what you still haven't handled. An official SDK gives you:
| What the SDK adds | Without it, you write... |
|---|---|
Typed request parameters (your editor and type checker catch max_tokens vs max_output_tokens) |
Dictionary keys that fail only at run time, with a 400 |
Typed response objects and helpers such as output_text |
Loops over nested JSON, like the one above |
Automatic retries with exponential backoff on 408, 409, 429 and 5xx, honouring retry-after |
Your own retry loop (03.8) |
| Sensible timeouts (10 minutes, with a 5-second connect timeout) and a connection pool | Remembering that httpx defaults to 5 seconds |
Typed exceptions (RateLimitError, AuthenticationError...) carrying the status, body and request ID |
Parsing error JSON and status codes yourself |
| Streaming helpers that parse server-sent events and assemble the final message (03.3) | An SSE parser |
| Auth and version headers, environment-variable defaults, pagination, file uploads, structured-output parsing | All of it |
Use the official SDKs in this path, and drop to raw HTTP only when you need to see or control the wire exactly. Knowing what happens underneath is what lets you debug the SDK when it surprises you.
Part 2: What is different about LLM APIs#
Deep-dive
If you've built against payment, maps or CRM APIs, most of the mechanics will feel familiar. But LLM APIs break several assumptions that hold for typical REST APIs, and each one causes real production bugs:
| Typical REST API | LLM API | What it means for you |
|---|---|---|
| Responds in milliseconds | Responds in seconds to minutes. Long outputs and reasoning models can take many minutes, which is why the openai and anthropic SDKs default to a 10-minute timeout |
Set an explicit timeout per use case (7.4). Stream anything a user waits for (03.3). Never call an LLM inside a database transaction or a request handler with a short gateway timeout |
| Billed per request, or a flat fee | Billed per token, input and output, including tokens the user never sees: hidden reasoning (02.8, 5.1), tool definitions, system prompts, re-sent conversation history | Always cap output (max_output_tokens and friends) and log usage on every call (02.2, 6.6; 03.7 builds a cost tracker) |
| The same request gives the same response | Non-deterministic: the same input can give different text each time (02.5, Part 7) | Test code paths with mocks or the stand-in, not by comparing exact text (03.10); evaluate quality statistically (Module 10A) |
| Failures are 4xx/5xx errors | Many meaningful "failures" arrive as HTTP 200: output truncated at the token cap, a refusal, a safety block, a tool call instead of text, an empty answer | Check the status or finish reason on every response (02.5, 4.5); 6.7 shows how, and 03.8 treats them as error handling |
| Rate limits count requests | Rate limits count tokens as well as requests (input and output tokens per minute), per organization or project, not per key (02.7, 6.4) | One large prompt can exhaust a limit that a hundred small ones wouldn't. Expect 429s and let the SDK retry (03.8) |
| One response body | Often streamed as a sequence of events while the text is generated | Streaming changes how you parse, time out, count usage and handle errors (03.3) |
Versions change slowly; /v2 arrives every few years |
Fast-moving: new API families, API versions, beta headers, monthly SDK releases with occasional breaking majors, and models retired within a year or two | Lock SDK versions, read changelogs, and keep model IDs in configuration (Part 9) |
| Output is data | Output is generated text that can be wrong, badly formatted or unsafe (Module 02, 02.10) | Validate output in code (03.4) and never trust it blindly |
| The request is small | The request often carries large, sensitive data: whole documents and users' messages | Mind data retention and privacy settings (02.9, Part 9) and send only what's needed |
Part 3: Accounts, keys and secrets#
3.1 Getting access to each provider#
You need one account per provider (or a single OpenRouter account for all of them). Every provider bills per token, and each has some way to try it cheaply. As of November 2026:
| OpenAI | Anthropic | Google Gemini (optional) | OpenRouter (optional) | |
|---|---|---|---|---|
| Where | platform.openai.com | platform.claude.com (the Claude Console) | aistudio.google.com (Google AI Studio) | openrouter.ai |
| How you pay | Prepaid credits. Usage tiers rise with total purchases: the paid tiers are Build ($5 of purchases), Launch and Grow | Prepaid credits; usage tiers Start, Build, Scale and Custom | Link a Google Cloud billing account (Tier 1); higher tiers follow payment history | Prepaid credits, with a platform fee on purchases (02.9, 5.4) |
| Free or nearly free options | OpenAI's rate-limit guide lists a Free usage tier (qualification: "User must be in an allowed geography", with a $100 monthly usage limit). It isn't one of the paid tiers, but the guide doesn't say which models it includes, so check your organization's Limits page | New organizations "may start in the Evaluation tier, with limits below the standard limits" while account history is established, and Anthropic's pricing FAQ says "New users receive a small amount of free credits to test the API" | A free tier on the Flash and Flash-Lite models (including gemini-3.8-flash and gemini-3.5-flash-lite, but not gemini-4-argon). Free-tier content may be used to improve Google's products and read by human reviewers, so never send real user data through it |
:free model variants (append :free to a model ID that has a free entry), with low per-minute and per-day request limits |
| Where to check your tier and limits | Settings → Organization → Limits | Console → Limits (rate-limit tiers, 03.8) | AI Studio → Projects, and the rate-limit page | GET /api/v1/key shows the key's limits and free-model usage |
Prices, free-tier limits and their data terms are covered in 02.9, Part 6 and 6.11. Rate-limit tiers and their numbers belong to 03.8.
3.1b Your first key, step by step#
Do this once per provider you want to use. Console layouts change, so treat the button names below as signposts (checked against each provider's documentation in November 2026) and follow the provider's current pages if they differ.
| OpenAI | Anthropic | Google Gemini (optional) | OpenRouter (optional) | |
|---|---|---|---|---|
| 1. Sign up | Create an account at platform.openai.com | Sign in or sign up at platform.claude.com | Sign in to aistudio.google.com with a Google account and accept the terms; you get a default Google Cloud project and key | Sign up at openrouter.ai |
| 2. Money | Add prepaid credit under billing (the quickstart's "Add credits to keep building" button leads there). OpenAI's rate-limit guide also lists a Free usage tier, but its model coverage isn't spelled out (3.1) | Buy prepaid credit under billing. Without it, or on the Evaluation tier, you can hit limits at once (3.1) | Nothing for the free tier. To go beyond it, link a Cloud billing account to the project | Add credits; :free model variants need none |
| 3. Create the key | Settings → Organization → API keys, then create a new secret key. Name it, pick the project, and set an expiry date if offered | Settings → API keys → Create key. Name it, choose an expiration (3 hours, 1 day, 7 days, 30 days, a custom duration or Never) and the Linked account (yourself for a personal key), and optionally one workspace | AI Studio dashboard → API Keys → Create API key. New keys are auth keys (3.2) | openrouter.ai/keys: name the key and set a credit limit (or none). Set one: OpenRouter's own docs recommend a limit on every key |
| 4. Copy it once | Copy it straight into .env |
Copy it straight into .env: "The Console shows the full key ... only once, at creation" |
Copy it straight into .env |
Copy it straight into .env |
Two details that cost beginners an afternoon:
- Copy the key the moment it appears. Anthropic's documentation states that the Console shows the full key only once and that a lost key can't be viewed again, so you create a new one. Assume the same everywhere (only Anthropic's pages state it, but treating every key this way costs nothing). Paste it into
.env(3.4), never into a chat window or a note. - Choose the expiry when you create the key. On Anthropic, "expiration is set at creation time and cannot be changed afterward", and an expired key then returns
401 authentication_error. A 30-day or 7-day key is a good default for practice. A key with no expiry belongs in a secret manager with a rotation routine (3.6).
What your first call costs. The samples in this lesson send about 15 tokens and get back about 30, a tiny fraction of a cent at any price in 02.9, Part 6, which is why a few dollars of credit covers a whole course of experiments. The expensive mistakes are loops with no output cap and leaked keys, which is why 3.3 comes before any code.
If your very first call fails with a 429, a 400 or a 402 rather than an answer, the cause is usually credit, billing or a free-tier quota rather than your code. See the first row of the troubleshooting table in 13.1.
3.2 Organizations, projects, workspaces and scoped keys#
Every provider groups usage into containers, and a key belongs to one of them. Getting this right decides who can spend what, which limits apply, and how much damage a leaked key can do.
| OpenAI | Anthropic | Google Gemini (optional) | OpenRouter (optional) | |
|---|---|---|---|---|
| Top level | Organization | Organization | Google Cloud project (every key belongs to one) | Account, with optional workspaces |
| Sub-containers | Projects, each with its own keys, members, rate limits and spend limits | Workspaces (wrkspc_... IDs; up to 100 per organization by default; the Default Workspace can't be renamed, archived or deleted). Files, batches and prompt caches are scoped per workspace |
One project per environment is the norm; rate limits apply "per project, not per API key" | Workspaces with guardrails (spend, model, provider and data-policy limits) |
| Key types | Project API keys (set an expiration date), service accounts for applications, and legacy user keys | Personal keys, service-account keys, and workspace keys ("should be considered legacy"); Admin keys (sk-ant-admin...) for the Admin API only |
Since 28 May 2026, new AI Studio keys are auth keys "bound directly to a Google Cloud service account". The API "rejects requests from unrestricted standard keys"; standard keys with explicit restrictions still work | Per-key credit limits (optionally reset daily, weekly or monthly); management API keys create and manage keys programmatically but "cannot be used to make API calls to OpenRouter's completion endpoints" |
| Selecting a container per request | OpenAI-Organization and OpenAI-Project headers, needed only if you belong to several organizations or use a legacy user key (SDK: organization= / project=, or OPENAI_ORG_ID / OPENAI_PROJECT_ID) |
anthropic-workspace-id header, required when the key isn't scoped to a single workspace (400 otherwise) |
The key's project | The key's workspace |
| Keyless auth for production | Workload identity federation: exchange your cloud's identity token for a short-lived OpenAI token (SDK: workload_identity=) |
Workload Identity Federation: short-lived OIDC (OpenID Connect, a standard identity-token format) tokens "instead of long-lived sk-ant-... API keys" (SDK: credentials=, profiles, or environment variables) |
Service-account credentials through Google Cloud (on Agent Platform, Part 11) | — (keys only) |
What this means for you as an engineer:
- Create one project or workspace per application and environment (for example
support-bot-dev,support-bot-prod). Each gets its own keys, limits, spend caps and usage reports, so a runaway test can't eat production's rate limit or budget. - Applications should use service-account keys, not a developer's personal key. When the developer leaves, the app keeps working.
- Give keys the narrowest scope that works. A key scoped to one project or workspace limits the blast radius of a leak.
- Prefer short-lived credentials in production where your platform supports them: no long-lived secret to leak at all (3.8).
3.3 Spend limits and alerts#
A bug in a loop, or a leaked key, can spend thousands of dollars overnight. Set limits on day one. As of November 2026:
| Provider | What you can set | What happens when a limit is hit |
|---|---|---|
| OpenAI | Monthly spend limits (hard) and spend alerts (notification only) for the organization and for each project, in USD | A hard limit makes requests fail with 429 and code organization_spend_limit_exceeded or project_spend_limit_exceeded. Alerts "do not enforce a cap" |
| Anthropic | Workspace spend limits with alerts at thresholds (not on the Default Workspace); your usage tier also has a monthly spend cap | A limit you set returns 400 invalid_request_error ("You have reached your specified API usage limits"). The tier cap returns 429 with enforced_spend_limit_reached and no retry-after, until the start of the next month (UTC) |
| Google Gemini | Project-level spend caps in AI Studio, on top of the billing account's tier cap | Requests are refused once the cap is reached; billing data lags, so Google warns that small overages are possible |
| OpenRouter | A credit limit per key (with optional reset), workspace budgets and guardrails, and your prepaid balance itself | 402 when credits run out; 403 with a budget reason when a key or guardrail limit is hit (03.8) |
3.4 Keys in a project: .env, python-dotenv and .gitignore#
Never put a key in your source code, not even "just for a test". Code gets committed, pushed, pasted into chats and shared. The standard pattern for development is an environment variable loaded from a .env file that git ignores.
1. Create .env in your project folder, with one key per line, no quotes and no spaces around =:
# .env: real secrets. NEVER commit this file.
OPENAI_API_KEY=sk-proj-...
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=sk-or-...2. Commit a template instead, .env.example, with the names but no values, so teammates know what to set:
# .env.example: copy to .env and fill in. Safe to commit.
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
GEMINI_API_KEY=
OPENROUTER_API_KEY=3. Ignore .env in git. A pattern like .env* is a good default, because it also catches .env.local, .env.production and the like. But it catches .env.example too, so negate that one explicitly:
# .gitignore
.env*
!.env.example
.venv/You can check what git will ignore with git check-ignore -v:
git check-ignore -v .env .env.production .env.example.gitignore:1:.env* .env
.gitignore:1:.env* .env.production
.gitignore:2:!.env.example .env.exampleThe third line means the negation rule matched, so .env.example is not ignored and will be committed. git status confirms it: .env.example shows up as a new file, and .env doesn't. (The output above is from a .gitignore that starts with these lines; if yours already has other lines above them, as most Python templates do, the line numbers after .gitignore: will differ.) Both commands need a git repository: if they say "not a git repository", run git init in the project folder first.
4. Load it with python-dotenv at the start of your program:
from dotenv import load_dotenv
load_dotenv() # copies the variables from .env into os.environEvery SDK then finds its key in the environment by itself (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY). Two behaviours of load_dotenv() trip people up:
- It doesn't override variables that are already set. The
python-dotenvREADME: "Not override existing environment variables (override=False)". If you exported an old key in your shell months ago, the shell's value wins over your fresh.env. To reproduce it, first add this line to the.envin the folder where you save the script (and remove it afterwards):
OPENAI_BASE_URL=https://api.openai.com/v1The script then simulates the stale shell variable by setting one itself:
"""load_dotenv() never overwrites a variable that is already set in the environment."""
import os
from dotenv import load_dotenv
os.environ["OPENAI_BASE_URL"] = "http://localhost:11434/v1" # e.g. exported in your shell earlier
load_dotenv() # your .env says OPENAI_BASE_URL=https://api.openai.com/v1
print("default: ", os.environ["OPENAI_BASE_URL"])
load_dotenv(override=True) # let the file win
print("override=True: ", os.environ["OPENAI_BASE_URL"])default: http://localhost:11434/v1
override=True: https://api.openai.com/v1This is usually what you want in production (the real environment wins over a stray file), but it's the number-one cause of "I fixed the key in .env and it still fails". Check whether your shell already has one without printing the key, and remove it if it's stale:
| macOS, Linux, WSL (bash, zsh) | Windows PowerShell | |
|---|---|---|
| Is it set? | [ -n "$OPENAI_API_KEY" ] && echo "set in the shell" |
if ($env:OPENAI_API_KEY) { "set in the shell" } |
| Remove it | unset OPENAI_API_KEY |
Remove-Item Env:OPENAI_API_KEY |
Variables you set this way last only for that terminal window. On Windows, one set through System Properties (or setx) is permanent and reaches every new terminal, so look there too.
- It looks for
.envnext to your script, not in the current directory. Called with no arguments from a.pyfile,load_dotenv()searches the script's folder and then each parent folder. If you runpython tools/check.pyand the.envsits somewhere that isn'ttools/or above it, it won't be found andload_dotenv()returnsFalse. Keep.envat the project root, or passload_dotenv(find_dotenv(usecwd=True)), or an explicit path.
3.5 Never ship a key to a browser or mobile app#
Anything you send to a user's device can be read by that user. JavaScript bundles, mobile app binaries, desktop apps and browser extensions can all be unpacked, and their network traffic can be inspected with the browser's developer tools. A key in client-side code is a public key, and anyone who finds it can run up your bill or abuse the provider in your name. OpenAI's production best practices say to avoid "exposing the API keys in your code or in public repositories", and every provider's guidance says the same about client-side code.
flowchart LR
subgraph bad ["Never: key shipped to the user's device"]
b1["Browser or mobile app<br/>(key inside the bundle)"] -->|"anyone can read it"| p1["Provider API"]
end
subgraph good ["Always: key stays on your server"]
b2["Browser or mobile app"] -->|"your own auth (session, token)"| be["Your backend<br/>key from env or secret manager"]
be -->|"Authorization header"| p2["Provider API"]
endThe fix is always the same: put your own backend in between. The client authenticates to your server with your normal login system, and your server, which holds the key, calls the provider. That also gives you one place to enforce per-user limits, log usage, filter input and keep the prompt private. 03.3 builds exactly this backend, streaming the reply to a browser.
3.6 One key per environment and per app; rotation#
- One key per application and per environment. Your laptop, CI, staging and production each get their own key, and so does each service. When something goes wrong, you can see in the usage dashboard which key did it, and revoke one key without taking everything down.
- Name keys clearly (
support-bot-prod,ci-integration-tests) and record who owns each one. - Give keys an expiry date where the provider supports it. OpenAI recommends "setting an expiration date when you create a project API key".
- Rotate regularly, and always when someone with access leaves. A rotation without downtime has three steps, from OpenAI's guidance: "Before a key expires, create a replacement, update your applications to use it", then revoke the old one once traffic on it has stopped.
3.7 When a key leaks: the first hour#
Keys leak through commits, screenshots, logs, chat messages and public notebooks. Assume it will happen and know the drill:
- Revoke the key immediately in the provider's console, then create a replacement. Don't wait to investigate first: a revoked key can't be abused while you look. (OpenAI's safety guidance: "revoke it promptly and replace it with a new key".)
- Deploy the replacement to every place that used the old key.
- Audit usage. In the usage dashboard, filter by the leaked key and look for unfamiliar models, times, volumes or IP-like patterns. Note when abuse started.
- Check the spend limits are in place (3.3), and contact provider support if there was fraudulent usage.
- Clean the source of the leak. Deleting a commit isn't enough: git history, forks, CI logs and caches keep copies. Rotating the key is what actually fixes it.
- Find out why it leaked and close the gap: log redaction, code review, and a secret scanner that blocks the next leak before it's pushed. Three common choices are GitHub's own push protection (a repository setting that rejects pushes containing known key formats), gitleaks (open source:
gitleaks git -vscans a repository's history, and its README describes apre-commithook that scans every commit), and git-secrets (an older AWS-originated tool with similar hooks). Run a history scan once on any repository you inherit, since a key committed last year is still in it.
Providers help. Anthropic participates in GitHub secret scanning: "If a Claude API key is detected in a public GitHub repository, GitHub immediately notifies Anthropic", which "automatically deactivates the exposed API key" and emails you. Google's auth keys "provide fast-acting leaked key enforcement". Don't rely on this: it covers only public places these systems watch, and only after the leak. Key leaks as a security incident (detection, response and prevention) are covered in Module 12.
3.8 Secret managers and keyless auth in production#
In production, keys belong in a secret manager (AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault, HashiCorp Vault, or your platform's equivalent). It stores secrets encrypted, controls who and which services can read them, logs every access, and supports rotation without redeploying code. Your deployment injects the secret into the process as an environment variable (or your code fetches it at start-up), so the application code stays exactly the same as in development: OpenAI() reads OPENAI_API_KEY. Better still, where your platform supports it, use workload identity federation (OpenAI, Anthropic) or your cloud's IAM roles (Bedrock, Google Cloud, Azure, Part 11), so there is no long-lived key at all. Deployment and secret management are covered in Module 11C.
Part 4: Project setup that works first time#
This part is the setup for the whole module. Other lessons link here.
4.1 Install uv and Python 3.11+#
uv is a fast Python package and project manager: it installs Python versions, creates virtual environments, adds packages and runs your scripts in one tool. Install it from the official instructions (for example curl -LsSf https://astral.sh/uv/install.sh | sh on macOS and Linux), then check:
uv --versionOn Windows, open PowerShell and run uv's documented installer, then open a new terminal so the uv command is found:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
uv --versionEvery bash command in this module works the same in PowerShell unless the lesson says otherwise. The differences that matter are environment variables ($env:NAME = "value" instead of export, Remove-Item Env:NAME instead of unset), loops (foreach) and curl (write curl.exe); each place where it matters shows a PowerShell version. If you'd rather use a Linux shell on Windows, WSL (the Windows Subsystem for Linux) runs every bash command here unchanged.
You don't need to install Python separately: uv downloads a suitable version when a project asks for one. This path requires Python 3.11 or newer, because google-genai requires it ("Drop support for Python 3.10" is in its 2.34.0 changelog).
4.2 Create the project#
uv add works only inside a project (uv's docs: "If a project cannot be found, uv will exit with an error"), so create one first:
uv init llm-apis --bare --python 3.13 # a new folder holding only a pyproject.toml
cd llm-apis
git init # so git check-ignore and git status work (3.4)
uv add openai anthropic google-genai python-dotenv httpxTwo flags are doing work here, and both are checked against uv 0.12.1:
--python 3.13sets the project'srequires-pythonlimit and makes uv pick a Python that satisfies it (downloading 3.13 if you have none). Without it,uv inittakes the limit from the first Python it finds. If that Python is 3.9 or 3.10,uv add google-genaifails with a long "No solution found" message that ends in "google-genai depends on Python>=3.11". The fix is to delete the folder and run the commands above again, or to editrequires-pythoninpyproject.toml(and.python-version, if you have one) to">=3.11"and re-runuv add. Python 3.11 or 3.12 also works; 3.13 is what this module's outputs were produced on.--bareskips the extras that plainuv initadds: aREADME.md, asrc/llm_apis/package, a[build-system]table and a[project.scripts]entry, none of which this module uses. Plainuv initalso runsgit initfor you outside a repository, but not inside one, so the explicitgit initabove is the predictable way.
uv add creates a virtual environment in .venv, installs the packages, records them in pyproject.toml and writes the exact versions of everything (including indirect dependencies) to uv.lock. After it, your pyproject.toml lists the four packages under dependencies, as in the listing below, which shows bare package names. uv itself writes a lower bound for each one (for example openai>=3.42.1, with whatever versions were newest on the day), and uv.lock records the exact versions (01B.1, 7.3):
[project]
name = "llm-apis"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = [
"anthropic",
"google-genai",
"openai",
"python-dotenv",
]Now add the files from 3.4: .env with your keys (or nothing yet, if you'll use the local stand-in), .env.example, and a .gitignore (--bare doesn't create one, so this is the whole file):
# .gitignore
.env*
!.env.example
.venv/
__pycache__/Your project looks like this:
llm-apis/
├── .git/ # created by git init
├── .venv/ # the virtual environment uv created (ignored by git)
├── .env # your keys (ignored by git)
├── .env.example # the template (committed)
├── .gitignore
├── pyproject.toml # your dependencies
├── uv.lock # exact versions of everything (committed)
└── first_call.py # your codeSeveral samples in this module also import httpx or import httpx2 (1.3, 8.5). The uv add line above includes httpx because google-genai 3.x no longer installs it (2.34.0 did: 4.5), and import httpx would otherwise fail. httpx2 comes with openai and anthropic; if you would rather your own code not rely on someone else's dependency, add what you import: uv add httpx2.
Write a script (any first call from Part 6) to first_call.py and run it with:
uv run python first_call.pyuv run makes sure the environment matches the lockfile, then runs the command inside it. You never need to "activate" the virtual environment.
4.3 The pip alternative#
If you can't use uv, the standard tools work too:
python3 --version # must be 3.11 or newer (Windows: py -3.13 --version)
python3 -m venv .venv # create a virtual environment (Windows: py -3.13 -m venv .venv)
source .venv/bin/activate # Windows PowerShell: .venv\Scripts\Activate.ps1 (cmd: .venv\Scripts\activate.bat)
pip install openai anthropic google-genai python-dotenv httpx
pip freeze > requirements.txt # record exact versions, a rough equivalent of uv.lock
git init # only needed for the git commands in 3.4, and only if this isn't a repository yet
python first_call.pyEvery uv run python file.py in this module can be replaced by python file.py inside the activated environment. If PowerShell refuses to run Activate.ps1 because scripts are disabled, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, or use uv instead, which never needs activation.
4.4 Pinning, the lockfile and reading SDK changelogs#
These SDKs release often: newer versions appear every few days, and this module's samples and outputs were written against openai 3.42.1. Most releases add support for new API features, but major versions break code (9.4). So:
- Lock versions for anything you ship. This module's commands name packages without versions, which is fine for learning, but a Dockerfile that runs a bare
pip install openaimeans your production build can change underneath you. Commit the lockfile (next point), or at least constrain the major version (openai>=3.42,<4). - Commit the lockfile (
uv.lock). uv's documentation: it "should be checked into version control", so that everyone, and your CI, installs exactly the same versions. Upgrade deliberately withuv lock --upgrade-package openai, run your tests, then commit. - Read the changelog before upgrading: openai-python, anthropic-sdk-python and python-genai. Look for "BREAKING", removed parameters and default changes.
- Pin your tools too. Proxies, gateways and libraries you run locally (LiteLLM, discussed in 03.11, is one that has had supply-chain incidents) can ship a malicious release. A lockfile with hashes means a newly published bad release can't sneak in, because you only move to a new version when you choose to. Bind any local server to
127.0.0.1, not every network interface.
4.5 The httpx2 switch#
Until mid-2026, all three SDKs used the popular httpx HTTP library, and countless blog posts, Stack Overflow answers and older tutorials configure timeouts, proxies and test mocks with httpx objects. That changed:
openai3.0.0 (12 August 2026): "HTTPX2 is now the default HTTP client, andhttpxis no longer installed automatically."anthropic2.x (2.0.0 released 21 October 2026) also depends onhttpx2.google-genai2.34.0 still useshttpxby default (it declareshttpx>=0.28.1as a hard dependency), but it can usehttpx2too. Ifhttpx2is installed, which it is wheneveropenaioranthropicis, setting the environment variableGOOGLE_GENAI_HTTP_CLIENT=httpx2switches its default client to anhttpx2one (httpxis the default for unset orauto, and a value ofhttpxforces it).HttpOptions(httpx_client=...)accepts either anhttpx.Clientor anhttpx2.Client, andpip install "google-genai[httpx2]"installshttpx2as an extra. Both options were found by reading the 2.34.0 source and checked by running a mock client of each kind. The samples in this lesson were written againstgoogle-genai2.34.0, whose default ishttpx.google-genai3.0.0 (6 November 2026) flips this default, and an unversioned install now gives you 3.x: see the dated note below the table.
httpx2 is a fork of httpx maintained by Pydantic. Its API is almost identical (httpx2.Client, httpx2.Timeout, httpx2.MockTransport), but its classes are different types. In practice:
| If old code does... | With openai 3.x / anthropic 2.x, do... |
|---|---|
OpenAI(http_client=httpx.Client(proxy=...)) |
OpenAI(http_client=httpx2.Client(proxy=...)), or openai.DefaultHttpx2Client(...) to keep the SDK's defaults. For anthropic 2.4.0 the equivalent is anthropic.DefaultHttpxClient(...): despite its name it subclasses httpx2.Client (there is no DefaultHttpx2Client in anthropic; check with dir(anthropic)) |
timeout=httpx.Timeout(60.0, connect=5.0) |
timeout=httpx2.Timeout(60.0, connect=5.0), or just a number of seconds: timeout=60.0 |
Mocks with respx or httpx.MockTransport |
http_client=httpx2.Client(transport=httpx2.MockTransport(handler)), returning httpx2.Response (1.3). respx patches only httpx, so with the default client a "mocked" request really goes out to the network |
import httpx assuming the SDK installed it |
uv add httpx yourself if your own code uses it. google-genai 2.34.0 pulled httpx in, but google-genai 3.x no longer does (dated note below), which is why the uv add line in 4.2 includes httpx |
The openai SDK still accepts a plain httpx.Client at run time as an escape hatch that "may be discontinued", and it doesn't match the type hints. Don't rely on it.
4.6 Try it: check your setup#
Save this as check_setup.py in your project root and run uv run python check_setup.py. It confirms the versions and which keys are present, without ever printing a key:
"""check_setup.py: confirm Python, the SDKs and your keys are in place, without printing any key."""
import os
import sys
from importlib.metadata import version
from dotenv import load_dotenv
assert sys.version_info >= (3, 11), "google-genai needs Python 3.11 or newer"
print("Python ", sys.version.split()[0])
for package in ("openai", "anthropic", "google-genai", "python-dotenv", "httpx2"):
print(f"{package:12s}", version(package))
loaded = load_dotenv() # True if a .env file was found and read
print(".env found ", loaded)
for name in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
value = os.environ.get(name)
print(f"{name:20s}", "set" if value else "not set") # never print any part of a key
for name in ("GOOGLE_API_KEY", "OPENAI_BASE_URL", "ANTHROPIC_BASE_URL", "GOOGLE_GEMINI_BASE_URL"):
if os.environ.get(name):
print(f"note: {name} is set, and it changes which key or server an SDK uses (Part 7.2)")Python 3.13.14
openai 3.42.1
anthropic 2.4.0
google-genai 2.34.0
python-dotenv 1.2.4
httpx2 2.16.0
.env found True
OPENAI_API_KEY set
ANTHROPIC_API_KEY not set
GEMINI_API_KEY set
OPENROUTER_API_KEY not setPart 5: The API families, and which one to use#
Two of the four providers offer more than one API for generating text, and OpenRouter speaks three formats. Picking the right one affects which features you get and how portable your code is.
5.1 OpenAI: Responses and Chat Completions#
The Responses API (client.responses.create, POST /v1/responses) is OpenAI's primary API. OpenAI's migration guide: "While Chat Completions remains supported, Responses is recommended for all new projects." Its shape:
inputis a string, or a list of typed items (messages, tool calls, tool results, reasoning items);instructionscarries the system/developer prompt.- The response's
outputis a list of typed items:messageitems containingoutput_text(orrefusal) parts,reasoningitems,function_callitems, built-in tool calls and more.statussays whether itcompleted. - It can store state on OpenAI's servers (
storedefaults to true; chaining withprevious_response_id, and the Conversations API), which 03.2 covers in depth. - New features (built-in tools, reasoning controls, compaction, background mode) arrive here.
Chat Completions (client.chat.completions.create, POST /v1/chat/completions) is the older API. The SDK README calls it "the previous standard (supported indefinitely)", and OpenAI's deprecations page lists no deprecation for it. Its shape:
messages: a list of{"role": ..., "content": ...}dictionaries (system/developer,user,assistant,tool).- The response has
choices, each with amessageand afinish_reason.
Why Chat Completions still matters so much: it's the lingua franca of the industry. OpenRouter, Ollama, vLLM, LiteLLM, Gemini's OpenAI-compatibility endpoint and dozens of hosting companies all accept this shape (5.5). Code written against it can often switch providers by changing base_url.
What this means for you: use Responses for new OpenAI-only code, and Chat Completions when portability across OpenAI-compatible servers matters more than OpenAI's newest features, or when you're maintaining existing code. Both are fully supported. Never describe Chat Completions as deprecated: it isn't.
5.2 Anthropic: Messages#
Anthropic has one API for generating text: Messages (client.messages.create, POST /v1/messages).
messagesis a list ofuserandassistantturns, andsystemis a separate top-level parameter (a string or a list of text blocks).max_tokensis required on every request. There's no default.- The response's
contentis a list of typed content blocks (text,thinking,tool_useand others), andstop_reasonsays why it stopped. - There are no sampling parameters under API version
2026-10-21:temperature,top_pandtop_kreturn a 400 (9.1).
Batches, token counting and the Files API are separate endpoints around it (03.7, 03.9, 03.6). Anthropic also offers an OpenAI SDK compatibility endpoint, which its docs describe as "primarily intended to test and compare model capabilities, and is not considered a long-term or production-ready solution for most use cases" (5.5).
5.3 Gemini: generate_content and Interactions#
Google offers two APIs, and in 2026 it changed which one it recommends.
generate_content (client.models.generate_content, POST /v1beta/models/{model}:generateContent) is the API most existing Gemini code uses, and the one Module 02's samples used.
contentsis a list ofContentobjects with roleuserormodel, each made of parts (text, images, function calls...). The SDK accepts a plain string and wraps it for you.- Settings go in a
config(types.GenerateContentConfig):system_instruction,max_output_tokens,thinking_config,toolsand so on. - The response has
candidates, each withcontent.partsand afinish_reason, plususage_metadata.
The Interactions API (client.interactions.create, POST /v1beta/interactions, and generally available in /v1) is Google's newer interface. Google's overview: "As of June 2026, it is Generally Available and the recommended interface for all new projects. While it is now considered legacy, the original generateContent API remains fully supported." And: "Going forward, new models and capabilities … will launch on the Interactions API."
inputis a string, content, or a list of steps;system_instruction,generation_config,toolsandresponse_formatsit alongside.- The response is an
Interactionwith anid, astatusand a list of typedsteps(model_output,thought,function_calland more). - It can store interactions server-side (
storedefaults to true) and chain them withprevious_interaction_id(03.2), run long jobs withbackground=True, and call Google's agents through the same API.
As of November 2026, three features are "not yet available in the Interactions API": the Batch API, automatic function calling in the Python SDK, and explicit caching. If you need any of them, generate_content is still their only home.
5.4 OpenRouter: three endpoints#
OpenRouter is a gateway: one account and one key in front of hundreds of models from many providers (02.9, 5.4). It accepts three request formats:
| Endpoint | Format | Call it with | Notes |
|---|---|---|---|
POST /api/v1/chat/completions |
OpenAI Chat Completions | openai SDK, base_url="https://openrouter.ai/api/v1" |
Primary in this module: OpenRouter's native and most widely supported format |
POST /api/v1/responses |
OpenAI Responses | the same openai client, client.responses.create |
Generally available, but stateless only: "Requests that set store: true or a non-null previous_response_id are rejected with a 400 error" |
POST /api/v1/messages |
Anthropic Messages | anthropic SDK, base_url="https://openrouter.ai/api" |
Lets Anthropic-shaped code (including the Claude Agent SDK and Claude Code) route through OpenRouter |
OpenRouter-only request fields (models fallbacks, provider routing, plugins, session_id) travel in the openai SDK's extra_body=, and OpenRouter-only response fields (such as usage.cost) arrive in model_extra (8.3).
5.5 OpenAI-compatible endpoints elsewhere: what "compatible" guarantees#
Because Chat Completions became the industry's common format, many servers accept it:
| Server | Base URL for the openai SDK |
Status and limits (as of November 2026) |
|---|---|---|
| Gemini OpenAI compatibility | https://generativelanguage.googleapis.com/v1beta/openai/ |
"Still in beta while we extend feature support". Chat Completions (with streaming, tools, images, audio, structured output), embeddings, models and batches; batch file upload and download aren't supported, and no Responses API is documented. Gemini-only settings go in a nested extra_body={"extra_body": {"google": {...}}} |
| Anthropic OpenAI compatibility | https://api.anthropic.com/v1/ |
For testing and comparison only. strict is ignored, audio and file inputs return 400, no prompt caching, thinking content isn't returned, n must be 1 |
| Ollama (local) | http://localhost:11434/v1 |
Chat Completions and Responses (stateless only); no tool_choice, logprobs, image URLs or n (Part 12) |
| vLLM, llama.cpp server, LM Studio (self-hosted) | Your server's /v1 |
Chat Completions for open-weight models you run (Module 11C) |
| Inference hosts (Together, Fireworks, DeepInfra, Groq and many others) | The host's documented /v1 URL |
Chat Completions for open-weight models; feature support varies by host |
| OpenRouter | https://openrouter.ai/api/v1 |
Chat Completions and Responses (5.4) |
What "OpenAI-compatible" does guarantee: the core request shape (model, messages, common parameters), the core response shape (choices, message, finish_reason, usage), and usually streaming in the same SSE format. Your openai SDK code will run.
What it doesn't guarantee:
- That every parameter is honoured. Unknown or unsupported parameters may be rejected with a 400, or silently ignored, which is worse: Ollama ignores
tool_choice, and many servers ignoreseedorreasoning_effort. - The same defaults (output limits, system-prompt handling, safety settings).
- The same errors: status codes, error
type/codestrings and retry hints differ, so error-handling code written for OpenAI may misclassify them (03.8). - The same metadata: request-ID headers, rate-limit headers,
usagedetails (cached or reasoning tokens),system_fingerprintandservice_tiermay be missing. On the stand-in,response._request_idisNonebecause Ollama sends nox-request-idheader; on OpenRouter's model list,owned_byisNone(10.2). - Newer features: Responses, strict structured outputs, built-in tools and file inputs are often missing.
- The same model behaviour. Same API, different model: prompts tuned for one model may not transfer (Module 10A).
What this means for you: compatibility layers are excellent for trying models quickly and for local practice. For production on a first-party model, use the provider's native SDK and API, which expose every feature and report errors precisely. 03.11 shows how to build your own thin abstraction instead of relying on compatibility alone.
5.6 Choosing: a decision table#
| Situation | OpenAI | Anthropic | Gemini | OpenRouter |
|---|---|---|---|---|
| New project, this provider only | Responses | Messages | Interactions (Google's recommendation) or generate_content (fully supported; this module's primary) |
Chat Completions |
| Need the newest features | Responses | Messages (with betas, 9.2) | Interactions | Whichever format your target model's features need |
| Existing code | Keep Chat Completions; migrate when you need Responses-only features | Messages | Keep generate_content |
Keep what you have |
| Must also run on other servers (Ollama, vLLM, hosts) | Chat Completions | — (use the native SDK; compatibility endpoints aren't for production) | — | Chat Completions |
| Need Batch API, explicit caching or Python automatic function calling | Either (batches accept both) | Messages | generate_content only |
— |
| Want server-side conversation state | Responses (previous_response_id, Conversations) |
— (send the history) | Interactions (previous_interaction_id) |
— (stateless) |
flowchart TD
start["Which API should a new project use?"] --> prov{"Which provider?"}
prov -->|OpenAI| oai{"Need Chat Completions compatibility<br/>with other servers or existing code?"}
oai -->|no| resp["Responses API"]
oai -->|yes| cc["Chat Completions"]
prov -->|Anthropic| msg["Messages API"]
prov -->|Gemini| gem{"Need Batch API, explicit caching<br/>or Python automatic function calling?"}
gem -->|yes| gc["generate_content"]
gem -->|no| inter["Interactions API<br/>(Google's recommendation)"]
prov -->|OpenRouter| orq{"Your code's existing shape?"}
orq -->|"OpenAI Chat"| orcc["/api/v1/chat/completions"]
orq -->|"OpenAI Responses"| orresp["/api/v1/responses (stateless)"]
orq -->|"Anthropic SDK"| ormsg["/api/v1/messages"]Part 6: Your first call on every provider#
Each section below shows the minimal call first: the shortest correct code, the kind you'd type to try a provider. Then 6.7 shows the production-minded version of each. All samples load keys from .env and use the module's default models. Their outputs are illustrative because they need a key (how to read the output labels), but every one of them has also been run against the local stand-in (12.3), so you can run them too, for free. The OpenRouter samples are the one exception to "unchanged": they hard-code OpenRouter's base URL, so you edit that line first (12.3 explains how).
Save each sample under the name in its first comment line (for example openai_responses_min.py) in your project folder, and run it with uv run python <name>. 12.3 and the exercises refer to the samples by those names.
6.1 OpenAI: Responses#
# openai_responses_min.py
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # copies OPENAI_API_KEY from .env into the environment
client = OpenAI() # reads OPENAI_API_KEY (and OPENAI_BASE_URL, if set) from the environment
response = client.responses.create(
model="gpt-6-luna",
input="In one sentence, what is an API?",
)
print(response.output_text)An API (application programming interface) is a defined set of rules that lets one program request data or actions from another.response.output_text is an SDK convenience property that joins the text of every output_text part in the output. It's handy, but it hides things (8.4).
6.2 OpenAI: Chat Completions#
# openai_chat_min.py
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-6-luna",
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
)
print(completion.choices[0].message.content)An API is a set of rules and endpoints that lets different software systems communicate and exchange data.The same client object serves both APIs. choices is a list because Chat Completions can return several alternatives (n); with the default n=1 there's one.
6.3 Anthropic: Messages#
# anthropic_min.py
import anthropic
from dotenv import load_dotenv
load_dotenv() # copies ANTHROPIC_API_KEY from .env into the environment
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY (and ANTHROPIC_BASE_URL, if set)
message = client.messages.create(
model="claude-haiku-5-5",
max_tokens=1024, # required by the Messages API
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
)
for block in message.content: # a list of typed blocks, not a string
if block.type == "text":
print(block.text)An API (Application Programming Interface) is a set of defined rules that allows different software applications to communicate with each other.Note the loop over message.content. A Claude reply is a list of blocks, and current Claude models may put a thinking block before the text, so message.content[0].text is a bug waiting to happen (8.4).
6.4 Gemini: generate_content#
# gemini_generate_min.py
from dotenv import load_dotenv
from google import genai
load_dotenv() # copies GEMINI_API_KEY from .env into the environment
client = genai.Client() # reads GEMINI_API_KEY (and GOOGLE_GEMINI_BASE_URL, if set)
response = client.models.generate_content(
model="gemini-3.8-flash",
contents="In one sentence, what is an API?",
)
print(response.text)An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate and exchange data with each other.6.5 Gemini: Interactions#
# gemini_interactions_min.py
from dotenv import load_dotenv
from google import genai
load_dotenv()
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="In one sentence, what is an API?",
)
print(interaction.output_text)An API is a set of rules that allows different software programs to communicate with each other and exchange data.The same genai.Client serves both APIs. Two differences from generate_content will matter later:
storedefaults to true, so Google keeps the interaction on its servers for a retention period (03.2 covers retention, chaining and deletion). Passstore=Falsewhen you don't need server-side state.- Interactions errors are a separate exception hierarchy.
client.models.*calls raisegoogle.genai.errors.APIErrorsubclasses (ClientError,ServerError).client.interactions.*calls raise different classes that don't inherit from it, soexcept errors.APIError:silently misses them. Ingoogle-genai2.34.0 they're importable only from a private module,google.genai._interactions. See it with a mock server returning each API's documented 404 error body:
"""generate_content and Interactions raise DIFFERENT exception classes (mock 404 in each API's error shape)."""
import httpx
from google import genai
from google.genai import _interactions, errors, types # _interactions: private, the only path in 2.34.0
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/interactions"): # Interactions error body
return httpx.Response(404, json={"error": {"code": "model_not_found", "message": "Model not found"}})
return httpx.Response(404, json={"error": {"code": 404, "message": "Model not found", "status": "NOT_FOUND"}})
client = genai.Client(api_key="gemini-test",
http_options=types.HttpOptions(httpx_client=httpx.Client(transport=httpx.MockTransport(handler))))
try:
client.models.generate_content(model="gemini-3.8-flahs", contents="Hi")
except errors.APIError as e:
print("generate_content ->", type(e).__name__, e.code, e.status, "| is errors.APIError: True")
try:
client.interactions.create(model="gemini-3.8-flahs", input="Hi")
except errors.APIError:
print("never reached: errors.APIError does not catch Interactions errors")
except _interactions.APIStatusError as e:
print("interactions ->", type(e).__name__, e.status_code,
"| is errors.APIError:", isinstance(e, errors.APIError))generate_content -> ClientError 404 NOT_FOUND | is errors.APIError: True
interactions -> NotFoundError 404 | is errors.APIError: False03.8 builds error handling that covers both. Retries differ too: by default client.models.* calls don't retry at all, while client.interactions.* calls do (7.4).
6.6 OpenRouter: Chat Completions, Responses and Messages#
# openrouter_min.py
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # copies OPENROUTER_API_KEY from .env
client = OpenAI(
base_url="https://openrouter.ai/api/v1", # the only real difference from OpenAI
api_key=os.environ["OPENROUTER_API_KEY"], # not OPENAI_API_KEY: pass it explicitly
default_headers={ # optional attribution, sent on every request
"HTTP-Referer": "https://your-app.example.com",
"X-OpenRouter-Title": "Your App Name",
},
)
completion = client.chat.completions.create(
model="anthropic/claude-haiku-5.5", # vendor/model, with dots in the version
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
)
print(completion.choices[0].message.content)
# The same client also speaks OpenRouter's Responses API (stateless only)
response = client.responses.create(model="openai/gpt-6-luna", input="In one sentence, what is an API?")
print(response.output_text)An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other.
An API is a set of rules that lets one piece of software request data or services from another.Points to notice:
- Pass the key explicitly. The
openaiSDK readsOPENAI_API_KEYby default, which would send your OpenAI key to OpenRouter. Always passapi_key=os.environ["OPENROUTER_API_KEY"]. - Attribution headers are optional.
HTTP-Referer(your site's URL) "is required for app attribution", andX-OpenRouter-Title"sets or modifies your app's display name" in OpenRouter's public app rankings.X-OpenRouter-TitlereplacedX-Title, which "is still supported for backwards compatibility". Setting them once indefault_headerssends them on every request; per-callextra_headersworks too. - Model IDs differ from the providers' own. OpenRouter writes
anthropic/claude-haiku-5.5, with a vendor prefix and dots in the version, while Anthropic's own ID isclaude-haiku-5-5, with hyphens. Copying one into the other's API gives a 404. - Don't send
store=Trueorprevious_response_idto OpenRouter's Responses API: it's stateless and returns a 400.
Anthropic-shaped code can use OpenRouter's Messages endpoint with the anthropic SDK:
# openrouter_messages.py
import os
import anthropic
from dotenv import load_dotenv
load_dotenv()
client = anthropic.Anthropic(
base_url="https://openrouter.ai/api", # the SDK appends /v1/messages
api_key=os.environ["OPENROUTER_API_KEY"], # SDK 2.x sends it as Authorization: Bearer
)
message = client.messages.create(
model="anthropic/claude-haiku-5.5",
max_tokens=1024,
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
)
print("".join(block.text for block in message.content if block.type == "text"))An API is a set of rules and protocols that lets different software applications communicate with each other.6.7 Production-minded first calls#
The minimal calls work, but each one has gaps that hurt in production: no timeout beyond the SDK's 10-minute default, no output cap (so a runaway answer bills thousands of tokens), no check that the answer is complete, and nothing logged for debugging or cost. Here are the same six calls with four additions:
- An explicit timeout sized for the task, plus the SDK's retries made explicit.
- A max-output-token cap. It also bounds the cost of one call. On reasoning models the cap includes hidden reasoning tokens, so leave headroom (02.8, 5.1).
- A status or finish-reason check before the text is used (02.5, 4.5 explains each value).
- A log line with the model, IDs, request ID and usage, so any call can be traced, debugged with the provider's support team, and costed.
They use Python's standard logging module. Logging set to INFO also shows the SDKs' own one-line log of each HTTP request, which is useful during development.
OpenAI Responses:
# openai_responses_prod.py
"""A production-minded first call: OpenAI Responses API."""
import logging
import openai
from dotenv import load_dotenv
from openai import OpenAI
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
log = logging.getLogger("llm")
load_dotenv()
client = OpenAI(timeout=30.0, max_retries=2) # created once at start-up and reused (Part 7)
try:
response = client.responses.create(
model="gpt-6-luna",
input="In one sentence, what is an API?",
max_output_tokens=500, # cap on output; reasoning tokens count towards it
reasoning={"effort": "none"}, # no thinking for a simple answer (Luna and Terra only)
store=False, # don't keep this response on OpenAI's servers (03.2)
)
except openai.APIStatusError as e: # the server answered with an error status
log.error("openai error status=%s request_id=%s body=%s", e.status_code, e.request_id, e.body)
raise
except openai.APIConnectionError: # no answer at all: network, DNS, TLS or timeout
log.exception("openai connection failed")
raise
usage = response.usage
log.info("openai model=%s id=%s request_id=%s status=%s tokens_in=%s tokens_out=%s",
response.model, response.id, response._request_id, response.status,
usage.input_tokens if usage else None, usage.output_tokens if usage else None)
if response.status != "completed": # "incomplete" still arrives as HTTP 200
reason = response.incomplete_details.reason if response.incomplete_details else None
raise RuntimeError(f"OpenAI response not complete: status={response.status} reason={reason}")
if not response.output_text: # "completed" can still mean a refusal or a tool call, not text (8.4)
raise RuntimeError("OpenAI returned no text output (a refusal or a tool call?): inspect response.output")
print(response.output_text)INFO httpx2 HTTP Request: POST https://api.openai.com/v1/responses "HTTP/1.1 200 OK"
INFO llm openai model=gpt-6-luna id=resp_0c2f9d81b7a4e3f60069a1e2 request_id=req_3f1a7c09e2b84d5fa6c1d0e9b8a7f612 status=completed tokens_in=14 tokens_out=24
An API is a defined set of rules that lets one piece of software request data or actions from another.OpenAI Chat Completions:
# openai_chat_prod.py
"""A production-minded first call: OpenAI Chat Completions."""
import logging
import openai
from dotenv import load_dotenv
from openai import OpenAI
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
log = logging.getLogger("llm")
load_dotenv()
client = OpenAI(timeout=30.0, max_retries=2)
try:
completion = client.chat.completions.create(
model="gpt-6-luna",
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
max_completion_tokens=500, # includes reasoning tokens
reasoning_effort="none", # no thinking for a simple answer (Luna and Terra only)
)
except openai.APIStatusError as e:
log.error("openai error status=%s request_id=%s body=%s", e.status_code, e.request_id, e.body)
raise
choice = completion.choices[0]
usage = completion.usage
log.info("openai model=%s id=%s request_id=%s finish_reason=%s tokens_in=%s tokens_out=%s",
completion.model, completion.id, completion._request_id, choice.finish_reason,
usage.prompt_tokens if usage else None, usage.completion_tokens if usage else None)
if choice.finish_reason != "stop": # "length" = truncated, "content_filter" = blocked
raise RuntimeError(f"Unexpected finish_reason: {choice.finish_reason}")
if choice.message.refusal: # a refusal is a separate field, not an error
raise RuntimeError(f"Model refused: {choice.message.refusal}")
print(choice.message.content)INFO httpx2 HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK"
INFO llm openai model=gpt-6-luna id=chatcmpl-DkT2v9QbXg4mRzL1aP8sYwE0nC5u request_id=req_8e02b6d4f1c94a73b5e0a2d9c7f61b38 finish_reason=stop tokens_in=14 tokens_out=21
An API is a set of rules and endpoints that lets different software systems communicate and exchange data.Anthropic Messages:
# anthropic_prod.py
"""A production-minded first call: Anthropic Messages API."""
import logging
import anthropic
from dotenv import load_dotenv
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
log = logging.getLogger("llm")
load_dotenv()
client = anthropic.Anthropic(timeout=30.0, max_retries=2)
try:
message = client.messages.create(
model="claude-haiku-5-5",
max_tokens=500, # required; thinking tokens count towards it
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
# no temperature/top_p/top_k: API version 2026-10-21 rejects them with a 400
)
except anthropic.APIStatusError as e:
log.error("anthropic error status=%s request_id=%s body=%s", e.status_code, e.request_id, e.body)
raise
except anthropic.APIConnectionError:
log.exception("anthropic connection failed")
raise
u = message.usage
log.info("anthropic model=%s id=%s request_id=%s stop_reason=%s tokens_in=%s "
"cache_read=%s cache_write=%s tokens_out=%s",
message.model, message.id, message._request_id, message.stop_reason, u.input_tokens,
u.cache_read_input_tokens, u.cache_creation_input_tokens, u.output_tokens)
if message.stop_reason != "end_turn": # max_tokens, refusal, pause_turn... arrive as HTTP 200
raise RuntimeError(f"Unexpected stop_reason: {message.stop_reason}")
print("".join(block.text for block in message.content if block.type == "text"))INFO httpx2 HTTP Request: POST https://api.anthropic.com/v1/messages "HTTP/1.1 200 OK"
INFO llm anthropic model=claude-haiku-5-5 id=msg_01HvQ3kXr8PzT5wYbN2cLdEa request_id=req_011CWa7Lm2nQx9RkT4vPzJ8s stop_reason=end_turn tokens_in=16 cache_read=0 cache_write=0 tokens_out=27
An API (Application Programming Interface) is a set of defined rules that allows different software applications to communicate with each other.The three Anthropic input counters are logged separately because total input is their sum (02.2, 6.6).
Gemini generate_content:
# gemini_generate_prod.py
"""A production-minded first call: Gemini generate_content."""
import logging
from dotenv import load_dotenv
from google import genai
from google.genai import errors, types
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
log = logging.getLogger("llm")
load_dotenv()
client = genai.Client(
http_options=types.HttpOptions(
timeout=30_000, # MILLISECONDS, unlike the other SDKs
retry_options=types.HttpRetryOptions(attempts=3), # models.* calls don't retry unless asked
)
)
try:
response = client.models.generate_content(
model="gemini-3.8-flash",
contents="In one sentence, what is an API?",
config=types.GenerateContentConfig(max_output_tokens=500), # thinking tokens count too
)
except errors.APIError as e: # ClientError (4xx) and ServerError (5xx) both inherit this
log.error("gemini error code=%s status=%s message=%s", e.code, e.status, e.message)
raise
u = response.usage_metadata
log.info("gemini model_version=%s response_id=%s tokens_in=%s tokens_out=%s thinking=%s",
response.model_version, response.response_id,
u.prompt_token_count if u else None, u.candidates_token_count if u else None,
u.thoughts_token_count if u else None)
if not response.candidates: # the prompt itself was blocked: no candidates at all
reason = response.prompt_feedback.block_reason if response.prompt_feedback else None
raise RuntimeError(f"Prompt blocked: {reason}")
finish = response.candidates[0].finish_reason
if finish != types.FinishReason.STOP: # MAX_TOKENS, SAFETY, RECITATION... arrive as HTTP 200
raise RuntimeError(f"Unexpected finish_reason: {finish}")
print(response.text)INFO google_genai.models AFC is enabled with max remote calls: 10.
INFO httpx HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent "HTTP/1.1 200 OK"
INFO llm gemini model_version=gemini-3.8-flash response_id=Wf8kafqZGt3V7M8Ps4ydmQo tokens_in=9 tokens_out=26 thinking=212
An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate and exchange data with each other.Two Gemini-specific details are in this sample. The timeout is in milliseconds (30_000), and retries are switched on explicitly, because google-genai 2.34.0 doesn't retry models.* calls unless you pass retry_options (7.4). The "AFC is enabled" line is the SDK announcing automatic function calling, which only matters when you pass Python functions as tools (03.5). Note that Gemini reports thinking tokens separately from output tokens (thinking=212 here), and you pay for both.
Gemini Interactions:
# gemini_interactions_prod.py
"""A production-minded first call: Gemini Interactions API."""
import logging
from dotenv import load_dotenv
from google import genai
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
log = logging.getLogger("llm")
load_dotenv()
client = genai.Client()
# Interactions errors are NOT google.genai.errors.APIError subclasses (see 6.5 and 03.8),
# so this sample lets them propagate rather than catch the wrong class.
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="In one sentence, what is an API?",
generation_config={"max_output_tokens": 500}, # thinking tokens count towards it
store=False, # default True: Google keeps the interaction (03.2 covers retention)
timeout=30.0, # per-call timeout here is in SECONDS
)
u = interaction.usage
log.info("gemini interaction id=%s model=%s status=%s tokens_in=%s tokens_out=%s thinking=%s",
interaction.id, interaction.model, interaction.status,
u.total_input_tokens if u else None, u.total_output_tokens if u else None,
u.total_thought_tokens if u else None)
if interaction.status != "completed": # incomplete, failed, requires_action...
raise RuntimeError(f"Interaction not completed: {interaction.status}")
print(interaction.output_text)INFO httpx HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/interactions "HTTP/1.1 200 OK"
INFO llm gemini interaction id=v1_ChdXZjhrYWZxWkd0M1Y3TThQczR5ZG1RbxIXV2Y4a2FmcVpHdDNWN004UHM0eWRtUW8 model=gemini-3.8-flash status=completed tokens_in=9 tokens_out=24 thinking=187
An API is a set of rules that allows different software programs to communicate with each other and exchange data.OpenRouter:
# openrouter_prod.py
"""A production-minded first call: OpenRouter Chat Completions through the openai SDK."""
import logging
import os
import openai
from dotenv import load_dotenv
from openai import OpenAI
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
log = logging.getLogger("llm")
load_dotenv()
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
timeout=30.0,
max_retries=2,
default_headers={"HTTP-Referer": "https://your-app.example.com", "X-OpenRouter-Title": "Your App Name"},
)
try:
# .with_raw_response gives us the HTTP headers as well as the parsed object
raw = client.chat.completions.with_raw_response.create(
model="anthropic/claude-haiku-5.5",
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
max_tokens=500,
)
except openai.APIStatusError as e: # 402 = out of credits, 403 = guardrail/moderation (03.8)
log.error("openrouter error status=%s body=%s", e.status_code, e.body)
raise
completion = raw.parse()
if not completion.choices: # OpenRouter can answer 200 with only an error body: choices is None (03.8)
raise RuntimeError(f"OpenRouter returned an error body: {completion.model_extra}")
choice = completion.choices[0]
usage = completion.usage
cost = (usage.model_extra or {}).get("cost") if usage else None # OpenRouter-only field
log.info("openrouter model=%s generation_id=%s finish_reason=%s tokens_in=%s tokens_out=%s cost=%s",
completion.model, raw.headers.get("x-generation-id"), choice.finish_reason,
usage.prompt_tokens if usage else None, usage.completion_tokens if usage else None, cost)
if choice.finish_reason != "stop": # length, content_filter, tool_calls, error
raise RuntimeError(f"Unexpected finish_reason: {choice.finish_reason}")
print(choice.message.content)INFO httpx2 HTTP Request: POST https://openrouter.ai/api/v1/chat/completions "HTTP/1.1 200 OK"
INFO llm openrouter model=anthropic/claude-haiku-5.5 generation_id=gen-1793758421-Xk2pQ9vLr7TmB4sNw1Ye finish_reason=stop tokens_in=16 tokens_out=27 cost=1.51e-05
An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other.The if not completion.choices guard matters because OpenRouter can answer HTTP 200 with a body that holds only an error. The SDK parses that without raising, choices is None, and unguarded indexing fails with TypeError: 'NoneType' object is not subscriptable (03.8 treats these errors in depth). OpenRouter returns the cost of every call in usage.cost (in credits, an OpenRouter-only field, so it lands in model_extra), and the generation ID in the X-Generation-Id response header on every endpoint. Keep the generation ID: GET /api/v1/generation?id=... returns the full record of the call (provider used, latency, native token counts), which 03.7 uses for cost reconciliation.
6.8 What later samples leave out#
The production-minded pattern above (timeout, cap, finish-reason check, usage and request-ID logging, typed exception handling) is what real code needs on every call. To keep the samples in the rest of Module 03 readable, most of them omit the logging and the exception handling, and often the explicit timeout, unless the lesson is about them. When you copy a sample into a real project, add them back, or better, wrap them once in your own client function (03.11 builds that wrapper). Every later sample still caps output where it matters and still selects text blocks by type.
Part 7: Configuring clients#
Deep-dive
7.1 Constructor parameters#
You configure most behaviour once, when you create the client. The three SDKs name things differently, and google-genai puts its HTTP settings in a separate HttpOptions object. As of openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0:
| Setting | OpenAI(...) |
anthropic.Anthropic(...) |
genai.Client(...) |
|---|---|---|---|
| Key | api_key= (a string, or a function returning one, for tokens that refresh) |
api_key=, or one of auth_token=, credentials=, config=, profile= (exactly one) |
api_key= |
| Server address | base_url= |
base_url= |
http_options=types.HttpOptions(base_url=...) |
| Timeout | timeout= in seconds (a number or an httpx2.Timeout); default 600 s, connect 5 s |
timeout= in seconds; default 600 s, connect 5 s |
HttpOptions(timeout=...) in milliseconds; per-call timeout= on interactions.create in seconds |
| Retries | max_retries= (default 2) |
max_retries= (default 2) |
HttpOptions(retry_options=types.HttpRetryOptions(...)); no retries by default for models.* |
| Extra headers on every request | default_headers= |
default_headers= |
HttpOptions(headers=...) |
| Default query parameters | default_query= |
default_query= |
— |
| Organization / project / workspace | organization=, project= |
(workspace via the anthropic-workspace-id header, or the key's scope) |
project=, location= (only with enterprise=True) |
| Custom HTTP client | http_client=httpx2.Client(...) |
http_client=httpx2.Client(...) |
HttpOptions(httpx_client=httpx.Client(...)) (an httpx2.Client is accepted too, 4.5) |
| API version | — (none to set) | fixed by the SDK major version (9.1) | HttpOptions(api_version="v1") (the 2.34.0 default is v1beta; 3.x defaults to v1, 4.5) |
| Other notable options | workload_identity= (keyless auth), data_residency= ("global", "us", "eu", "ae": picks a regional endpoint such as https://eu.api.openai.com/v1), provider= (cloud platforms, Part 11), webhook_secret= |
middleware=, open_telemetry=, webhook_key= |
enterprise=True / vertexai=True (Google Cloud, Part 11), credentials= |
7.2 Environment variables and precedence#
Every SDK reads defaults from environment variables. The rule is the same everywhere: an explicit constructor argument wins over an environment variable, which wins over the SDK's built-in default.
| SDK | Variables it reads (as of November 2026) |
|---|---|
openai |
OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_ORG_ID, OPENAI_PROJECT_ID, OPENAI_ADMIN_KEY, OPENAI_WEBHOOK_SECRET; the SDK source also reads OPENAI_CUSTOM_HEADERS (one Name: value per line) |
anthropic |
ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL, ANTHROPIC_PROFILE plus the federation variables, ANTHROPIC_WEBHOOK_SIGNING_KEY; the source also reads ANTHROPIC_CUSTOM_HEADERS |
google-genai |
GEMINI_API_KEY, GOOGLE_API_KEY (wins if both are set), GOOGLE_GEMINI_BASE_URL; for Google Cloud, GOOGLE_GENAI_USE_ENTERPRISE (or the older GOOGLE_GENAI_USE_VERTEXAI), GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION |
| OpenRouter | None: OPENROUTER_API_KEY is a naming convention you read yourself and pass as api_key= |
The *_BASE_URL variables are what make the free local stand-in work: set OPENAI_BASE_URL=http://localhost:11434/v1 and unchanged code that calls OpenAI() talks to Ollama instead (12.3). They're also a trap: a forgotten OPENAI_BASE_URL in your shell sends production traffic somewhere unexpected.
Here's the precedence on each SDK, with dummy keys so nothing is sent:
# s7_env_precedence.py
"""Where does each SDK get its settings? Environment variables vs constructor arguments.
Every key below is an obviously fake dummy: nothing is sent anywhere."""
import logging
import os
import sys
import anthropic
import openai
from google import genai
# Send the SDKs' warnings to stdout so they appear in order with our prints
logging.basicConfig(level=logging.WARNING, stream=sys.stdout, format=" [%(levelname)s %(name)s] %(message)s")
# --- OpenAI: environment variables are defaults; constructor arguments win -----------
os.environ["OPENAI_API_KEY"] = "sk-dummy"
os.environ["OPENAI_BASE_URL"] = "http://localhost:11434/v1"
print("openai, from env: ", openai.OpenAI().base_url)
print("openai, explicit wins: ", openai.OpenAI(base_url="https://api.openai.com/v1").base_url)
del os.environ["OPENAI_API_KEY"]
try:
openai.OpenAI() # no key anywhere: fails at construction
except openai.OpenAIError as e:
print("openai, no key: OpenAIError:", str(e)[:60], "...")
# --- Anthropic: exactly one credential per client ------------------------------------
try:
anthropic.Anthropic(api_key="sk-ant-dummy", auth_token="dummy-token")
except ValueError as e:
print("anthropic, two creds: ValueError:", str(e)[:60], "...")
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-dummy"
os.environ["ANTHROPIC_AUTH_TOKEN"] = "dummy-token"
print("anthropic, both env vars:")
client = anthropic.Anthropic()
print(" -> uses ANTHROPIC_API_KEY:", client.api_key == os.environ["ANTHROPIC_API_KEY"])
# --- Gemini: GOOGLE_API_KEY beats GEMINI_API_KEY, with only a log warning -------------
os.environ["GEMINI_API_KEY"] = "dummy-key-you-just-created"
os.environ["GOOGLE_API_KEY"] = "dummy-key-left-over-from-another-project"
print("gemini, both env vars:")
gemini = genai.Client()
used = gemini._api_client.api_key # private attribute: inspected only for this demo
print(" -> uses GOOGLE_API_KEY:", used == os.environ["GOOGLE_API_KEY"])openai, from env: http://localhost:11434/v1/
openai, explicit wins: https://api.openai.com/v1/
openai, no key: OpenAIError: Missing credentials. Please pass an `api_key`, `workload_ide ...
anthropic, two creds: ValueError: Pass at most one of `api_key=`, `auth_token=`, `credentials= ...
anthropic, both env vars:
[WARNING anthropic.lib.credentials._auth] Anthropic: ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN are both set. Using ANTHROPIC_API_KEY.
-> uses ANTHROPIC_API_KEY: True
gemini, both env vars:
[WARNING google_genai._api_client] Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.
-> uses GOOGLE_API_KEY: True7.3 Per-request options#
Sometimes one call needs different settings, or a field the SDK doesn't know yet. Three tools cover it:
client.with_options(...)(openai,anthropic) returns a copy of the client with some settings changed (timeout, retries, headers, base URL...). The copy shares the original's connection pool, so it's cheap, and the original is unchanged.extra_headers=,extra_query=,extra_body=on any method add headers, URL query parameters or JSON body fields to that one request.google-genai'sinteractions.createaccepts the same three; itsmodels.*methods takeconfig=types.GenerateContentConfig(http_options=...)for per-call HTTP settings.- Per-call
timeout=on anyopenaioranthropicmethod.
See all three on the wire (a mock transport again):
"""Per-request options and client lifecycle, observed on the wire through a mock transport."""
import json
import httpx2
from openai import OpenAI
def handler(request: httpx2.Request) -> httpx2.Response:
body = json.loads(request.content)
print(f" -> {request.method} {request.url}")
print(f" x-stainless-read-timeout={request.headers.get('x-stainless-read-timeout')} "
f"x-client-request-id={request.headers.get('x-client-request-id')} "
f"body keys={sorted(body)}")
return httpx2.Response(200, json={"output": []})
mock = httpx2.Client(transport=httpx2.MockTransport(handler))
with OpenAI(api_key="sk-test", timeout=30.0, http_client=mock) as client: # closes on exit
print("1. plain call, client defaults (timeout 30 s):")
client.responses.create(model="gpt-6-luna", input="Hi")
print("2. with_options: a copy with different settings, sharing the same connection pool")
fast = client.with_options(timeout=5.0, max_retries=0)
fast.responses.create(model="gpt-6-luna", input="Hi")
print(" original client still has timeout", client.timeout, "| copy has", fast.timeout)
print("3. extra_headers / extra_query / extra_body: escape hatches for one request")
client.responses.create(
model="gpt-6-luna", input="Hi",
extra_headers={"X-Client-Request-Id": "order-4711-attempt-1"}, # your own correlation ID
extra_query={"debug": "1"}, # appended to the URL
extra_body={"some_new_field": True}, # merged into the JSON body
)
print("4. after the with-block: client closed =", client.is_closed())1. plain call, client defaults (timeout 30 s):
-> POST https://api.openai.com/v1/responses
x-stainless-read-timeout=30.0 x-client-request-id=None body keys=['input', 'model']
2. with_options: a copy with different settings, sharing the same connection pool
-> POST https://api.openai.com/v1/responses
x-stainless-read-timeout=5.0 x-client-request-id=None body keys=['input', 'model']
original client still has timeout 30.0 | copy has 5.0
3. extra_headers / extra_query / extra_body: escape hatches for one request
-> POST https://api.openai.com/v1/responses?debug=1
x-stainless-read-timeout=30.0 x-client-request-id=order-4711-attempt-1 body keys=['input', 'model', 'some_new_field']
4. after the with-block: client closed = TrueWhen to use each:
extra_bodyis for genuinely provider-specific fields the SDK's types don't include: OpenRouter'smodels,providerandplugins(5.4), a brand-new API parameter before the SDK adds it, or Gemini's settings through its OpenAI-compatibility endpoint. Don't use it to sneak past type errors on parameters the SDK does know: a typo inextra_bodyis sent straight to the server.extra_headersis for things like OpenAI'sX-Client-Request-Id, your own correlation ID. OpenAI's API reference says it "isn't added automatically" and must be ASCII, at most 512 characters and unique per request (otherwise the request returns 400). It lets you find a request in OpenAI's logs even when it timed out before you got a response ID back (8.6).with_optionsis for a different timeout or retry policy on one code path, such as a fast autocomplete versus a slow report.
7.4 Timeouts and retries: a preview#
Every SDK retries some failures and times out slow requests, but the defaults differ, and 03.8 owns the details. What you need now:
openai 3.42.1 |
anthropic 2.4.0 |
google-genai 2.34.0 |
|
|---|---|---|---|
| Default timeout | 600 s (connect 5 s) | 600 s (connect 5 s) | none: the SDK creates its HTTP client with timeout=None, so a stuck request can wait indefinitely. Set HttpOptions(timeout=...) (milliseconds); the SDK then also sends it to the server as an X-Server-Timeout header, in seconds |
| Default retries | 2 (so up to 3 attempts) | 2 | models.*: none; interactions.*: retried by default |
| Retried on | connection errors, timeouts, 408, 409, 429, 5xx | the same, including 529 (overloaded) | only what HttpRetryOptions lists (when enabled: 408, 429, 500, 502, 503, 504) |
Google's troubleshooting page says the Python SDK retries transient errors automatically, but in 2.34.0 client.models.* makes exactly one attempt unless you pass retry_options, which is why the production-minded sample in 6.7 sets it. Set explicit timeouts sized for each use case: a 10-minute default is right for a long report and wrong for an autocomplete box.
7.5 Client lifecycle: create once, reuse, close#
An SDK client owns a connection pool: open HTTPS connections to the provider, kept alive between requests. Opening a new connection costs a DNS lookup (turning the host name into an IP address), a TCP handshake and a TLS handshake (setting up the encryption) (often 50–300 ms, more across continents), and re-reading certificates. With one long-lived client, only the first request pays that cost.
Practical rules:
- One client per provider (and per distinct configuration) for the whole process. Need a different timeout? Use
with_options(7.3), which shares the pool. - The clients are safe to share between threads, because the underlying HTTP clients are designed for concurrent use. Async clients belong to one event loop: create them inside the loop that uses them (03.9).
- Close clients you create for a short task. Use a context manager,
with OpenAI() as client:orwith anthropic.Anthropic() as client:, which closes the pool when the block ends (the output above showsclient.is_closed()becomingTrue), or callclient.close()yourself.genai.Clientsupports both too:with genai.Client() as client:andclient.close(), plusawait client.aio.aclose()for its async side. For a long-running server, close the clients at shutdown. - Keep a reference to a
genai.Clientwhile you use it. Its__del__method closes its connection pool. When you writegenai.Client().models.generate_content(...), the unnamed client object is freed as soon as.modelshas been looked up, before the request is sent:
"""A throwaway client: Python can destroy (and close) it before the call even starts."""
from google import genai
try:
# The Client object has no name, so it is freed as soon as `.models` has been looked up.
# Its __del__ closes the HTTP connection pool that `.models` still needs.
genai.Client().models.generate_content(model="gemini-3.8-flash", contents="Hi")
except RuntimeError as e:
print("RuntimeError:", e)
client = genai.Client() # keep a reference for as long as you use the client
response = client.models.generate_content(model="gemini-3.8-flash", contents="Hi")
print("with a reference:", response.candidates[0].finish_reason)The same one-liner style works with OpenAI() and anthropic.Anthropic() (it's merely wasteful), which is why this trap surprises people moving between SDKs.
7.6 Sync vs async: a preview#
Every SDK has an async version for programs that run many calls at once, such as web servers handling many users, or batch jobs: AsyncOpenAI, AsyncAnthropic, and client.aio on genai.Client. The methods are the same, but you await them. Here's one async call against the local stand-in:
"""A first async call (preview of 03.9), against the local stand-in."""
import asyncio
from openai import AsyncOpenAI
async def main() -> None:
# async with: the connection pool is closed when the block ends
async with AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama") as client:
response = await client.responses.create( # await: other tasks can run meanwhile
model="qwen2.5:0.5b", input="In one sentence, what is an API?", max_output_tokens=100
)
print(response.status, "|", response.output_text)
asyncio.run(main())completed | An API stands for Application Programming Interface, which allows software applications to interact with each other and communicate over the internet or within their systems.With one call, async gains nothing. Its value appears when you run tens or hundreds of calls concurrently, while each one spends seconds waiting on the network. 03.9 covers async clients, bounded concurrency and batch APIs properly. The async primer itself is in Module 01B.
Part 8: Anatomy of a response#
8.1 Where everything lives#
Every response object has the same handful of things you need, in different places. This table is the map. What each finish reason means is in 02.5, 4.5, and what each usage field counts is in 02.2, 6.6:
| OpenAI Responses | OpenAI Chat Completions | Anthropic Messages | Gemini generate_content |
Gemini Interactions | OpenRouter (Chat Completions) | |
|---|---|---|---|---|---|---|
| Object | Response |
ChatCompletion |
Message |
GenerateContentResponse |
Interaction |
ChatCompletion |
| ID | .id (resp_...) |
.id (chatcmpl-...) |
.id (msg_...) |
.response_id |
.id |
.id |
| Resolved model | .model |
.model |
.model |
.model_version |
.model |
.model (the model that actually served, after any fallback) |
| Output | .output: a list of items (message with output_text/refusal parts, reasoning, function_call, ...) |
.choices[i].message (.content, .refusal, .tool_calls) |
.content: a list of blocks (text, thinking, tool_use, ...) |
.candidates[i].content.parts (text, function_call, thought parts, ...) |
.steps: a list (model_output with content, thought, function_call, ...) |
.choices[i].message |
| Why it stopped | .status + .incomplete_details.reason |
.choices[i].finish_reason |
.stop_reason (+ .stop_sequence, .stop_details) |
.candidates[i].finish_reason; if the prompt was blocked, .prompt_feedback.block_reason and no candidates |
.status |
.choices[i].finish_reason (+ native_finish_reason in model_extra) |
| Usage | .usage |
.usage |
.usage |
.usage_metadata |
.usage |
.usage (+ cost in model_extra) |
| Request ID | ._request_id (from the x-request-id header) |
._request_id |
._request_id (from the request-id header) |
no request-ID header is documented; .response_id is the ID you can log |
.id (the interaction's own ID, not an HTTP request ID) |
X-Generation-Id response header |
| Convenience text | .output_text |
— | — | .text |
.output_text |
— |
8.2 Real objects from the local stand-in#
The best way to learn these shapes is to look at real ones. This script makes tiny calls to the local stand-in (Ollama, through the OpenAI and Anthropic SDKs) and dumps the SDK objects as JSON:
"""Dump real response objects from the local stand-in, to see their true shapes."""
import anthropic
from openai import OpenAI
QUESTION = "Name one primary colour. One word."
# openai SDK -> Ollama
oai = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
response = oai.responses.create(model="gpt-6-luna", input=QUESTION, max_output_tokens=20)
print("### OpenAI Response (Responses API)")
print(response.model_dump_json(indent=2))
# anthropic SDK -> Ollama
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
message = claude.messages.create(model="claude-haiku-5-5", max_tokens=20,
messages=[{"role": "user", "content": QUESTION}])
print("### Anthropic Message")
print(message.model_dump_json(indent=2))### OpenAI Response (Responses API)
{
"id": "resp_871844",
"access_programs": null,
"created_at": 1793759422.0,
"error": null,
"incomplete_details": null,
"instructions": null,
"metadata": {},
"model": "gpt-6-luna",
"object": "response",
"output": [
{
"id": "msg_205126",
"content": [
{
"annotations": [],
"text": "Red",
"type": "output_text",
"logprobs": []
}
],
"role": "assistant",
"status": "completed",
"type": "message",
"phase": null
}
],
"parallel_tool_calls": true,
"temperature": 1.0,
"tool_choice": "auto",
"tools": [],
"top_p": 1.0,
"background": false,
"completed_at": 1793759422.0,
"conversation": null,
"max_output_tokens": 20,
"max_tool_calls": null,
"moderation": null,
"previous_response_id": null,
"prompt": null,
"prompt_cache_diagnostics": null,
"prompt_cache_key": null,
"prompt_cache_options": null,
"prompt_cache_retention": null,
"reasoning": null,
"safety_identifier": null,
"service_tier": "default",
"status": "completed",
"text": {
"format": {
"type": "text"
},
"verbosity": null
},
"tool_usage": null,
"top_logprobs": 0,
"truncation": "disabled",
"usage": {
"input_tokens": 37,
"input_tokens_details": {
"cache_write_tokens": null,
"cached_tokens": 0
},
"output_tokens": 2,
"output_tokens_details": {
"reasoning_tokens": 0
},
"total_tokens": 39
},
"user": null,
"presence_penalty": 0,
"frequency_penalty": 0,
"store": false
}
### Anthropic Message
{
"id": "msg_b294516f7401af773696eb56",
"container": null,
"content": [
{
"citations": null,
"text": "Yellow.",
"type": "text"
}
],
"diagnostics": null,
"model": "claude-haiku-5-5",
"role": "assistant",
"stop_details": null,
"stop_reason": "end_turn",
"stop_sequence": null,
"type": "message",
"usage": {
"cache_creation": null,
"cache_creation_input_tokens": null,
"cache_read_input_tokens": null,
"inference_geo": null,
"input_tokens": 37,
"output_tokens": 3,
"output_tokens_details": null,
"server_tool_use": null,
"service_tier": null,
"speed": null
}
}The two Gemini objects have no local stand-in, so they come from a separate sample:
"""Dump the two Gemini response objects (hosted only: needs GEMINI_API_KEY)."""
from google import genai
from google.genai import types
QUESTION = "Name one primary colour. One word."
gemini = genai.Client() # reads GEMINI_API_KEY from the environment
g = gemini.models.generate_content(model="gemini-3.8-flash", contents=QUESTION,
config=types.GenerateContentConfig(max_output_tokens=20))
print("### Gemini GenerateContentResponse (None fields left out)")
print(g.model_dump_json(indent=2, exclude_none=True, exclude={"sdk_http_response"}))
interaction = gemini.interactions.create(model="gemini-3.8-flash", input=QUESTION,
generation_config={"max_output_tokens": 20})
print("### Gemini Interaction (None fields left out)")
print(interaction.model_dump_json(indent=2, exclude_none=True))
print("model_extra:", sorted((interaction.model_extra or {}).keys()))The OpenAI and Anthropic objects above are real SDK objects, so their field names and nesting are what you'll see from the hosted APIs. Their values come from a small local model behind compatibility layers, so read them with care. Where a hosted provider fills in fields the stand-in leaves empty or fakes:
modelis just an echo. The stand-in reportsgpt-6-lunaandclaude-haiku-5-5because those are the names it was asked for (they're aliases forqwen2.5:0.5b, 12.3). A hosted provider reports the model that actually ran, and Gemini fillsmodel_version. Never present stand-in output as a real provider's.- IDs have provider formats on hosted APIs (
resp_plus a long string;msg_01...; a Geminiresponse_id). store: falseon the Responses object is the stand-in's value; on OpenAI,storedefaults to true.- Usage details are sparse: real responses fill
reasoning_tokensfor reasoning models, cache counters when prompt caching applies, Anthropic'sservice_tier,inference_geoandoutput_tokens_details.thinking_tokens, and Gemini'sthoughts_token_count. The stand-in's counts are approximate. - Safety and metadata: hosted Gemini fills
safety_ratings,create_timeandmodel_status, and Anthropic fillsstop_detailson refusals. - The Interaction's
outputsfield is the old name.outputsis the Interactions API's old field name, replaced bysteps, so older tutorials that readoutputsare out of date. Google's changelog announced it on 6 May 2026 ("request and response schema (outputs→steps) ... [is] changing"), made the new schema the default on 26 May and removed the legacy one on 8 June. The SDK keeps unknown fields inmodel_extrarather than rejecting them, which is the subject of the next section.
8.3 SDK objects are Pydantic models#
All three SDKs build their response objects with Pydantic, the Python data-validation library (Module 01B). That gives you a consistent toolkit on every provider:
- Attribute access with type hints:
response.usage.input_tokens, and your editor autocompletes it. .model_dump()turns the object into plain dictionaries and lists, for storing in a database or a log..model_dump_json(indent=2)gives a JSON string, as above. Both acceptexclude_none=Trueto drop empty fields..model_extra: a dictionary of fields the server sent that the SDK's model doesn't declare. The SDKs accept unknown fields instead of failing, so a provider can add a field before the SDK is updated, and compatible servers can add their own. OpenRouter'susage.costis read exactly this way:(completion.usage.model_extra or {}).get("cost")(6.7).Model.model_validate(data)builds an SDK object from a dictionary, useful for tests and for re-loading stored responses (8.4 uses it).
8.4 Convenience accessors and their traps#
output_text (OpenAI Responses and Gemini Interactions) and .text (Gemini generate_content) are handy, but each hides information. These examples build SDK objects directly from documented JSON shapes (no network):
"""Convenience accessors and their traps, shown on SDK objects built from documented JSON shapes."""
from anthropic.types import Message
from google.genai import types
from openai.types.responses import Response
BASE = {"id": "resp_1", "object": "response", "created_at": 0, "model": "gpt-6-luna",
"status": "completed", "parallel_tool_calls": True, "tool_choice": "auto", "tools": []}
# 1. The model only called a tool: there is no text at all
tool_only = Response.model_validate({**BASE, "output": [
{"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "get_weather",
"arguments": '{"city": "Paris"}', "status": "completed"}]})
print("tool call only -> output_text =", repr(tool_only.output_text))
# 2. The model refused: the refusal is a different content type, so output_text skips it
refusal = Response.model_validate({**BASE, "output": [
{"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
"content": [{"type": "refusal", "refusal": "I can't help with that."}]}]})
print("refusal -> output_text =", repr(refusal.output_text))
# 3. Two text parts are glued together with no separator
two_parts = Response.model_validate({**BASE, "output": [
{"type": "message", "id": "msg_2", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": "First part.", "annotations": []},
{"type": "output_text", "text": "Second part.", "annotations": []}]}]})
print("two parts -> output_text =", repr(two_parts.output_text))
# 4. Anthropic: content[0] is not always text (thinking and tool_use blocks come first)
msg = Message.model_validate({
"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"stop_reason": "end_turn", "stop_sequence": None,
"usage": {"input_tokens": 12, "output_tokens": 40},
"content": [{"type": "thinking", "thinking": "The user wants...", "signature": "sig"},
{"type": "text", "text": "Paris."}]})
print("Anthropic content[0].type =", msg.content[0].type, "| has .text:", hasattr(msg.content[0], "text"))
print("Anthropic text blocks =", repr("".join(b.text for b in msg.content if b.type == "text")))
# 5. Gemini: .text is None when the only part is a function call
gem = types.GenerateContentResponse.model_validate({"candidates": [{
"finish_reason": "STOP",
"content": {"role": "model", "parts": [{"function_call": {"name": "get_weather", "args": {"city": "Paris"}}}]}}]})
print("Gemini function call only -> .text =", repr(gem.text), "| .function_calls[0].name =", gem.function_calls[0].name)Warning: there are non-text parts in the response: ['function_call'], returning concatenated text result from text parts. Check the full candidates.content.parts accessor to get the full model response.
tool call only -> output_text = ''
refusal -> output_text = ''
two parts -> output_text = 'First part.Second part.'
Anthropic content[0].type = thinking | has .text: False
Anthropic text blocks = 'Paris.'
Gemini function call only -> .text = None | .function_calls[0].name = get_weatherThe first line is the SDK's warning for sample 5. It goes to the logging system (standard error), not to print, so captured with 2>&1 into a file it can land at the top as above, while in a terminal it usually appears just before the last line.
The traps, in order:
- Empty when the model only called a tool.
output_textis''and Gemini's.textisNone, yet the call succeeded and was billed. Code that treats empty text as "the model said nothing" misses the tool call (03.5). - Refusals are hidden. A refusal arrives as a
refusalcontent part, whichoutput_textskips, so you get''withstatus: "completed". Check for refusal parts (Responses),message.refusal(Chat Completions),stop_reason == "refusal"(Anthropic) or the finish reason (Gemini) explicitly (02.10, 14.3). - Several parts are silently joined, with no separator, which can glue sentences or JSON fragments together.
- Anthropic has no convenience accessor, and
content[0].textbreaks as soon as athinkingortool_useblock comes first. Select blocks bytype. - Gemini warns only in the log. The warning above went to the logging system, which most apps don't display. Gemini's
.textalso returns only the first candidate, and skips thought parts. The Interactionsoutput_textis computed by the SDK from the trailing run of text in the final model-output steps only.
What this means for you: use the accessors for quick scripts and for logging. In production code, check the status or finish reason first, then read the typed output items or blocks you expect, as 6.7 does.
8.5 Raw responses and headers#
The parsed object doesn't include HTTP headers, but some headers are worth reading: request IDs, processing time, and rate-limit counters. Each SDK gives you access:
openaiandanthropic: put.with_raw_responsebefore the method. You get a raw response object with.headers,.status_codeand.parse()(which returns the usual parsed object)..with_streaming_responseis the equivalent for streamed bodies, used as a context manager.google-genai: everyGenerateContentResponsecarriessdk_http_response, with.headers.
The mock "servers" below return documented header names with made-up values:
"""Reading HTTP headers: with_raw_response (openai, anthropic) and sdk_http_response (google-genai).
The 'servers' are mocks returning documented header names with made-up values."""
import anthropic
import httpx
import httpx2
from google import genai
from google.genai import types
from openai import OpenAI
# --- OpenAI ------------------------------------------------------------------------------
OPENAI_HEADERS = {"x-request-id": "req_8f2c51d0a7", "openai-processing-ms": "412",
"openai-version": "2020-10-01", "openai-organization": "org-example",
"x-ratelimit-remaining-requests": "4999", "x-ratelimit-remaining-tokens": "3999712"}
OPENAI_BODY = {"id": "resp_123", "object": "response", "status": "completed", "model": "gpt-6-luna",
"output": [{"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": "Hello!", "annotations": []}]}]}
oai = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda req: httpx2.Response(200, json=OPENAI_BODY, headers=OPENAI_HEADERS))))
raw = oai.responses.with_raw_response.create(model="gpt-6-luna", input="Hi")
response = raw.parse() # the normal Response object
print("openai status:", raw.status_code, "| x-request-id:", raw.headers["x-request-id"],
"| _request_id:", response._request_id)
print(" processing ms:", raw.headers["openai-processing-ms"],
"| remaining tokens:", raw.headers["x-ratelimit-remaining-tokens"], "| text:", response.output_text)
# --- Anthropic ---------------------------------------------------------------------------
ANTHROPIC_HEADERS = {"request-id": "req_011CVexample", "anthropic-ratelimit-requests-remaining": "3999",
"anthropic-ratelimit-output-tokens-remaining": "399000"}
ANTHROPIC_BODY = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"content": [{"type": "text", "text": "Hello!"}], "stop_reason": "end_turn",
"stop_sequence": None, "usage": {"input_tokens": 8, "output_tokens": 3}}
claude = anthropic.Anthropic(api_key="sk-ant-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda req: httpx2.Response(200, json=ANTHROPIC_BODY, headers=ANTHROPIC_HEADERS))))
raw_msg = claude.messages.with_raw_response.create(
model="claude-haiku-5-5", max_tokens=100, messages=[{"role": "user", "content": "Hi"}])
message = raw_msg.parse()
print("anthropic request-id:", raw_msg.headers["request-id"], "| _request_id:", message._request_id,
"| requests remaining:", raw_msg.headers["anthropic-ratelimit-requests-remaining"])
# --- Gemini: every response carries its HTTP headers in sdk_http_response -------------------
GEMINI_BODY = {"responseId": "Fh4kZ-example", "modelVersion": "gemini-3.8-flash",
"candidates": [{"content": {"role": "model", "parts": [{"text": "Hello!"}]},
"finishReason": "STOP"}]}
gemini = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=httpx.MockTransport(
lambda req: httpx.Response(200, json=GEMINI_BODY)))))
g = gemini.models.generate_content(model="gemini-3.8-flash", contents="Hi")
headers = g.sdk_http_response.headers if g.sdk_http_response else {}
print("gemini response_id:", g.response_id, "| model_version:", g.model_version,
"| header names:", sorted(headers or {}))openai status: 200 | x-request-id: req_8f2c51d0a7 | _request_id: req_8f2c51d0a7
processing ms: 412 | remaining tokens: 3999712 | text: Hello!
anthropic request-id: req_011CVexample | _request_id: req_011CVexample | requests remaining: 3999
gemini response_id: Fh4kZ-example | model_version: gemini-3.8-flash | header names: ['content-length', 'content-type']Headers worth knowing, as of November 2026:
| Provider | Request ID | Timing | Rate limits (03.8) |
|---|---|---|---|
| OpenAI | x-request-id |
openai-processing-ms (server-side processing time) |
x-ratelimit-limit-*, x-ratelimit-remaining-*, x-ratelimit-reset-* for requests and tokens, plus project-level variants |
| Anthropic | request-id, plus anthropic-organization-id and anthropic-workspace-id (which organization and workspace the request ran in) |
— | anthropic-ratelimit-{requests,tokens,input-tokens,output-tokens}-{limit,remaining,reset}, retry-after |
| Gemini | No request-ID header is documented; the response_id field is what you can log (it identifies the response, not the HTTP request) |
— | None documented |
| OpenRouter | X-Generation-Id |
— | None on successful responses; only OpenRouter's own 429s carry X-RateLimit-* |
OpenAI also returns openai-version (the REST API version, 2020-10-01) and openai-organization. Comparing openai-processing-ms with the time your code measured tells you how much latency was the model and how much was the network and queueing.
8.6 Request IDs: log them every time#
A request ID is the provider's unique identifier for one HTTP request. When something goes wrong (a strange answer, a timeout, a billing question), it's the first thing provider support asks for, and the only reliable way to find your request in their logs. Log it on every call, success or failure:
- OpenAI:
response._request_id(fromx-request-id); on errors,exc.request_id. Add your ownX-Client-Request-Id(7.3) to find requests that never returned. - Anthropic:
message._request_id(fromrequest-id); on errors,exc.request_id, and the error body'srequest_idfield. Also keep theanthropic-workspace-idandanthropic-organization-idresponse headers (viawith_raw_response, 8.5): they answer "which workspace did this call run in?", the question 3.2 raised. - Gemini: no request-ID header is documented, so log what identifies the response:
response.response_idforgenerate_contentandinteraction.idfor Interactions. These are resource IDs, not HTTP request IDs, so quote them to support as "response ID", not "request ID". - OpenRouter: the
X-Generation-Idheader (viawith_raw_response); look the call up later withGET /api/v1/generation?id=....
The leading underscore in _request_id doesn't mean "private, don't use" here: it's the SDKs' documented way to avoid clashing with a response field called request_id. The OpenAI README: "All object responses in the SDK provide a _request_id property which is added from the x-request-id response header." Structured logging of these fields is covered in 03.10.
Part 9: Versioning: three things people confuse#
"Which version are you on?" has three different answers for an LLM integration, and mixing them up causes real outages. The API version is the contract of the HTTP interface. The model version is which set of weights answers. The SDK version is which release of the Python library you installed. Each changes on its own schedule.
9.1 API versions#
| Provider | How the API is versioned (as of November 2026) |
|---|---|
| OpenAI | No version header to send. The path carries /v1, and changes are additive within it; new behaviour arrives as new endpoints (Responses) or new parameters. Responses report the REST API version in an openai-version header (2020-10-01) |
| Anthropic | A required anthropic-version request header. The current version is 2026-10-21; 2023-06-01 and the original 2023-01-01 are still listed in the version history. The SDK sends the version that was current at its major release: anthropic 2.0.0 and later send 2026-10-21, while 1.x sent 2023-06-01 |
| Gemini | The URL path: v1 (stable) or v1beta (newer features). google-genai 2.34.0 defaults to v1beta, and 3.0.0 (6 November 2026) changes the Gemini Developer API default to v1 (4.5); choose either with types.HttpOptions(api_version=...) or the GOOGLE_GENAI_API_VERSION environment variable (3.x). The Interactions API is generally available in v1; some features (context caching, the Live API, service tiers and others) exist only in v1beta |
| OpenRouter | The /api/v1 path. It follows the OpenAI and Anthropic formats it imitates |
What Anthropic's 2026-10-21 changed. Within a version, Anthropic promises to keep existing inputs and outputs working; breaking changes get a new version. Version 2026-10-21 made these breaking changes on the Messages API (and on token counting and batches):
temperature,top_pandtop_kare removed. Sending any of them "returns a 400 error, even at the parameter's default value". (02.5, Part 6 explains why frontier models are dropping sampling controls.)- A
documentblock directly in anassistantmessage returns 400. - A
textblock in ausermessage with a non-emptycitationsarray returns 400. - Several Admin API fields were renamed, and on Amazon Bedrock the new version works only with Claude 4.7 and later models.
The same release of the SDKs also changed client behaviour: keys sent as Authorization: Bearer, and one credential per client (7.1).
You can see which version the SDK sends in the wire capture in 9.2.
9.2 Beta features#
Providers ship new features as betas before making them generally available:
- Anthropic uses beta headers:
anthropic-beta: feature-name-YYYY-MM-DD, several separated by commas. In the SDK, callclient.beta.messages.create(..., betas=[...]), which adds the header and uses beta types. An unknown beta name, or one your organization can't access, returns 400. Betas that graduate (structured outputs, the Files API, token counting and PDFs all have) no longer need the header. - OpenAI ships new features as new parameters and endpoints, sometimes labelled beta in the docs. The old
OpenAI-Betaheader was used by the Assistants API and the Realtime beta, both now gone. - Gemini marks preview features and models in the docs; many live only in
v1beta.
See the version and beta headers on the wire, and Gemini's version in the URL:
"""API versions and beta flags on the wire (mock transports: nothing is sent)."""
import anthropic
import httpx
import httpx2
from google import genai
from google.genai import types
def h2(request: httpx2.Request) -> httpx2.Response:
print(f" {request.method} {request.url.path} anthropic-version={request.headers.get('anthropic-version')}"
f" anthropic-beta={request.headers.get('anthropic-beta')}")
return httpx2.Response(200, json={"content": []})
def h1(request: httpx.Request) -> httpx.Response:
print(f" {request.method} {request.url}")
return httpx.Response(200, json={"candidates": []})
claude = anthropic.Anthropic(api_key="sk-ant-test", http_client=httpx2.Client(transport=httpx2.MockTransport(h2)))
print("Anthropic, stable API (the version is fixed by the SDK major version):")
claude.messages.create(model="claude-haiku-5-5", max_tokens=100, messages=[{"role": "user", "content": "Hi"}])
print("Anthropic, a beta feature through client.beta with betas=[...]:")
claude.beta.messages.create(model="claude-haiku-5-5", max_tokens=100, messages=[{"role": "user", "content": "Hi"}],
betas=["context-management-2025-06-27"])
print("Gemini, SDK default API version, then v1 pinned through HttpOptions:")
for version in (None, "v1"): # None = the SDK default
client = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(
api_version=version, httpx_client=httpx.Client(transport=httpx.MockTransport(h1))))
client.models.generate_content(model="gemini-3.8-flash", contents="Hi")Anthropic, stable API (the version is fixed by the SDK major version):
POST /v1/messages anthropic-version=2026-10-21 anthropic-beta=None
Anthropic, a beta feature through client.beta with betas=[...]:
POST /v1/messages anthropic-version=2026-10-21 anthropic-beta=context-management-2025-06-27
Gemini, SDK default API version, then v1 pinned through HttpOptions:
POST https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent
POST https://generativelanguage.googleapis.com/v1/models/gemini-3.8-flash:generateContentThe first Gemini line shows 2.34.0's default. On google-genai 3.x the default is v1, so both lines would show /v1/ (from the 3.0.0 release notes; not re-run here), and api_version="v1beta" is how you ask for the old behaviour.
What this means for you: betas can change or disappear with short notice, so keep beta usage in one place in your code, record which beta flags each feature depends on, and re-check them when you upgrade the SDK.
9.3 Model versions#
The model ID decides which weights answer, and it's versioned separately from the API: claude-haiku-5-5 is a fixed snapshot, while some IDs are aliases that move to newer snapshots. Aliases versus snapshots, lifecycle stages, notice periods and pinning are all covered in 02.9, Part 8. The API-level points to add:
- Log
response.model(or Gemini'smodel_version), which reports what actually ran, not just what you asked for. - Keep model IDs in configuration with the API version and SDK version they were tested with (02.9, 8.3).
- A new model can need a new API version or SDK. New parameters (effort levels, new tool types) often arrive with, or only work on, a new SDK release.
9.4 SDK versions#
The Python SDKs use semantic versioning: MAJOR.MINOR.PATCH. A patch fixes bugs, a minor version adds features (usually support for new API parameters), and a major version may break your code. Recent majors show what "break" means:
| Release | Date | What broke |
|---|---|---|
openai 3.0.0 |
12 Aug 2026 | httpx replaced by httpx2; TLS via the OS trust store (4.5) |
anthropic 2.0.0 |
21 Oct 2026 | API version 2026-10-21 by default (sampling parameters removed), Bearer auth, one credential per client |
google-genai 2.34.0 (a minor release) |
29 Oct 2026 | Dropped Python 3.10 |
google-genai 3.0.0 |
6 Nov 2026 | httpx2 required and default (httpx no longer installed); Gemini Developer API default version v1 instead of v1beta, which hides model aliases such as gemini-flash-latest; a changed CodeExecutionResultStep.result type in Interactions (4.5). The samples were written against 2.34.0 |
The google-genai 2.34.0 row is a reminder that even minor releases can drop support for old Python versions. The practical rules are in 4.4: lock, read changelogs, upgrade deliberately with tests.
Part 10: The Models APIs as calls#
Reference
Each provider has a Models API that lists the models your key can use. 02.9, 4.10 tables what fields each returns (context limits, lifecycle, capabilities). This part is about the calls themselves, and especially pagination.
10.1 Listing models on each provider#
"""List the models your key can use, on each provider (and page through the results)."""
import anthropic
from dotenv import load_dotenv
from google import genai
from openai import OpenAI
load_dotenv()
# OpenAI: GET /v1/models returns everything in one unpaginated list
for model in OpenAI().models.list():
if model.id.startswith("gpt-6"):
print("openai ", model.id, "| owned_by:", model.owned_by)
# Anthropic: paginated (limit 1-1000, default 20). Iterating fetches further pages for you.
claude = anthropic.Anthropic()
for info in claude.models.list(limit=20):
print("anthropic", info.id, "|", info.display_name, "|", info.lifecycle)
# ...or page by hand with the cursor fields
page = claude.models.list(limit=2)
print("anthropic first page:", [m.id for m in page.data], "| has_more:", page.has_more)
if page.has_more and page.last_id:
nxt = claude.models.list(limit=2, after_id=page.last_id)
print("anthropic next page: ", [m.id for m in nxt.data])
# Gemini: a Pager; iterating it requests the next page when needed
gemini = genai.Client() # keep a reference while the pager is in use (7.5)
for m in gemini.models.list(config={"page_size": 50}):
if m.name and "gemini-3.8" in m.name:
print("gemini ", m.name, "| supported_actions:", m.supported_actions)openai gpt-6-astra | owned_by: system
openai gpt-6.1-sol | owned_by: system
openai gpt-6.1-terra | owned_by: system
openai gpt-6-luna | owned_by: system
anthropic claude-fable-5-2 | Claude Fable 5.2 | active
anthropic claude-fable-5-1 | Claude Fable 5.1 | active
anthropic claude-opus-5-5 | Claude Opus 5.5 | active
anthropic claude-sonnet-5-5 | Claude Sonnet 5.5 | active
anthropic claude-haiku-5-5 | Claude Haiku 5.5 | active
anthropic first page: ['claude-fable-5-2', 'claude-fable-5-1'] | has_more: True
anthropic next page: ['claude-opus-5-5', 'claude-sonnet-5-5']
gemini models/gemini-3.8-flash | supported_actions: ['generateContent', 'countTokens', 'createCachedContent', 'batchGenerateContent']The three pagination styles:
| Provider | Pagination | In the SDK |
|---|---|---|
| OpenAI | None: one list of everything | client.models.list() returns a SyncPage[Model]; iterate it |
| Anthropic | Cursor: limit (1–1000, default 20), after_id / before_id; responses carry has_more, first_id, last_id |
Iterating the page fetches further pages automatically; or follow last_id by hand. A lifecycle=[...] filter is also available |
| Gemini | Page tokens: page_size, page_token |
client.models.list(config={"page_size": N}) returns a Pager; iterate it, or call pager.next_page() |
| OpenRouter | Opt-in limit (default 500, max 1000) and offset, with links.next |
Plain HTTP, or the openai SDK's models.list() (10.2) |
Against the local stand-in, models.list() returns Ollama's local models (with the :latest tags of your aliases) and ignores limit. The Gemini model list has no local stand-in (12.4), so it needs a real key.
10.2 OpenRouter's public catalogue, live#
OpenRouter's catalogue needs no key, so this one runs for real. Its docs say pagination "is opt-in: when both are omitted, the full list is returned and links.next is null":
"""OpenRouter's model catalogue is public: list it with no key, with httpx and with the openai SDK."""
import httpx
from openai import OpenAI
URL = "https://openrouter.ai/api/v1/models"
# 1. Plain HTTP. Pagination is opt-in: send limit/offset to get pages, and follow links.next.
page = httpx.get(URL, params={"limit": 2, "offset": 0}, timeout=30).json()
print("page of", len(page["data"]), "| next:", page["links"]["next"])
# Without limit/offset you get the whole catalogue in one response
catalogue = {m["id"]: m for m in httpx.get(URL, timeout=30).json()["data"]}
print("models in the catalogue:", len(catalogue))
for model_id in ("openai/gpt-6-luna", "anthropic/claude-haiku-5.5", "google/gemini-3.8-flash"):
m = catalogue[model_id]
print(f" {model_id:28s} context={m['context_length']:>9,} "
f"modalities_in={m['architecture']['input_modalities']}")
# 2. The openai SDK: the same endpoint, typed objects. It needs *some* api_key string,
# but this endpoint ignores it. OpenRouter-only fields land in model_extra.
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key="unused-for-this-endpoint")
for model in client.models.list(): # iterating a SyncPage
if model.id == "anthropic/claude-haiku-5.5":
extra = model.model_extra or {}
print(type(model).__name__, model.id, "| owned_by:", model.owned_by,
"| context_length (extra):", extra.get("context_length"))page of 2 | next: /api/v1/models?offset=2&limit=2
models in the catalogue: 454
openai/gpt-6-luna context=1,050,000 modalities_in=['file', 'image', 'text']
anthropic/claude-haiku-5.5 context=1,000,000 modalities_in=['text', 'image', 'file']
google/gemini-3.8-flash context=1,048,576 modalities_in=['text', 'image', 'video', 'file', 'audio']
Model anthropic/claude-haiku-5.5 | owned_by: None | context_length (extra): 1000000Notice the compatibility lesson from 5.5 in miniature: the openai SDK parses OpenRouter's catalogue into its Model type, but owned_by (an OpenAI field) is None, and OpenRouter's own fields such as context_length sit in model_extra. Lesson 02.9, 4.9 explores this catalogue's fields further.
Part 11: Cloud-platform clients#
Reference
Many companies reach models through the cloud they already use: Microsoft Azure, Amazon Web Services or Google Cloud (02.9, 5.3 explains why). The SDKs support this with alternative client classes or options:
| Platform | Models | Client (as of November 2026) |
|---|---|---|
| Azure OpenAI in Microsoft Foundry | OpenAI models | The standard OpenAI() client with base_url="https://<resource>.openai.azure.com/openai/v1/" (the "v1 API"); Microsoft: "OpenAI() client is used instead of AzureOpenAI()" and "api-version is no longer a required parameter". Auth by Azure key, or an Entra ID token provider passed as api_key (a callable). The older AzureOpenAI class still exists for the dated api-version APIs |
| Microsoft Foundry | Claude | AnthropicFoundry(resource=..., api_key=...) or azure_ad_token_provider= |
| Amazon Bedrock | Claude | AnthropicBedrockMantle for new projects: "Use AnthropicBedrockMantle for new projects; AnthropicBedrock remains for existing applications using the Bedrock InvokeModel API." AWS SigV4 request signing (AWS's standard way of authenticating API calls) from the standard AWS credential chain, or a bearer token |
| Claude Platform on AWS | Claude, with the first-party API's features | AnthropicAWS (beta): an API key sent as Bearer, or SigV4; a region is required |
| Amazon Bedrock | OpenAI models (gpt-oss and others) | The openai SDK's provider=openai.providers.bedrock(...) option |
| Google Cloud (Gemini Enterprise Agent Platform, formerly Vertex AI) | Gemini | genai.Client(enterprise=True, project=..., location=...); vertexai=True is the legacy name for the same flag |
| Google Cloud (Google-managed Claude) | Claude | AnthropicVertex(project_id=..., region=...), with Application Default Credentials |
| Google Cloud (Anthropic-managed Claude) | Claude | AnthropicGoogleCloud (beta), with Application Default Credentials plus a workspace ID |
The first call, through each of the four main routes:
"""The same first call through cloud platforms (needs each cloud's credentials and model access)."""
import os
from anthropic.lib.bedrock import AnthropicBedrockMantle # also exposed as anthropic.AnthropicBedrockMantle
from anthropic.lib.vertex import AnthropicVertex
from dotenv import load_dotenv
from google import genai
from openai import OpenAI
load_dotenv()
QUESTION = "In one sentence, what is an API?"
# Azure OpenAI in Microsoft Foundry, v1 API: the standard OpenAI client, a different base URL
# (AZURE_OPENAI_RESOURCE and AZURE_OPENAI_API_KEY are names invented for this sample, not an SDK convention)
azure = OpenAI(
base_url=f"https://{os.environ['AZURE_OPENAI_RESOURCE']}.openai.azure.com/openai/v1/",
api_key=os.environ["AZURE_OPENAI_API_KEY"], # or an Entra ID token provider (a callable)
)
r = azure.responses.create(model="my-gpt-6-luna-deployment", input=QUESTION) # YOUR deployment name
print("azure ", r.output_text)
# Claude on Amazon Bedrock: AWS credentials from the usual chain (env vars, profile, IAM role)
bedrock = AnthropicBedrockMantle(aws_region=os.environ["AWS_REGION"])
m = bedrock.messages.create(model="anthropic.claude-sonnet-5-5", max_tokens=1024, # Bedrock's model ID
messages=[{"role": "user", "content": QUESTION}])
print("bedrock ", "".join(b.text for b in m.content if b.type == "text"))
# Claude on Google Cloud (Google-managed): Application Default Credentials
vertex = AnthropicVertex(project_id=os.environ["GOOGLE_CLOUD_PROJECT"],
region=os.environ["GOOGLE_CLOUD_LOCATION"])
m = vertex.messages.create(model="claude-sonnet-5-5", max_tokens=1024,
messages=[{"role": "user", "content": QUESTION}])
print("vertex ", "".join(b.text for b in m.content if b.type == "text"))
# Gemini on Gemini Enterprise Agent Platform (formerly Vertex AI): IAM instead of an API key
gcp = genai.Client(enterprise=True, project=os.environ["GOOGLE_CLOUD_PROJECT"], location="global")
g = gcp.models.generate_content(model="gemini-3.8-flash", contents=QUESTION)
print("agent platform", g.text)azure An API is a set of rules that lets one software application request data or services from another.
bedrock An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other.
vertex An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other.
agent platform An API is a set of rules and protocols that allows different software applications to communicate and exchange data.Three notes on this sample. The environment variable names AZURE_OPENAI_RESOURCE and AZURE_OPENAI_API_KEY are invented for the sample (the OpenAI SDK reads neither), so use whatever your deployment tooling provides. The two Claude calls name Sonnet 5.5 rather than this module's default Haiku; those are the IDs 02.9, 5.5 lists for these platforms. It isn't a recommendation, and it isn't a typo. A platform's model list, regions and ID spellings are its own, so look your ID up in the platform's model catalogue and swap in a model you have access to. And the whole sample is illustrative, because it needs each cloud's credentials and model access.
What changes on a cloud platform, and what doesn't:
| Changes | Stays the same |
|---|---|
| Authentication: the cloud's identity system (IAM, identity and access management: roles, service accounts, Entra ID) instead of, or alongside, provider API keys | The request and response shapes: the same messages.create, responses.create and generate_content calls and objects |
Model IDs: Bedrock prefixes Claude IDs (anthropic.claude-sonnet-5-5); Azure uses your deployment name, not the model name |
Finish reasons, usage fields and content blocks |
| Feature availability: new models and beta features often arrive later; check each platform's model page | The SDK's retries, timeouts and error classes (with a few platform-only ones, such as Anthropic's ServiceUnavailableError on Bedrock and Vertex) |
| Endpoints, regions, quotas, prices and retirement dates set by the platform (02.9, 5.5) | Everything you learned in Parts 6–8 |
| Who processes your data, which matters for compliance (02.9, 9.3) |
Part 12: Practise for free: a local stand-in#
Deep-dive
You don't need a key, or any money, to learn the mechanics in this module. A small model running on your own laptop, behind a server that speaks the providers' API formats, lets the OpenAI and Anthropic SDK samples run for real. Gemini is the exception: Ollama doesn't speak Gemini's API, so the google-genai samples need a hosted key (12.4). This is Module 03's free practice path.
flowchart LR
subgraph code ["Your lesson code (unchanged)"]
o["openai SDK"]
a["anthropic SDK"]
g["google-genai SDK"]
end
o -->|"OPENAI_BASE_URL=http://localhost:11434/v1"| ol["Ollama :11434<br/>OpenAI- and Anthropic-compatible API"]
a -->|"ANTHROPIC_BASE_URL=http://localhost:11434"| ol
g -.->|"no local stand-in: needs GEMINI_API_KEY"| gh["Hosted Gemini API"]
ol --> m[("qwen2.5:0.5b<br/>plus aliases such as gpt-6-luna")]12.1 Install Ollama and a small model#
Ollama is a free tool that downloads and runs open-weight models locally and serves them over HTTP on port 11434. It speaks the OpenAI-compatible API (Chat Completions and Responses) and an Anthropic-compatible Messages API.
- Install it from ollama.com/download (an app on macOS and Windows; on Linux, the install script shown on that page, which is a
curl ... | shcommand, so read the caution in 4.1 first and look at the script before you run it). On macOS and Windows the app starts the server for you. On Linux the installer usually sets up a background service; if the check below can't connect, runollama servein a separate terminal and leave it open. - Download a small model.
qwen2.5:0.5bis about 400 MB of disk and runs on almost any laptop, with no GPU:
ollama pull qwen2.5:0.5b
curl http://localhost:11434/api/version # check the server is running (Windows PowerShell: curl.exe ...)The check prints a small JSON object with the Ollama version (this module's outputs were produced on 0.32.5). ollama list shows the models you have.
A 0.5-billion-parameter model is tiny and its answers are often clumsy, but that doesn't matter here: this module teaches the mechanics of calls (request building, response parsing, streaming, tool-call round trips, errors), which work the same regardless of model quality. Larger local models and local serving in depth are covered in Module 11C.
12.2 Point the SDKs at it explicitly#
The openai and anthropic SDKs talk to Ollama when you change base_url. The key is required by the SDKs but ignored by Ollama:
"""Free practice: the openai SDK against a local Ollama model (Responses and Chat Completions)."""
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1", # Ollama's OpenAI-compatible API
api_key="ollama", # required by the SDK, ignored by Ollama
)
response = client.responses.create(
model="qwen2.5:0.5b", input="In one sentence, what is an API?", max_output_tokens=100
)
print("Responses: ", response.status, "|", response.output_text)
completion = client.chat.completions.create(
model="qwen2.5:0.5b",
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
max_tokens=100, # Ollama honours max_tokens and silently ignores max_completion_tokens (see 12.5)
)
print("Chat Completions:", completion.choices[0].finish_reason, "|", completion.choices[0].message.content)Responses: completed | An API (Application Programming Interface) allows two software systems to communicate and interact with each other through defined protocols.
Chat Completions: stop | An API stands for Application Programming Interface, which refers to the network of software applications and services that allow users to communicate with each other or use third-party programs in their systems."""Free practice: the anthropic SDK against a local Ollama model."""
import anthropic
client = anthropic.Anthropic(
base_url="http://localhost:11434", # no /v1: the SDK adds /v1/messages itself
api_key="ollama",
)
message = client.messages.create(
model="qwen2.5:0.5b",
max_tokens=100,
messages=[{"role": "user", "content": "In one sentence, what is an API?"}],
)
text = "".join(block.text for block in message.content if block.type == "text")
print("Messages:", message.stop_reason, "|", text)Messages: end_turn | An API stands for Application Programming Interface, which is a system of rules and guidelines that defines how software applications interact with each other to enable communication between them.Note the base URLs: http://localhost:11434/v1 for the openai SDK (which appends /responses or /chat/completions), but http://localhost:11434 for the anthropic SDK (which appends /v1/messages). OpenRouter-style code works too: it's the openai SDK, so point its base_url at http://localhost:11434/v1.
"""Do output caps truncate on the local stand-in? (Ollama 0.32.5)"""
import anthropic
from openai import OpenAI
from openai.types.chat import ChatCompletionMessageParam
QUESTION = "In one sentence, what is an API?"
messages: list[ChatCompletionMessageParam] = [{"role": "user", "content": QUESTION}]
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
c = client.chat.completions.create(model="qwen2.5:0.5b", messages=messages, max_completion_tokens=5)
print("chat max_completion_tokens=5 ->", c.choices[0].finish_reason, "| tokens:", c.usage.completion_tokens if c.usage else None)
c = client.chat.completions.create(model="qwen2.5:0.5b", messages=messages, max_tokens=5)
print("chat max_tokens=5 ->", c.choices[0].finish_reason, "| tokens:", c.usage.completion_tokens if c.usage else None)
r = client.responses.create(model="qwen2.5:0.5b", input=QUESTION, max_output_tokens=16)
print("responses max_output_tokens=16 ->", r.status, "| incomplete_details:", r.incomplete_details,
"| tokens:", r.usage.output_tokens if r.usage else None)
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
m = claude.messages.create(model="qwen2.5:0.5b", max_tokens=5, messages=[{"role": "user", "content": QUESTION}])
print("anthropic max_tokens=5 ->", m.stop_reason, "| tokens:", m.usage.output_tokens)chat max_completion_tokens=5 -> stop | tokens: 24
chat max_tokens=5 -> length | tokens: 5
responses max_output_tokens=16 -> completed | incomplete_details: None | tokens: 16
anthropic max_tokens=5 -> max_tokens | tokens: 5Ollama's Chat Completions route ignores max_completion_tokens (the parameter OpenAI recommends) and obeys only the older max_tokens. Its Responses route generates only 16 tokens for max_output_tokens=16, but reports status == "completed" with no incomplete_details, where OpenAI reports incomplete with reason max_output_tokens. Its Anthropic route does obey max_tokens (stop_reason == "max_tokens"). So the finish-reason checks in 6.7 can't be exercised against a cap locally: use a mock transport that returns the documented truncated response (03.8 and 03.10 show how).
12.3 Run the lesson code unchanged#
Explicit base_url lines are fine for practice scripts, but you'll want to run the lesson's samples, which use real model IDs and default clients, exactly as written. Two steps make that work.
1. Create aliases, so that every real model ID the module uses resolves to your local model. ollama cp makes a new name for the same weights, instantly and with no extra disk space. Module 03 uses these 19 IDs (the OpenAI and Anthropic ones, plus the OpenRouter spellings of those and of the Gemini and Llama models; a few appear in only one lesson; claude-fable-5-1 is Anthropic's legacy Fable model, kept because 03.7's price table and tests still price it), so alias them all now and you'll never meet "model not found" in the middle of a lesson:
for id in gpt-6-luna gpt-6.1-terra gpt-6.1-sol gpt-6-astra \
claude-haiku-5-5 claude-sonnet-5-5 claude-opus-5-5 claude-fable-5-2 claude-fable-5-1 \
openai/gpt-6-luna openai/gpt-6.1-sol \
anthropic/claude-haiku-5.5 anthropic/claude-sonnet-5.5 anthropic/claude-opus-5.5 \
google/gemini-3.8-flash google/gemini-3.5-flash-lite google/gemini-4-argon \
meta-llama/llama-3.3-70b-instruct openrouter/auto; do
ollama cp qwen2.5:0.5b "$id"
done
ollama list # the new names appear next to qwen2.5:0.5b, all with the same IDOn Windows PowerShell the same loop is:
$ids = "gpt-6-luna", "gpt-6.1-terra", "gpt-6.1-sol", "gpt-6-astra",
"claude-haiku-5-5", "claude-sonnet-5-5", "claude-opus-5-5", "claude-fable-5-2", "claude-fable-5-1",
"openai/gpt-6-luna", "openai/gpt-6.1-sol",
"anthropic/claude-haiku-5.5", "anthropic/claude-sonnet-5.5", "anthropic/claude-opus-5.5",
"google/gemini-3.8-flash", "google/gemini-3.5-flash-lite", "google/gemini-4-argon",
"meta-llama/llama-3.3-70b-instruct", "openrouter/auto"
foreach ($id in $ids) { ollama cp qwen2.5:0.5b $id }2. Redirect the SDKs with environment variables in the terminal where you run the samples (not in your .env, so you can't confuse it with real keys):
export OPENAI_BASE_URL=http://localhost:11434/v1 OPENAI_API_KEY=ollama
export ANTHROPIC_BASE_URL=http://localhost:11434 ANTHROPIC_API_KEY=ollama$env:OPENAI_BASE_URL = "http://localhost:11434/v1"; $env:OPENAI_API_KEY = "ollama"
$env:ANTHROPIC_BASE_URL = "http://localhost:11434"; $env:ANTHROPIC_API_KEY = "ollama"Now the minimal samples from 6.1 and 6.3, saved under the file names from Part 6, run unchanged:
uv run python openai_responses_min.py
uv run python anthropic_min.pyAn API (Application Programming Interface) allows different applications to communicate with each other through a common interface.
An API stands for Application Programming Interface, providing a method of communication between different software applications and systems that use the same underlying technology.Because load_dotenv() doesn't override variables that are already set (3.4), these exports win over any real keys in your .env. Open a fresh terminal (or unset the four variables; in PowerShell, Remove-Item Env:OPENAI_BASE_URL, Env:OPENAI_API_KEY, Env:ANTHROPIC_BASE_URL, Env:ANTHROPIC_API_KEY) to go back to the real providers. OpenRouter samples set base_url="https://openrouter.ai/api/v1" explicitly, so the environment variable can't redirect them; change that line to http://localhost:11434/v1 to practise, or read the URL from your own setting, such as os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1").
12.4 Gemini has no local stand-in#
Ollama doesn't speak Gemini's API format. It serves the OpenAI formats and the Anthropic Messages format, but not generateContent, Gemini streaming, Gemini token counting or the Interactions API. So there is no free local way to run the google-genai SDK for real, and no way to see real Gemini output without a Gemini key.
That affects every google-genai sample in this module: generate_content, streaming, response_schema, chats, count_tokens and the Interactions API. Each is hosted-only: it needs GEMINI_API_KEY and is not run locally, and its output is illustrative or described in prose, never pasted from a local run. You have three options:
- Use a hosted Gemini key. Set a spend limit where the provider offers one and use the free tier where it is available to you (3.3 covers limits). Keep
GEMINI_API_KEYin your.envas in 3.4, and ifGOOGLE_API_KEYis also set it shadowsGEMINI_API_KEY(7.2). - Read the Gemini samples as illustrative. The code follows the SDK's documented shapes, but you take the output on trust. The response tables in 8.1 show the shapes to expect.
- Write your own tiny mock for tests. A hand-written mock server or a set of recorded responses can stand in for Gemini in your own test suite, which is how 03.8 and 03.10 exercise failure paths that the hosted API can't produce on demand.
Anthropic structured output has the same limit for a different reason. Ollama's Anthropic endpoint accepts output_config but ignores it (12.5), so samples that depend on output_config.format being enforced are hosted-only too. Anthropic samples that don't use output_config still run on Ollama directly.
12.5 What works locally, and what doesn't#
Later lessons link here for "what the stand-in can't do". What it runs for real, as of November 2026 (Ollama 0.32.5):
| Works | Doesn't work (or isn't real) |
|---|---|
OpenAI SDK: Responses and Chat Completions, .parse() structured output, streaming, tool calls, base64 image input only with a vision model (see below) |
Stored responses (previous_response_id, conversation), truncation, logprobs, n, image URLs |
| Anthropic SDK: Messages, the streaming helper, tool use, base64 image blocks only with a vision model | count_tokens (on Ollama itself), batches, caching, citations, PDF/document blocks, metadata |
(nothing for google-genai: hosted-only, see 12.4) |
Every Gemini sample: generate_content, streaming, response_schema, chats, count_tokens, the Interactions API, the Gemini model list, explicit caches, batches and the Files API need GEMINI_API_KEY and a hosted Gemini API. Anthropic output_config (structured output) is hosted-only too, because Ollama ignores it |
| SDK behaviour: request building, response parsing, exception classes for errors such as an unknown model (404) | Rate-limit headers, request-ID headers, real usage numbers (counts are approximate), provider-only features (OpenRouter routing and costs, Files APIs, server tools) |
The rest of this section groups the known quirks by what they mean for you. Every item is something a lesson sample or exercise can hit.
Accepted but silently ignored (no error, and no effect: the worst kind, because a local pass proves nothing about the parameter):
| What you send | What the stand-in does |
|---|---|
max_completion_tokens on Chat Completions |
Ignored. Only max_tokens is honoured (12.2) |
strict on tools or schemas, tool_choice |
Ignored (the model may still call the tool) |
Anthropic output_config (structured output) |
Ignored by Ollama's Anthropic endpoint, so enforced structured output through it is hosted-only |
Responses json_object |
Accepted, ignored: the model may wrap its JSON in a Markdown fence |
previous_response_id, conversation, Anthropic thread |
Accepted, ignored: nothing is stored, so the model doesn't see earlier turns (03.2) |
service_tier, speed |
Ignored: no tier fields come back (03.9) |
cache_control, prompt-cache settings |
No caching happens: cache counters stay 0 or None (03.7) |
background=True |
Accepted, answered as completed at once, but you can't poll it afterwards (404 from Ollama) |
Rejected with an error (the stand-in is stricter than, or different from, the hosted API):
| What you send | What happens |
|---|---|
Any reasoning effort other than "none", or any Anthropic thinking config |
400: "does not support thinking" (qwen2.5 can't think). Keep the parameters in lesson code, but smoke-test without them |
A JSON Schema pattern |
400: "failed to parse grammar" (03.4) |
Anthropic max_tokens: 0 (a cache pre-warm) |
400, so those samples can't run locally (03.7) |
An Anthropic citations field |
Rejected. document blocks are ignored |
| An unknown model ID | 404 from Ollama |
Missing endpoints, which answer 404 (use mock transports to test code that calls them):
| Endpoint | Where it's used |
|---|---|
All batch endpoints: OpenAI files.create(purpose="batch") and batches.*, Anthropic messages.batches.*, Gemini batches.*, OpenRouter /batches |
03.9 |
OpenAI token counting (POST /v1/responses/input_tokens), and Anthropic count_tokens on Ollama itself |
03.7 |
Stored responses: GET /v1/responses/{id} |
03.2 |
Gemini endpoints of any kind (the models list, caches.*, generate_content): Ollama doesn't serve them, so they need a hosted key |
10.1, 03.7 |
OpenRouter GET /api/v1/generation, and the admin and usage endpoints |
03.7 |
Files APIs, PDF input_file |
03.6 |
Behaves differently from the hosted APIs (the call succeeds, but the result isn't what production sends):
| Behaviour | Why it matters |
|---|---|
A Responses call or stream that hits the output cap ends with status == "completed" (or a response.completed event), where OpenAI reports incomplete and response.incomplete |
You can't exercise truncation handling against a cap locally (12.2); use a mock transport (03.8, 03.10) |
Ollama's tool IDs start with call_ (Anthropic's start with toolu_), and it streams tool arguments as one fragment; it can give a text item and a tool call the same output_index, which makes the openai stream helper raise "Duplicate response output index" |
Local runs don't exercise argument accumulation: use mocks (03.5, 03.3) |
| The small model sometimes leaves out required tool arguments | Validate arguments in code, as you would for a hosted model |
| Ollama doesn't check how tool calls pair with tool results | A local pass is not a valid request. Ollama accepts broken tool histories that hosted APIs reject with a 400 (03.5) |
GET /v1/models lists IDs with a :latest suffix (gpt-6-luna:latest) |
Don't compare them with the ID you asked for |
| Ollama serves requests almost one at a time (four concurrent requests gave about 20% more throughput) | Demonstrate concurrency with a mock transport that sleeps (03.9) |
No cost or cache data: OpenRouter has no usage.cost or cache_write_tokens; Anthropic cache fields and diagnostics stay 0 or None; OpenAI cached_tokens stays 0 |
Cost tracking needs mocks or a hosted run (03.7) |
Lessons in this module say "not supported locally" where a sample needs a hosted feature, and use mock transports (1.3) to show those features' behaviour instead.
12.6 Where the stand-in differs from hosted models#
So you never mistake it for the real thing:
- Answer quality. A 0.5B model is far weaker than any hosted model: it misreads instructions, invents facts and formats JSON badly. Don't judge prompts by it, and don't evaluate on it (Module 10A).
- Model identity.
response.modelechoes the alias you asked for (12.3). - Parameters. Ollama accepts, and silently ignores, many parameters that hosted APIs enforce or reject (12.5 lists them). A sample that runs locally can still fail on the real API: for example, Ollama accepts
temperatureon its Anthropic endpoint, while Anthropic's API returns a 400, and it accepts tool-call histories that OpenAI would reject. The type checker and the provider's docs are your check, not the stand-in. - Output caps.
max_completion_tokensis ignored and a capped Responses call reportscompleted, so the stand-in never shows you a truncated answer the way a hosted API does (12.2). Test truncation handling with a mock transport. - Reasoning.
qwen2.5:0.5bdoesn't think, so reasoning tokens are zero and some reasoning settings are rejected locally (for examplereasoning_effort="low"returns400 ... does not support thinking, while"none"is accepted). - Gemini and
output_config. Gemini samples and Anthropicoutput_configstructured output are hosted-only, so nothing here has shown you real Gemini output or enforced Anthropic structured output (12.4). - Metadata. No request IDs, no rate-limit headers, approximate token counts, and default values (such as
store: false) that differ from the hosted APIs. - Speed and limits. Local latency depends on your laptop, a laptop-sized setup handles few requests at once, and there are no rate limits or bills, so the stand-in can't teach you about
429s or costs. Mock transports can (03.8).
Part 13: First-call troubleshooting#
13.1 The errors you'll hit first#
| Symptom | Likely cause | Fix | Depth |
|---|---|---|---|
| 429, 400 or 402 on your very first call, with a key you know is right | No credit, no billing, a free-tier quota or a spend limit: the usual first failure on a brand-new account, and not a code bug. The wording differs by provider and changes over time, so read the message (as of November 2026): OpenAI returns 429 with an insufficient_quota or other billing-related code ("You exceeded your current quota"), and its error guide says "Retrying billing, spend, or quota errors won't restore API access"; Anthropic documents 402 billing_error for billing or payment problems and returns 400 invalid_request_error when a spend limit you set is reached; Gemini returns 429 RESOURCE_EXHAUSTED, typically when a free-tier quota is used up, and Google's troubleshooting page also ties 400 INVALID_ARGUMENT to depleted prepay credits; OpenRouter returns 402 ("insufficient credits") |
Open the provider's billing or limits page (3.1b) and add credit, or wait for the quota to reset. A plain rate-limit 429 (no billing wording) clears after a minute, and the SDK retries it by itself. Don't retry a billing error in a loop |
3.3, 03.8 |
| 500, 503, 529 or "overloaded" | The provider's side: OpenAI 500 and 503 (server_is_overloaded), Anthropic 500 (api_error) and 529 (overloaded_error), Gemini 503 (UNAVAILABLE), OpenRouter 502 and 503 |
Nothing is wrong with your code. openai and anthropic retry twice before raising; google-genai models.* calls don't retry unless you set retry_options (7.4). Retry later with backoff, and check the provider's status page |
03.8 |
401 AuthenticationError (OpenAI: invalid_api_key, "Incorrect API key provided") |
Missing or wrong key; a stale key exported in your shell beating .env (3.4); the OpenAI key sent to OpenRouter (or vice versa); a key from the wrong project; a revoked key |
Run check_setup.py (4.6); pass the right api_key= explicitly; create a new key |
03.8 |
403 PermissionDeniedError |
The key is valid but lacks access: a model not enabled for your project or tier, an unsupported country, a workspace without permission, an OpenRouter guardrail or budget block | Check the project's model access and limits in the console; check OpenRouter guardrails. On Gemini, also make sure the key isn't an unrestricted standard key, which the API rejects (3.2) | 03.8 |
404 NotFoundError |
Model ID typo; the other provider's ID style (claude-haiku-5.5 vs claude-haiku-5-5); a retired model; a wrong base URL path (/v1 missing or doubled); a model not available on the chosen Gemini API version |
Copy the ID from the Models API (Part 10); check base_url |
03.8 |
400 BadRequestError |
A removed or unsupported parameter (temperature on Claude with API version 2026-10-21; reasoning.effort: "none" on a model that doesn't accept it); the wrong parameter name for this API family (max_tokens on Responses); missing max_tokens on Anthropic; store: true on OpenRouter's Responses API; a missing anthropic-workspace-id; malformed messages |
Read the error message: it names the field. Run the type checker on your code | 03.8 |
APIConnectionError (no HTTP response at all) |
No network, a VPN or proxy blocking the host, DNS failure, nothing listening at a local base_url, TLS certificate errors (with openai 3.x, the OS certificate store is used: install system CA certificates or set SSL_CERT_FILE, 4.5) |
Test the host with curl; check proxy settings (HTTPS_PROXY); check base_url |
03.8 |
APITimeoutError or requests that hang |
A timeout too short for the output size (or a Gemini HttpOptions(timeout=30) meaning 30 ms); or the 10-minute default left in place for a call that's stuck |
Size timeouts per use case; stream long outputs (03.3) | 03.8 |
ValueError at client creation (Anthropic) |
Two credential sources passed to one client | Pass exactly one of api_key, auth_token, credentials, config, profile |
7.1 |
RuntimeError: Cannot send a request, as the client has been closed (Gemini) |
A throwaway genai.Client() was garbage-collected (7.5), or you used a client after close() |
Keep a reference to the client | 7.5 |
Empty output_text / .text is None, with status 200 |
The model called a tool, refused, or used the whole budget on reasoning (status: "incomplete", reason max_output_tokens) |
Check the status or finish reason first; inspect the output items; raise the output cap | 8.4, 03.8 |
| Gemini uses the wrong key or project | GOOGLE_API_KEY is set and shadows GEMINI_API_KEY |
unset GOOGLE_API_KEY, or pass api_key= explicitly |
7.2 |
| Mocks don't intercept; tests hit the network | respx with the openai/anthropic 3.x/2.x SDKs (they use httpx2) |
Inject httpx2.MockTransport through http_client= |
4.5, 03.10 |
| Old example code fails on import or type check | httpx.Timeout / httpx.Client passed to openai 3.x or anthropic 2.x; positional types.Part.from_text("...") (it's keyword-only in google-genai 2.34.0: Part.from_text(text="...")) |
Use httpx2 objects; use keyword arguments |
4.5 |
13.2 Try it: three first errors, for free#
Two real errors from the local stand-in, and the documented shape of a 401 from a mock server:
"""Three first-call failures you will meet, reproduced for free."""
import httpx2
import openai
from openai import OpenAI
# 1. A model ID typo (real local server): 404 -> NotFoundError
local = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0)
try:
local.responses.create(model="qwen2.5:0.5", input="Hi") # missing the final "b"
except openai.NotFoundError as e:
print("1.", type(e).__name__, e.status_code, "-", e.message[:70])
# 2. Nothing listening at the base URL (wrong port): no HTTP response at all
wrong_port = OpenAI(base_url="http://localhost:11435/v1", api_key="ollama", max_retries=0)
try:
wrong_port.responses.create(model="qwen2.5:0.5b", input="Hi")
except openai.APIConnectionError as e:
print("2.", type(e).__name__, "-", e.message, "| cause:", type(e.__cause__).__name__)
# 3. A bad key (mock server returning OpenAI's documented 401 error shape)
ERROR_401 = {"error": {"message": "Incorrect API key provided.", "type": "invalid_request_error",
"param": None, "code": "invalid_api_key"}}
mock = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda req: httpx2.Response(401, json=ERROR_401, headers={"x-request-id": "req_demo401"}))))
try:
mock.responses.create(model="gpt-6-luna", input="Hi")
except openai.AuthenticationError as e:
print("3.", type(e).__name__, e.status_code, "| code:", e.code, "| request_id:", e.request_id)1. NotFoundError 404 - Error code: 404 - model 'qwen2.5:0.5' not found
2. APIConnectionError - Connection error. | cause: ConnectError
3. AuthenticationError 401 | code: invalid_api_key | request_id: req_demo401max_retries=0 makes each failure immediate; with the default of 2, the connection error would be retried twice first. The exception classes, their attributes and which errors are worth retrying are the subject of 03.8.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Calling an LLM needs special infrastructure." | It's an HTTPS POST of a JSON body with an auth header (1.3). The SDKs add types, retries, timeouts, streaming and error classes on top. |
| "HTTP 200 means the call worked." | Truncation, refusals, safety blocks and tool-only replies all arrive as 200. Check the status or finish reason on every response (6.7). |
| "Chat Completions is deprecated." | It's "supported indefinitely" and the industry's common format. OpenAI recommends Responses for new projects, which is a different statement. The Assistants API is the one that was shut down (26 August 2026). |
"generateContent is deprecated, so we must migrate now." |
Google calls it "legacy" but "fully supported", and it's still the only home of the Batch API, explicit caching and Python automatic function calling. Interactions is recommended for new projects. |
| "OpenAI-compatible means fully compatible." | It guarantees the core request and response shapes, not every parameter, default, error code, header or feature. Unsupported parameters may be silently ignored (5.5). |
| "It's fine to call the API from the frontend if the key is hidden in an environment variable." | Build-time environment variables are baked into the bundle. Anything shipped to a browser or app can be read. Put a backend in between (3.5). |
| "Deleting the commit removes a leaked key." | Forks, clones, caches and logs keep it. Revoke and rotate the key first (3.7). |
"load_dotenv() makes my .env the source of truth." |
It doesn't override variables already set in the environment, and it looks for .env next to your script, not in the current directory (3.4). |
| "Creating a client per request is harmless." | It discards the connection pool, adding handshakes, socket pressure and (on Gemini) the closed-client error. Create one client at start-up and reuse it (7.5). |
| "A timeout of 30 means 30 seconds everywhere." | google-genai's HttpOptions(timeout=...) is in milliseconds (7.1). |
| "All SDKs retry failures by default." | openai and anthropic retry twice; google-genai's models.* calls don't retry unless you configure it, while its interactions.* calls do (7.4). |
"output_text is the answer." |
It's empty for tool calls and refusals and joins parts silently. Check the status, then read typed output (8.4). |
| "API version, model version and SDK version are the same thing." | Three separate contracts that change independently (Part 9). |
| "If it works against the local stand-in, it works against the provider." | The stand-in proves the code path, not that the provider accepts every parameter or how the real model behaves (12.6). |
"Old httpx examples still apply to the OpenAI and Anthropic SDKs." |
Since openai 3.0.0 and anthropic 2.x they use httpx2; respx no longer intercepts their default clients (4.5). |
Key takeaways#
- An LLM call is an HTTPS
POSTof JSON with an auth header, returning JSON or an SSE stream. Each API family has its own endpoint, auth header and body shape, and a mock transport lets you see exactly what an SDK sends. - LLM APIs differ from typical REST APIs: they take seconds to minutes, bill per token (including tokens you never see), are non-deterministic, rate-limit by tokens, stream, change fast, and report many failures as HTTP 200.
- Keys are money. Use one scoped key per app and environment, service accounts for applications, spend limits and alerts,
.envplus.gitignore(with!.env.example) in development, a secret manager or workload identity in production, and a backend between any client app and the provider. On a leak, revoke first, then audit. - Set up once, properly: Python 3.11+ set at project creation (
uv init llm-apis --bare --python 3.13), thenuv addwith package names only, a committeduv.lockthat records the exact versions you got, and changelogs read before upgrades.openai3.x andanthropic2.x usehttpx2, nothttpx, andgoogle-genai3.0.0 (6 November 2026) follows them and also moves its Gemini default tov1; the samples were written against 2.34.0, so a plain install gives you the changes described in 4.5. - Choose the API family deliberately: OpenAI Responses for new OpenAI work and Chat Completions for portability; Anthropic Messages; Gemini
generate_content(this module's primary, fully supported) or Interactions (Google's recommendation for new projects); OpenRouter Chat Completions, with Responses and Messages available. - A production-minded call sets a timeout and an output cap, checks the status or finish reason, and logs the model, IDs, request ID and usage.
- Configure clients once and reuse them. Constructor arguments beat environment variables, which beat defaults. Watch
GOOGLE_API_KEYshadowingGEMINI_API_KEY, Gemini's millisecond timeouts, Anthropic's one-credential rule, and the garbage-collectedgenai.Client. - Know the response anatomy: where the ID, resolved model, output items, stop reason, usage and request ID live on each provider. SDK objects are Pydantic models with
model_dump()andmodel_extra. Convenience accessors hide tool calls and refusals. - Three kinds of versioning: API versions (
anthropic-version: 2026-10-21, Geminiv1/v1beta, none for OpenAI), model versions (snapshots and aliases), and SDK versions (semver, with breaking majors). - Practise for free with Ollama alone (OpenAI- and Anthropic-compatible). Gemini samples (and Anthropic
output_configstructured output) are hosted-only: no local stand-in exists for them. The stand-in runs the real SDK code paths, but never stands in for a real model's quality, metadata or limits.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| HTTP request / response | A message to a server (method, URL, headers, body) and its reply (status code, headers, body) |
| Endpoint | One URL path an API offers, such as /v1/responses |
| Status code | The three-digit result of an HTTP request: 2xx success, 4xx your error, 5xx server error |
| JSON | The plain-text data format used for LLM request and response bodies |
| API key | A secret string that identifies and authorizes your account or project, and lets the provider bill you |
Bearer token / Authorization header |
The standard header carrying a credential (Authorization: Bearer <key>) |
| SDK | A provider's library that builds requests and parses responses into typed objects |
| API family | A distinct request/response format with its own endpoint, such as Responses or Chat Completions |
| Responses API | OpenAI's primary API, built around typed input and output items, with optional server-side state |
| Chat Completions | OpenAI's earlier message-list API, "supported indefinitely" and copied across the industry |
| Messages API | Anthropic's API for generating text, with typed content blocks |
generate_content / generateContent |
Gemini's long-standing API, "legacy" but fully supported |
| Interactions API | Gemini's newer API (GA June 2026), recommended by Google for new projects |
| OpenAI-compatible endpoint | A non-OpenAI server that accepts the Chat Completions (and sometimes Responses) format |
| Gateway | A service such as OpenRouter that puts many providers' models behind one key and API |
| Mock transport | A fake network layer that answers an HTTP client's requests with your own code, for tests and wire captures |
| Wire capture | Recording the exact HTTP request a library sends |
httpx2 |
Pydantic's fork of httpx, used by openai 3.x and anthropic 2.x (and, from 3.0.0, by google-genai) |
| Environment variable | A named value the operating system passes to a program, used for keys and settings |
.env file / python-dotenv |
A local file of environment variables, and the library that loads it |
.env.example |
A committed template listing the variable names without values |
| Secret manager | A service that stores secrets encrypted with access control, audit logs and rotation |
| Key rotation | Replacing a key with a new one without downtime, then revoking the old one |
| Project / workspace | A container inside a provider organization with its own keys, limits and usage |
| Service account | A non-human identity for an application, with its own keys or credentials |
| Workload identity federation | Authenticating a workload with short-lived tokens from its own platform instead of a long-lived key |
| Spend limit / spend alert | A hard monthly cap that stops requests / a notification at a spending threshold |
uv / lockfile (uv.lock) |
A Python project manager / the file recording the exact versions of every dependency |
| Virtual environment | A per-project folder of installed packages |
| Semantic versioning (semver) | MAJOR.MINOR.PATCH numbering, where a new major version may break code |
| Connection pool | A client's set of reusable open connections, which avoids repeated TLS handshakes |
| Client lifecycle | Creating a client once, reusing it, and closing it when done |
with_options |
An SDK method returning a copy of the client with some settings changed |
extra_headers / extra_query / extra_body |
Per-request escape hatches to add headers, query parameters or body fields |
| Response object | The SDK's typed object for an API reply (Response, ChatCompletion, Message, GenerateContentResponse, Interaction) |
| Convenience accessor | An SDK shortcut such as output_text or .text that extracts the text from a response |
model_extra |
The Pydantic dictionary of fields a server sent that the SDK model doesn't declare |
| Raw response | The HTTP-level response (status, headers) behind a parsed object, via with_raw_response or sdk_http_response |
| Request ID | A provider's unique ID for one request, used for debugging and support |
| Generation ID | OpenRouter's ID for one call, returned in the X-Generation-Id header |
| API version | The version of an HTTP API's contract, such as anthropic-version: 2026-10-21 or Gemini's v1beta |
| Beta header | A request header that opts into a pre-release feature, such as anthropic-beta |
| Models API | The endpoint listing the models a key can use (02.9) |
| Pagination | Returning a long list in pages, with cursors or page tokens to fetch the next |
| Cloud-platform client | An SDK client class for a provider's models on Azure, AWS or Google Cloud |
| Local stand-in | A local model behind provider-compatible APIs, used to run SDK code for free |
| Ollama | A tool that runs open-weight models locally with OpenAI- and Anthropic-compatible APIs |
| Model alias (Ollama) | A second name for a local model, created with ollama cp |
All terms are also collected in the glossary.
Exercises#
Run the code from this lesson and experiment. Every exercise can be done without an API key.
- The wire (1.3): add
instructions="Answer like a pirate."to the Responses call andsystem="Answer like a pirate."to the Anthropic call. Where does each appear in the JSON body? Then addconfig=types.GenerateContentConfig(system_instruction="Answer like a pirate.")to the Gemini call. What key does it become on the wire, and in which case? (Hint: compare with the keys of the Responses and Anthropic bodies; the answer is a camelCase key holding apartslist, and 03.2 shows the full body.) - No SDK (1.4): change the raw
httpxscript to call Ollama's Responses endpoint (/v1/responses, withinputinstead ofmessages). Then extract the text from the JSON by hand, as in 1.5. Which fields differ from the Chat Completions reply? (Hint: look foroutputinstead ofchoices,statusinstead offinish_reason, andinput_tokens/output_tokensinsideusage.) - Keys (3.4): create a project with
.env,.env.exampleand the.gitignorefrom 3.4. Prove withgit check-ignore -vandgit statusthat.envis ignored and.env.exampleisn't. Then exportOPENAI_BASE_URLin your shell, put a different value in.env, and confirm which oneload_dotenv()keeps. - Setup (4.6): run
check_setup.pyfrom a different directory (cd ..thenuv run --project llm-apis python llm-apis/check_setup.py). Does it still find.env? Explain why, using what 3.4 says about whereload_dotenv()searches. (Hint: print the valueload_dotenv()returns, and remember that the search starts in the script's folder, not in your current directory.) - First calls on the stand-in (12.3): create the aliases, export the redirect variables, and run all the minimal samples from Part 6 unchanged, each saved under the file name in its first comment line (for OpenRouter, change the base URL as 12.3 describes; skip the Gemini samples: they are hosted-only, see 12.4). Then run the production-minded versions from 6.7 and compare the log lines with the illustrative output: which fields are
Nonelocally, and why? - Finish reasons (6.7, 12.2): run the probe in 12.2, then in the production-minded Chat Completions sample set
max_tokens=5(notmax_completion_tokens: say why, using the probe's output) and run it against the stand-in. Which line of the sample catches thelengthfinish reason? Then setmax_output_tokens=16in the Responses sample. Does the stand-in reportincompletethe way 02.5's table says OpenAI does? What does that tell you about testing truncation handling locally, and what would you use instead (hint: 1.3's mock transport, with a truncated body that you write)? - Configuration (7.2): extend
s7_env_precedence.pyto show that an explicitapi_key=beatsGOOGLE_API_KEYforgenai.Client, and thatOpenAI(base_url=...)beatsOPENAI_BASE_URL, without ever printing a key. - Lifecycle (7.5): write a loop that makes 20 calls to the stand-in, once creating a new
OpenAIclient inside the loop and once reusing one client. Time both withtime.perf_counter(). Is there a difference locally? Why would it be much larger against a hosted API across the internet? - Anatomy (8.2): run the dump script and find, for each provider, the field you'd log as the request ID, the field that says why generation stopped, and the field holding output tokens. Check your answers against the table in 8.1.
- Traps (8.4): add a sixth case to the accessor script: a Responses output with a
reasoningitem followed by amessage. What doesoutput_textreturn? Then write a functionfirst_text(message)for Anthropic that returnsNone(rather than raising) when there's no text block. - Models (10.2): using OpenRouter's public catalogue, list every model whose
supported_parametersincludes"tools"and whose ID starts withanthropic/. Then use?supported_parameters=toolsas a query parameter instead, and compare the counts. - Troubleshooting (13.2): reproduce two more rows of the troubleshooting table on the stand-in: a doubled
/v1in the base URL (http://localhost:11434/v1/v1), and anOpenAIclient withtimeout=0.001andmax_retries=0pointed at Ollama. What exception does each raise?
Check yourself#
- What four parts make up an HTTP request? Which header does each provider use for authentication, which provider also requires a version header, and how does Gemini's
generateContentURL differ from every other endpoint in 1.2?A method, a URL, headers and a body. The key goes in a header: OpenAI, Anthropic (SDK 2.x) and OpenRouter useAuthorization: Bearer <key>(Anthropic also still accepts the legacyx-api-key), and Gemini usesx-goog-api-key. Anthropic also requiresanthropic-version(currently2026-10-21). Gemini'sgenerateContentputs the model name in the URL path, with the action after a colon (/v1beta/models/gemini-3.8-flash:generateContent), instead of"model"in the JSON body. - Name four ways LLM APIs differ from a typical REST API, and what each means for your code.Any four of: latency of seconds to minutes (set explicit timeouts, stream); billing per token including hidden tokens (cap output, log usage); non-determinism (test with mocks, evaluate statistically); failures as HTTP 200 (check finish reasons); token-based rate limits (expect 429s); streaming (different parsing and error handling); fast-moving versions (lock SDK versions, read changelogs).
- Why must you never put an API key in a React app or a mobile app, even in an environment variable? What do you do instead? And if a key has leaked in a public repository, what are your first three actions, in order?Anything shipped to a user's device can be extracted, including build-time environment variables baked into the bundle, so anyone could use and bill your key. Put your own backend between the client and the provider; the backend holds the key. After a leak: revoke the key (and create a replacement), deploy the replacement, then audit usage on the leaked key. After that: check spend limits, clean up the source and fix the cause.
- You fixed the key in
.env, but the SDK still uses the old one. Give two possible reasons.Any two of: a variable with the same name is already exported in your shell, andload_dotenv()doesn't override it;load_dotenv()didn't find the.envbecause it searches from the script's folder, not the current directory; for Gemini,GOOGLE_API_KEYis set and takes precedence overGEMINI_API_KEY. - Why does
uv add openaifail in a fresh folder, and what fixes it? And why doesuv add google-genaifail in a project created with plainuv initon a machine whose only Python is 3.10?uv addneeds a project (pyproject.toml), and uv exits with an error if none is found. Runuv initfirst (orcdinto an existing project). Plainuv initcopiesrequires-pythonfrom the interpreter it finds, here>=3.10, andgoogle-genai2.34.0 requires Python 3.11 or newer, so the resolver reports that your project's requirements are unsatisfiable. Create the project withuv init llm-apis --bare --python 3.13(or editrequires-pythonto">=3.11"). - An old blog post configures the OpenAI client with
httpx.Timeoutand mocks it withrespx. What's wrong with that in November 2026? And what changes for your ownimport httpxcode if you upgradegoogle-genaifrom 2.34.0 to 3.0.0?openai3.x useshttpx2, nothttpx, sohttpxobjects don't match its types (usehttpx2.Timeoutor a plain number), andrespxonly patcheshttpx, so the default client's requests aren't intercepted and really go out to the network. Usehttpx2.MockTransportviahttp_client=. Withgoogle-genai3.0.0 the SDK no longer installshttpx(it depends onhttpx2and treatshttpxas an optional extra), so your ownimport httpxfails until youuv add httpx; the SDK's default client ishttpx2, and the default Gemini API version becomesv1(4.5). - When would you choose OpenAI's Chat Completions over the Responses API for a new project?When the code must also run on other OpenAI-compatible servers (OpenRouter, Ollama, vLLM, hosts), when you integrate with tools that only speak Chat Completions, or when you don't need Responses-only features. OpenAI recommends Responses for new projects otherwise.
- What does OpenAI-compatible guarantee, and name three things it doesn't?It guarantees the core request and response shapes (and usually SSE streaming). It doesn't guarantee that every parameter is honoured (some are silently ignored), the same defaults, the same error codes, the same headers and usage details, newer features such as Responses or strict structured output, or the same model behaviour.
- Your Gemini calls all time out immediately. The client was created with
HttpOptions(timeout=60). Why?HttpOptions.timeoutis in milliseconds, so 60 means 60 ms. Usetimeout=60_000for 60 seconds. - Why is creating a new SDK client inside every request handler a production bug?It throws away the connection pool each time, so every request pays new DNS, TCP and TLS handshakes, can exhaust sockets under load, re-reads configuration, and with
google-genaican hit the "client has been closed" error. Create clients once and reuse them. response.output_textis'', the status iscompleted, and you were billed. What could have happened?The model called a tool instead of writing text, or it refused (arefusalpart, whichoutput_textskips). (If the status had beenincomplete, it could also have spent the whole token budget on reasoning.)- Where do you find the request ID (or its nearest equivalent) on an OpenAI, an Anthropic, a Gemini and an OpenRouter response?OpenAI:
response._request_id(thex-request-idheader). Anthropic:message._request_id(therequest-idheader). Gemini documents no request-ID header; logresponse.response_id(generate_content) orinteraction.id, which identify the response rather than the HTTP request. OpenRouter: theX-Generation-Idresponse header. - What did Anthropic's API version
2026-10-21change that breaks a lot of older code?It removedtemperature,top_pandtop_k: sending any of them returns a 400, even at default values. (It also rejectsdocumentblocks in assistant messages and citations in user text blocks.) - You call
gpt-6-lunaon the local stand-in andresponse.modelsaysgpt-6-luna. Did GPT-6 Luna answer? And what do you see if a later lesson uses a model ID you haven't aliased?No. The stand-in echoes the requested model ID; the answer came from the localqwen2.5:0.5bmodel through an alias. An unaliased ID gives a404from Ollama;ollama cp qwen2.5:0.5b <id>fixes it. - What two security precautions does this lesson give for anything you run locally, and why? And your very first call on a brand-new account returns a
429: what should you check before you change any code?Pin and lock what you run (a lockfile with hashes stops a newly published malicious release from reaching you), and bind local servers to127.0.0.1(a server on0.0.0.0is exposed to your whole network). Also keep real provider keys out of practice setups and don't run them as shared or production services. A first-call429on a new account is usually billing, credit or a free-tier quota, so check the provider's billing and limits page before you touch the code (13.1).
Further resources#
- OpenAI, API reference overview (authentication, organization and project headers, request IDs) and Migrate to the Responses API: the official comparison of Responses and Chat Completions.
- OpenAI, Production best practices and Spend limits: keys, service accounts, rotation and spending controls.
- Anthropic, API overview, Versioning and Migrating to API version 2026-10-21.
- Anthropic, Workspaces and Python SDK: workspaces, key types, credential resolution and cloud-platform clients.
- Google, Interactions API overview, API versions and Using Gemini API keys.
- Google, python-genai (SDK repository and README: clients,
HttpOptions, environment variables, pagination) and its CHANGELOG, where the 3.0.0 breaking changes (4.5) are listed. - OpenRouter, Quickstart, App attribution and Responses API overview.
- SDK repositories and changelogs: openai-python (and its httpx2 migration notes), anthropic-sdk-python.
- Astral, uv: Working on projects, and python-dotenv.
- Ollama, OpenAI compatibility and Anthropic compatibility: exactly what the local stand-in supports.
- RFC 9110: HTTP Semantics: the specification of methods, status codes and headers, for readers who want the precise definitions.
← Module 02: How LLMs Work | Module 03 overview | 03.2 — Messages, Roles and Conversation State →