Sub topic 11
Using an official SDK instead of raw HTTP
This chapter assumes you can already send a chat request with requests, read the response fields, and set environment variables. An SDK (software development kit) is a library the provider maintains. It wraps the same HTTP endpoint you have been calling by hand.
What an SDK does for you
Every earlier example built the URL, headers, JSON body and error handling by hand. An SDK takes over these jobs:
- It builds the
Authorizationheader from your key. - It serializes the request and parses the response into objects.
- It applies default timeouts and retries on connection errors, 429 and 5xx responses.
- It raises typed exceptions instead of bare status codes.
- It handles streaming and tracks API changes.
The request on the wire is the same. The SDK does not change what the model does or what it costs.
The same request with the Python SDK
Install the package with pip install openai. The client reads OPENAI_API_KEY from the environment by default, so the key never appears in your code.
import os
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
completion = 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 = completion.choices[0]
print(choice.message.content)
print("finish_reason:", choice.finish_reason)
print("usage:", completion.usage)Compare it with the raw version. Fields are attributes (choice.message.content) instead of dictionary lookups. There is no URL, no headers and no raise_for_status().
Retries, timeouts and errors
The client has its own settings. You can set them for the whole client or for a single call.
import os
import openai
from openai import OpenAI
client = OpenAI(timeout=30.0, max_retries=3)
try:
completion = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=[{"role": "user", "content": "Say hello."}],
)
print(completion.choices[0].message.content)
except openai.RateLimitError:
print("Still rate limited after the built-in retries.")
except openai.APIConnectionError:
print("Could not reach the API.")
except openai.APIStatusError as err:
print("API returned status", err.status_code)The exceptions map to the status codes from the error chapter. Catch the specific classes first and APIStatusError last, because the specific classes are subclasses of it.
Streaming with an SDK
Passing stream=True returns an iterator of chunks. The SDK parses the server-sent events for you.
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,
)
for chunk in stream:
if chunk.choices:
print(chunk.choices[0].delta.content or "", end="", flush=True)
print()Choosing between an SDK and raw HTTP
| Concern | SDK | Raw HTTP |
|---|---|---|
| Code to write | Less | More |
| Retries and parsing | Built in | You write them |
| Dependencies | One extra package | `requests` only |
| New API features | Arrive with a library upgrade | Add fields to the JSON yourself |
| Other providers | May need a different SDK | Same technique, different URL and fields |
Use an SDK for most application code. Use raw HTTP when you need full control of every request, must avoid a dependency, or are calling a provider that has no good SDK.
Common mistakes
- Stacking your own retry loop on top of the SDK's retries. Attempts multiply. Set
max_retriesto match your design. - Leaving the SDK on its default timeout when your service has a stricter deadline.
- Not pinning the library version. A major upgrade can rename classes or fields.
- Assuming other providers' SDKs have the same method names. Many accept the chat-completions shape, but check your provider's documentation.
Exercise
Your code wraps an SDK call in a loop that retries up to 5 times. The client was created with the default max_retries. Why can a persistently failing request take far more than 5 attempts, and how do you fix it?
Show answer
Each of your 5 loop iterations triggers the SDK's own built-in retries, so the total number of HTTP attempts is the product of the two counts. Fix it by keeping only one retry layer, for example by creating the client with maxretries=0 and keeping your own loop, or by removing the loop and setting maxretries on the client.