Sub topic 2
Where a bare SDK starts to hurt
This chapter assumes you have used a provider SDK to send a chat request, as in the previous chapter. It also assumes you can read basic Python, including classes, exceptions, and type hints. You do not need any framework knowledge yet.
A provider SDK (software development kit) is the client library a model vendor publishes, such as openai or anthropic. It handles authentication, HTTP, and typed responses well. It stops there. Everything your application needs around a single request is yours to write. This chapter lists the places where that work piles up, so you can recognize them and later judge what a framework offers.
The SDK's job ends at one request
A single call to client.chat.completions.create(...) does one thing: it sends one request and returns one response. Real applications need more than that:
- Conversation state across many requests.
- Handling of failures such as rate limits and timeouts.
- Control over how many tokens you send and pay for.
- A consistent shape for results, so the rest of your code does not care which model answered.
- A record of what happened.
None of these is hard alone. The cost comes from writing, testing, and maintaining all of them in every project.
Each box except the SDK call is code you own.
Boilerplate: the glue you write every time
The sections below take the pieces of glue one at a time.
Conversation state
The chat API is stateless. The server remembers nothing between calls, so you resend the full message list every time. That means you store the history, append to it, and decide what to drop when it grows.
Retries and timeouts
Networks fail and providers rate-limit. The OpenAI SDK retries a few transient errors by default (two retries unless you change max_retries). Beyond that, you decide which errors to retry, how long to wait, and when to give up. The SDK does not know your latency budget.
Token accounting
Responses report usage, but nothing stops you from sending a history that exceeds the model's context window. You must count or estimate tokens yourself, then truncate or summarize.
A small example
This class handles state, trimming, retries, and usage logging for a simple chat. It sets max_retries=0 on the client so the SDK's built-in retries do not multiply with the loop below.
import time
import openai
from openai import OpenAI
client = OpenAI(timeout=30.0, max_retries=0)
MAX_TURNS = 10 # keep the last 10 user/assistant pairs
class Chat:
def __init__(self, system: str, model: str = "gpt-4o-mini"):
self.model = model
self.system = {"role": "system", "content": system}
self.turns: list[dict] = []
def ask(self, text: str) -> str:
self.turns.append({"role": "user", "content": text})
messages = [self.system, *self.turns]
response = None
for attempt in range(3):
try:
response = client.chat.completions.create(
model=self.model, messages=messages
)
break
except (openai.RateLimitError, openai.APITimeoutError):
time.sleep(2 ** attempt) # 1s, 2s, 4s
if response is None:
self.turns.pop() # do not keep a user turn that got no reply
raise RuntimeError("Model call failed after 3 attempts")
reply = response.choices[0].message.content or ""
self.turns.append({"role": "assistant", "content": reply})
self.turns = self.turns[-MAX_TURNS * 2:] # trim in whole pairs
usage = response.usage
print(f"tokens in={usage.prompt_tokens} out={usage.completion_tokens}")
return reply
chat = Chat("You are a concise assistant.")
print(chat.ask("What is a context window?"))
print(chat.ask("Why does it matter for long chats?"))This is about 35 lines for behavior that looks trivial. It is also incomplete. It does not count tokens before sending, so ten long turns can still exceed the context window. It retries rate limits blindly instead of reading the Retry-After header. It does not handle streaming. Each of these is a small project.
Provider lock-in: the same idea, different shapes
Most vendors offer similar features, but the request and response shapes differ. Code written against one SDK's types does not run against another's.
| Concern | OpenAI SDK (chat completions) | Anthropic SDK (messages) |
|---|---|---|
| System prompt | A message with `role: "system"` | A separate `system=` argument |
| Output limit | Optional `max_tokens` | Required `max_tokens` |
| Reply text | `response.choices[0].message.content` | `response.content[0].text` (a list of blocks) |
| Token usage | `usage.prompt_tokens`, `usage.completion_tokens` | `usage.input_tokens`, `usage.output_tokens` |
| Tool schema | `{"type": "function", "function": {...}}` | `{"name": ..., "input_schema": {...}}` |
| Tool arguments | JSON string in `tool_calls[i].function.arguments` | Parsed dict in a `tool_use` block's `input` |
The tool rows matter most. A later chapter covers tool calling in detail. For now, note that the shapes diverge on exactly the features that make applications interesting.
Here is the same question sent to two providers. Both functions return a plain string, so callers do not need to know which vendor answered:
from anthropic import Anthropic
from openai import OpenAI
openai_client = OpenAI()
anthropic_client = Anthropic() # reads ANTHROPIC_API_KEY
def ask_openai(system: str, question: str) -> str:
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system},
{"role": "user", "content": question},
],
)
return response.choices[0].message.content or ""
def ask_anthropic(system: str, question: str) -> str:
response = anthropic_client.messages.create(
model="claude-3-5-haiku-latest",
max_tokens=512,
system=system,
messages=[{"role": "user", "content": question}],
)
return response.content[0].text
ASKERS = {"openai": ask_openai, "anthropic": ask_anthropic}
print(ASKERS["openai"]("You are concise.", "What is lock-in?"))
print(ASKERS["anthropic"]("You are concise.", "What is lock-in?"))This adapter is small because the task is small. Once you add tools, streaming, images, and structured output, you maintain a parallel version of every feature per provider.
Lock-in has several layers
Lock-in is more than a package name. Check each layer before you decide how much it matters.
- Code lock-in. Your functions import vendor types and read vendor-specific fields. This is the easiest layer to fix, by wrapping calls in a thin interface of your own.
- Prompt lock-in. A prompt tuned for one model may behave differently on another. Changing providers means re-testing outputs, not just changing code.
- Feature lock-in. Some features have no equivalent elsewhere, such as a vendor's hosted file search or a specific caching mechanism. Using them trades portability for capability.
- Contract lock-in. Pricing, data-residency terms, and rate limits can tie you to a vendor regardless of your code structure.
A framework can help only with the first layer, and only partly. Layers two to four need testing and business decisions, whatever library you use.
A decision rule for this chapter
The pain points above are not reasons to adopt a framework by default. They are a checklist. For each one, ask whether it applies to your project right now:
- Do you keep multi-turn state? If your app makes single-shot calls, you have no history problem.
- Do you call more than one provider, or expect to? If not, an adapter layer is cost without benefit.
- Do you need retries beyond the SDK defaults? Many projects do not.
- Is the glue code spread across many files, or contained in one module?
If the glue lives in one small module you understand, the bare SDK is working fine. If you find yourself rewriting the same retry, trimming, or adapter code in several places, you have found a real problem that a shared abstraction could solve. A later chapter weighs what such abstractions cost.
Common errors
- Stacked retries. The SDK retries internally and your loop retries again, so one failure can produce many requests. Either set
max_retries=0or rely on the SDK and drop your loop. - Trimming history mid-pair. Cutting the list so it begins with an assistant message can confuse the model or be rejected by some providers. Trim in whole user/assistant pairs, as the example does.
- Keeping failed turns. If a call fails after you appended the user message, the next request will contain a user turn with no reply. Remove it on failure.
- Assuming the response shape is portable.
choices[0].message.contentdoes not exist on other vendors' responses. Isolate that access in one function. - Treating compatibility endpoints as identical. A shared URL format does not mean shared behavior on advanced features.
Exercise
The Chat class above sets max_retries=0 on the client and retries three times in its own loop. Suppose you removed max_retries=0, leaving the SDK default of 2 retries. In the worst case, how many HTTP requests could one failing ask call send, and why?
Show answer
Up to nine. The loop makes 3 attempts. Each attempt calls the SDK, which can make 1 initial request plus 2 internal retries, so 3 requests per attempt. 3 × 3 = 9 requests. This multiplies load on an already rate-limited API and makes total wait time harder to predict. Keep retry logic in one place.
Exercise
Name two things in the OpenAI-versus-Anthropic table that you would have to change if you moved the ask_openai function to Anthropic. Then name one thing that would still need testing even after those code changes.
Show answer
Any two of: the system prompt moves from a message to the system= argument; max_tokens becomes required; the reply is read from response.content[0].text instead of response.choices[0].message.content; the usage field names change. Still needing testing: prompt behavior, because the same prompt can produce different outputs, formatting, or refusals on a different model.