Sub topic 1
What a provider SDK gives you
A provider SDK is the client library a model vendor publishes so you can call its API from your own code. This chapter covers what the OpenAI-style SDK does for you, where its responsibilities end, and which details cause errors in practice. Later chapters compare this baseline with frameworks, so it helps to know exactly what the baseline contains.
Prerequisites
This chapter assumes you have the following:
- Basic Python, including functions, classes, and virtual environments.
- Experience calling an LLM chat API at least once.
- Familiarity with JSON and HTTP APIs.
- An API key from the provider, stored in an environment variable rather than in your code.
To run the examples, create a virtual environment and install the library with pip install openai.
The job of an SDK
A chat model API is an HTTP endpoint. You send a JSON body and receive a JSON body. You could do this with any HTTP client. An SDK wraps that exchange so you write Python objects instead of raw requests.
An SDK typically does these things:
- Authentication. It reads the API key, usually from
OPENAI_API_KEY, and attaches it to every request as a header. - Request building. It turns Python arguments into the JSON body the endpoint expects.
- Transport. It sends the request over HTTPS, applies timeouts, and reuses connections.
- Retries. It retries some failures, such as connection errors and rate-limit responses, with a delay between attempts.
- Response parsing. It converts the JSON reply into typed objects, so you can write
response.choices[0].message.contentinstead of indexing nested dictionaries. - Errors. It raises specific exception classes for different failures.
- Streaming. It can deliver the reply in pieces as the model produces them.
- Async support. It offers an async client for concurrent calls.
Everything else is your code. The SDK does not decide what to ask, remember earlier turns, validate the content of the reply, or run tools for you.
The smallest complete call
The example below is the whole request and response with no abstraction layer in between.
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API client library is in one sentence."},
],
)
print(response.choices[0].message.content)Each part has a clear role.
OpenAI()creates the client. It holds the key, the base URL, the timeout, and the retry settings.modelnames the model that will answer.messagesis the full conversation you want the model to see. Each message has aroleandcontent.responseis a typed object.choicesis a list, and the first item holds the reply.
Messages and roles
The messages list is the only input the model has. The common roles are:
| Role | Purpose |
|---|---|
| `system` | Standing instructions that set behavior and tone. |
| `user` | What the person or your program is asking. |
| `assistant` | Earlier model replies that you send back as history. |
| `tool` | The result of a function call, covered in a later chapter. |
Some newer models accept a developer role in place of system. Check the current documentation for the model you use.
The API is stateless
The chat completions endpoint does not remember anything between calls. If you want a conversation, you must send the earlier turns again each time. The SDK will not do this for you.
from openai import OpenAI
client = OpenAI()
history = [{"role": "system", "content": "You are a concise assistant."}]
def ask(question: str) -> str:
history.append({"role": "user", "content": question})
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=history,
)
answer = response.choices[0].message.content
history.append({"role": "assistant", "content": answer})
return answer
print(ask("Name one Python web framework."))
print(ask("Name another one."))The second question only makes sense because history contains the first exchange. This has two consequences:
- Every call costs tokens for the whole history, so long conversations get more expensive.
- Each model has a context window, which is the maximum number of tokens it can read in one request. When
historygrows past it, the call fails. Trimming or summarizing history is your job.
Frameworks offer memory helpers for this. The SDK offers nothing, and that is the first place you will see boilerplate grow.
Anatomy of a response
The response object carries more than the text. These fields matter most.
| Field | What it tells you |
|---|---|
| `choices[0].message.content` | The reply text. It can be `None` when the model returned a tool call instead. |
| `choices[0].finish_reason` | Why generation stopped. |
| `usage.prompt_tokens` and `usage.completion_tokens` | Tokens billed for input and output. |
| `model` | The exact model version that served the request. |
The finish_reason field is the one beginners skip and later regret. Common values are:
stop: the model finished naturally.length: the reply hit the token limit and was cut off. Any JSON in it may be incomplete.tool_calls: the model wants you to run a function.content_filter: the provider's safety system stopped the output.
If you parse the reply without checking finish_reason, a truncated answer can look like a valid one until parsing fails.
Common parameters
You pass these to create to control the call.
temperaturecontrols randomness. Lower values give more repeatable output. Some reasoning models reject or ignore it.max_tokens, ormax_completion_tokenson newer models, caps the length of the reply.stream=Truereturns chunks as they are generated instead of one final object.nasks for several alternative replies.seedrequests best-effort repeatability. It does not guarantee identical output.
Parameter names and support differ between models and between SDK versions. This is the first sign of the provider lock-in discussed in the next chapter.
Errors, retries, and timeouts
The SDK raises exceptions from openai. The ones you will meet most often are below.
| Exception | Typical cause |
|---|---|
| `AuthenticationError` | Missing or wrong API key. |
| `RateLimitError` | Too many requests or tokens in a time window. |
| `BadRequestError` | Invalid parameters, or the request exceeds the context window. |
| `APIConnectionError` | Network failure before a reply arrived. |
| `APITimeoutError` | The request exceeded the timeout. |
| `APIStatusError` | Base class for errors that carry an HTTP status code. |
The client retries connection errors, 408, 409, 429, and 5xx responses twice by default, with exponential backoff. You can change this when you build the client.
import openai
from openai import OpenAI
client = OpenAI(max_retries=4, timeout=30.0)
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say hello."}],
)
print(response.choices[0].message.content)
except openai.RateLimitError:
print("Still rate limited after retries. Slow down or queue the work.")
except openai.APIConnectionError as err:
print("Network problem:", err)
except openai.APIStatusError as err:
print("API returned status", err.status_code)The order of the except clauses matters. RateLimitError and APIConnectionError are both more specific than APIStatusError, so they go first where they overlap with it.
Built-in retries solve transient failures only. They do not fix a BadRequestError, because sending the same bad request again gives the same answer.
Streaming
For a chat interface, waiting for the full reply feels slow. With stream=True the SDK returns an iterator of chunks.
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Count from one to five."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()Two details cause bugs here. Each chunk holds a delta, which is a fragment, not the full message. The content of a delta can be None, for example in the first and last chunks, so check it before printing. Some configurations also send a final chunk with empty choices, which is why the code tests chunk.choices first.
The request flow
The diagram shows what happens during one call and which part the SDK handles.
Where the SDK's responsibility ends
Knowing the boundary prevents wrong expectations. The SDK guarantees a well-formed request and a parsed response. It does not guarantee anything about the content.
- Meaning of the reply. The text can be wrong, off-topic, or in the wrong format. The SDK returns it as a string.
- Conversation state. You store and resend history.
- Output structure. Asking for JSON in the prompt does not make the reply valid JSON. You validate it, which the next chapters cover.
- Tool execution. The model can ask for a function call, but your code must run it.
- Multi-step workflows. Looping until a task is done is your code.
- Retrieval. The SDK has no knowledge of your documents.
- Cost control. It reports token usage but does not enforce a budget.
Common mistakes
- Hard-coding the key. Keys committed to a repository get leaked. Use an environment variable or a secrets manager.
- Assuming
contentis a string. It can beNonewhen the model calls a tool. - Ignoring
finish_reason. Alengthresult means the reply was cut off. - Forgetting history. The model does not remember the last call.
- Retrying everything. Only transient errors are worth retrying. Invalid requests are not.
- Pinning to a model alias. Names like
gpt-4o-minican move to newer versions, which can change behavior. Use dated model names when you need stable output. - Not setting a timeout. Calls without a sensible timeout can hang a web request for a long time.
What to carry forward
The SDK is a thin, reliable layer over HTTP. It handles authentication, transport, retries, and parsing. It leaves state, validation, tools, loops, and retrieval to you. The next chapter looks at how that division of work becomes painful as an application grows, and which of those pains frameworks try to remove.
Exercise
A colleague's chatbot answers the first question correctly but replies "What are you referring to?" to the follow-up "And what about its price?". The code calls client.chat.completions.create with only the latest user message each time. What is wrong, and what is the fix? Also name one field you would check to find out whether a very long reply was cut off.
Show answer
The chat completions endpoint is stateless, so the model never sees the earlier question. The fix is to keep a list of messages, append each user message and each assistant reply to it, and send the full list on every call. To detect a truncated reply, check choices[0].finish_reason. A value of length means the output hit the token limit.
Exercise
You wrap a call in try/except openai.APIStatusError and add a retry loop around it that retries on every such error up to ten times. Why is this a poor design, given what the SDK already does?
Show answer
The SDK already retries connection errors, 408, 409, 429, and 5xx responses with backoff, so the loop multiplies retries and delays. APIStatusError also covers permanent failures such as BadRequestError and AuthenticationError, which return the same error every time. A better design is to set max_retries on the client and catch specific exceptions, handling rate limits and connection failures separately from invalid requests.