Sub topic 11
Using an official SDK instead of raw HTTP
This chapter assumes you have read the earlier chapters on the chat request and response, error codes, retries, and streaming. You should be comfortable with Python, JSON, environment variables, and the idea of HTTP status codes. The examples use the Python package for the widely adopted chat-completions request shape. Class names, parameters, and defaults differ between providers and SDK versions, so check your provider's documentation.
What an SDK does for you
An SDK (software development kit) is a client library published by the API provider. It wraps the HTTP calls you wrote by hand in earlier chapters. You call a Python method, and the library builds the URL, adds the Authorization header, serializes the JSON body, sends the request, and parses the reply.
The SDK adds nothing to the model. Every SDK call turns into the same HTTP request you could send with curl or requests. The SDK saves you from rewriting the same plumbing in every project.
The same request, with an SDK
Install the package and set the same environment variables as before.
pip install openai
export OPENAI_API_KEY="your-key-here"
export LLM_MODEL="your-model-name"Here is the request from the chapter on reading responses, rewritten with the SDK.
import os
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
response = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a token is in one sentence."},
],
)
choice = response.choices[0]
print(choice.message.content)
print("finish_reason:", choice.finish_reason)
print("usage:", response.usage)Compare this with the requests version. Four things changed:
- Authentication.
OpenAI()finds the key inOPENAI_API_KEYon its own. You never build a header, and the key never appears in your source. - Endpoint. The URL is built into
client.chat.completions.create. - Parsing. The result is an object, so you write
response.choices[0].message.contentinstead of dictionary lookups with string keys. - Errors. A failed call raises a typed exception. You do not call
raise_for_status().
The field names are the same as in the raw JSON: choices, message, finish_reason, usage. If you know the JSON shape, you can read SDK code.
Built-in timeouts and retries
Earlier you wrote a retry function with capped exponential backoff, jitter, and Retry-After handling. Most official SDKs ship the same behavior. In the OpenAI Python SDK, the client retries by default, up to 2 times, on:
- connection errors,
- 408, 409, and 429 responses,
- 5xx responses.
It uses exponential backoff with jitter and respects Retry-After. Other 4xx errors, such as 400 or 401, are not retried because repeating a bad request cannot fix it. This is the same policy you built by hand.
Defaults differ between SDKs. This one has a long default timeout, which can be 10 minutes, so set your own. You can configure the whole client or a single call.
import os
from openai import OpenAI
client = OpenAI(
timeout=30.0, # seconds, applies to every request from this client
max_retries=4, # default is 2
)
response = client.with_options(timeout=10.0, max_retries=0).chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=[{"role": "user", "content": "Say hello."}],
)
print(response.choices[0].message.content)with_options returns a copy of the client with changed settings, so the original client keeps its values. Setting max_retries=0 is useful when you have your own retry layer, for example in a job queue. Two retry layers multiply: 3 SDK attempts inside 5 queue attempts can mean 15 calls against a rate limit.
Typed exceptions
Because the SDK maps failures to exception classes, you can catch them by meaning instead of checking numbers.
import os
import openai
from openai import OpenAI
client = OpenAI(timeout=30.0)
try:
response = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=[{"role": "user", "content": "Say hello."}],
)
print(response.choices[0].message.content)
except openai.RateLimitError as err:
print("Still rate limited after SDK retries:", err.status_code)
except openai.APITimeoutError:
print("The request timed out after SDK retries.")
except openai.APIConnectionError as err:
print("Could not reach the API:", err.__cause__)
except openai.APIStatusError as err:
print("API returned an error:", err.status_code, err.response.text)The order matters. APITimeoutError is a subclass of APIConnectionError, and RateLimitError is a subclass of APIStatusError. Python uses the first matching except clause, so list the specific classes first and the general ones last.
These exceptions are raised after the SDK has used up its retries. If you see a RateLimitError, the client already waited and tried again. Waiting longer or reducing your request rate is the next step.
Streaming without parsing lines
The raw streaming example read server-sent event lines, stripped the data: prefix, watched for [DONE], and decoded JSON. The SDK does all of that and gives you an iterator of chunk objects.
import os
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=[{"role": "user", "content": "Count from one to five in words."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if not chunk.choices:
# With include_usage, the final chunk has no choices and carries token usage.
if chunk.usage:
print("\nusage:", chunk.usage)
continue
print(chunk.choices[0].delta.content or "", end="", flush=True)
print()Two details from the raw version still apply. Some chunks have an empty choices list, so check before indexing. The delta.content field can be None, for instance in the first chunk that only carries the role, so use or "". Without include_usage, a streamed response does not report token counts, so you cannot measure cost from it.
Reaching the raw HTTP data
An SDK hides HTTP details, but sometimes you need them: rate-limit headers, a request ID for a support ticket, or the exact status code on success. The OpenAI Python SDK offers a raw-response wrapper.
import os
from openai import OpenAI
client = OpenAI()
raw = client.chat.completions.with_raw_response.create(
model=os.environ["LLM_MODEL"],
messages=[{"role": "user", "content": "Say hello."}],
)
print("status:", raw.status_code)
print("request id:", raw.headers.get("x-request-id"))
response = raw.parse() # the same typed object as before
print(response.choices[0].message.content)Header names for rate-limit information vary by provider, so print raw.headers once and see what you get. Log the request ID with each failure. Providers can use it to trace a specific call.
Pointing the SDK at another provider
Many providers and local model servers copy the chat-completions request shape. For these you can keep the SDK and change where it sends requests.
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ["LLM_BASE_URL"],
api_key=os.environ["LLM_API_KEY"],
)This works only as far as the other server matches the format. Optional parameters, error bodies, streaming details, and usage fields are common places where compatible servers differ. Test the features you rely on, such as streaming and tool calls, before depending on them.
SDK versus raw HTTP: choosing
| Concern | Official SDK | Raw HTTP (`requests`) |
|---|---|---|
| Code to write | Short | Longer, you own every detail |
| Retries, backoff | Built in, configurable | You write and test them |
| Streaming | Iterator of parsed chunks | You parse event lines |
| Typed results and errors | Yes | Plain dicts and status codes |
| New API features | Usually supported soon after release, sometimes needs an upgrade | Available at once as JSON fields |
| Dependencies | Adds a package and its dependencies | Only an HTTP library |
| Debugging | Another layer between you and the wire | Full visibility |
| Provider lock-in | Tied to one provider's classes | Easy to adapt per provider |
Use the SDK for most application code. Use raw HTTP when you need a feature the SDK does not expose yet, when you work in a language without an official SDK, or when you want to see exactly what goes over the wire.
Gotchas
- Version drift. SDKs change names and behavior between major versions. Pin the version in your dependency file, for example
openai==X.Y.Zwith a version you have tested, and read the changelog before upgrading. - Hidden retries inflate latency. A call with a 30-second timeout and 2 retries can take well over a minute in the worst case. Budget for the total, not one attempt.
- Retries and cost. A retried request can be billed if the first attempt did reach the model before the connection failed. Keep
max_retriesmodest for expensive calls. - Clients are reusable. Create one client at startup and share it. Each client keeps a connection pool, so creating a new one per request wastes connections.
- Secrets still need care. Passing
api_key="sk-..."as a literal in code defeats the purpose. Let the client read it from the environment or a secrets manager.
Exercise
Your service wraps each LLM call in its own retry loop of 3 attempts, and it uses an SDK client with default settings (2 SDK retries). During a rate-limit spike, how many HTTP requests can one logical call produce, and what change would you make?
Show answer
Each of your 3 attempts can make up to 3 HTTP requests (1 original plus 2 SDK retries), so one logical call can produce up to 9 requests, which makes the rate-limit spike worse. Keep one retry layer. Either set max_retries=0 on the client and keep your own loop, or remove your loop and rely on the SDK, tuning max_retries and timeout on the client. Also set an explicit timeout.
Exercise
A streaming loop crashes with IndexError: list index out of range on the last chunk after you turned on stream_options={"include_usage": True}. Why, and how do you fix it?
Show answer
The final chunk carries only token usage, and its choices list is empty, so chunk.choices[0] fails. Check if not chunk.choices: first, read chunk.usage there if present, and continue. Also use delta.content or "" because the content can be None.