Skip to content

Commit ef9c908

Browse files
authored
docs: modernize openai python sdk tutorial for responses era (#56)
1 parent 88e43f6 commit ef9c908

9 files changed

Lines changed: 194 additions & 528 deletions

tutorials/openai-python-sdk-tutorial/01-getting-started.md

Lines changed: 15 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,7 @@ parent: OpenAI Python SDK Tutorial
77

88
# Chapter 1: Getting Started
99

10-
This chapter sets up the OpenAI Python SDK and walks through your first successful API call.
11-
12-
## Goals
13-
14-
- Install the SDK in an isolated environment.
15-
- Configure authentication safely.
16-
- Make your first text-generation request.
17-
- Understand response objects and common errors.
10+
This chapter gets you to a stable baseline with Responses API-first code.
1811

1912
## Install and Configure
2013

@@ -23,24 +16,19 @@ python3 -m venv .venv
2316
source .venv/bin/activate
2417
pip install --upgrade pip
2518
pip install openai
26-
```
27-
28-
Set your API key through environment variables:
29-
30-
```bash
3119
export OPENAI_API_KEY="your_api_key_here"
3220
```
3321

34-
## First Request
22+
## First Responses API Call
3523

3624
```python
3725
from openai import OpenAI
3826

3927
client = OpenAI()
4028

4129
response = client.responses.create(
42-
model="gpt-4.1-mini",
43-
input="Write a one-sentence summary of why typed APIs help in production."
30+
model="gpt-5.2",
31+
input="Summarize why idempotency matters in API design in 3 bullets."
4432
)
4533

4634
print(response.output_text)
@@ -52,54 +40,26 @@ print(response.output_text)
5240
import asyncio
5341
from openai import AsyncOpenAI
5442

55-
async def main() -> None:
43+
async def main():
5644
client = AsyncOpenAI()
57-
response = await client.responses.create(
58-
model="gpt-4.1-mini",
59-
input="Give three short tips for robust API clients."
45+
resp = await client.responses.create(
46+
model="gpt-5.2",
47+
input="Give 3 tips for reliable background jobs."
6048
)
61-
print(response.output_text)
49+
print(resp.output_text)
6250

6351
asyncio.run(main())
6452
```
6553

66-
## Response Basics
67-
68-
- `response.output_text`: convenient flattened text output.
69-
- `response.id`: request identifier useful for support/debugging.
70-
- `response.usage`: token usage metadata for cost tracking.
71-
72-
## Security and Ops Basics
73-
74-
- Never hardcode API keys in source files.
75-
- Rotate keys and use environment-specific credentials.
76-
- Add request logging with redaction for sensitive content.
77-
- Use timeouts and retries in production paths.
54+
## Baseline Production Controls
7855

79-
## Common Errors
80-
81-
| Error | Cause | Fix |
82-
|:------|:------|:----|
83-
| `401 Unauthorized` | Missing/invalid API key | Re-export key and retry |
84-
| `429 Too Many Requests` | Rate limit exceeded | Backoff + retry policy |
85-
| `400 Bad Request` | Invalid request shape | Validate payload and model name |
86-
87-
## Quick Troubleshooting
88-
89-
```python
90-
from openai import OpenAI
91-
92-
client = OpenAI(timeout=30.0)
93-
94-
try:
95-
r = client.responses.create(model="gpt-4.1-mini", input="health check")
96-
print(r.id)
97-
except Exception as exc:
98-
print(type(exc).__name__, str(exc))
99-
```
56+
- set explicit client timeouts
57+
- capture request IDs in logs
58+
- keep secrets out of source control
59+
- fail fast on invalid configuration
10060

10161
## Summary
10262

103-
You now have a working SDK installation, secure key loading, and both sync and async first calls.
63+
You now have a working SDK setup with both sync and async Responses API calls.
10464

10565
Next: [Chapter 2: Chat Completions](02-chat-completions.md)

tutorials/openai-python-sdk-tutorial/02-chat-completions.md

Lines changed: 22 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -7,101 +7,55 @@ parent: OpenAI Python SDK Tutorial
77

88
# Chapter 2: Chat Completions
99

10-
This chapter covers message-based interactions, streaming output, and tool/function calling patterns.
10+
Chat Completions remains important for existing systems even as new builds move to Responses-first flows.
1111

12-
## Message-Based Requests
12+
## Basic Message-Based Request
1313

1414
```python
1515
from openai import OpenAI
1616

1717
client = OpenAI()
1818

19-
messages = [
20-
{"role": "system", "content": "You are a concise assistant."},
21-
{"role": "user", "content": "Explain exponential backoff in two bullets."},
22-
]
23-
24-
response = client.chat.completions.create(
25-
model="gpt-4.1-mini",
26-
messages=messages,
27-
temperature=0.2,
19+
completion = client.chat.completions.create(
20+
model="gpt-5.2",
21+
messages=[
22+
{"role": "developer", "content": "Be concise and structured."},
23+
{"role": "user", "content": "Explain exponential backoff in 2 bullets."}
24+
]
2825
)
2926

30-
print(response.choices[0].message.content)
27+
print(completion.choices[0].message.content)
3128
```
3229

33-
## Streaming
30+
## Streaming Pattern
3431

3532
```python
36-
from openai import OpenAI
37-
38-
client = OpenAI()
39-
4033
stream = client.chat.completions.create(
41-
model="gpt-4.1-mini",
42-
messages=[{"role": "user", "content": "List five API reliability checks."}],
43-
stream=True,
34+
model="gpt-5.2",
35+
messages=[{"role": "user", "content": "List 5 SRE runbook checks."}],
36+
stream=True
4437
)
4538

4639
for chunk in stream:
4740
delta = chunk.choices[0].delta
4841
if delta and delta.content:
4942
print(delta.content, end="", flush=True)
50-
print()
51-
```
52-
53-
## Tool Calling Pattern
54-
55-
```python
56-
import json
57-
from openai import OpenAI
58-
59-
client = OpenAI()
60-
61-
tools = [{
62-
"type": "function",
63-
"function": {
64-
"name": "get_weather",
65-
"description": "Get weather by city",
66-
"parameters": {
67-
"type": "object",
68-
"properties": {"city": {"type": "string"}},
69-
"required": ["city"],
70-
},
71-
},
72-
}]
73-
74-
resp = client.chat.completions.create(
75-
model="gpt-4.1-mini",
76-
messages=[{"role": "user", "content": "What is the weather in Seattle?"}],
77-
tools=tools,
78-
tool_choice="auto",
79-
)
80-
81-
choice = resp.choices[0].message
82-
if choice.tool_calls:
83-
call = choice.tool_calls[0]
84-
args = json.loads(call.function.arguments)
85-
print("Tool requested:", call.function.name, args)
8643
```
8744

88-
## Recommended Practices
45+
## When to Keep Chat Completions
8946

90-
- Keep system prompts short and explicit.
91-
- Validate tool arguments before execution.
92-
- Keep tool responses structured and bounded.
93-
- Capture request IDs for incident triage.
47+
- existing production systems with stable message middleware
48+
- deeply integrated toolchains using current message schemas
49+
- migration phases where Responses API adoption is incremental
9450

95-
## Common Pitfalls
51+
## When to Prefer Responses
9652

97-
| Pitfall | Symptom | Fix |
98-
|:--------|:--------|:----|
99-
| Overlong prompts | Higher cost/latency | Summarize and chunk context |
100-
| Missing tool schema validation | Runtime errors | Strict JSON schema checks |
101-
| No streaming backpressure handling | UI freezes | Buffer and throttle rendering |
53+
- new services
54+
- multimodal and unified response flows
55+
- systems that need cleaner forward compatibility with current OpenAI platform direction
10256

10357
## Summary
10458

105-
You can now implement chat flows with streaming and function calls.
59+
You can now support legacy/interoperable message workflows while planning Responses-first migration.
10660

10761
Next: [Chapter 3: Embeddings and Search](03-embeddings-search.md)

tutorials/openai-python-sdk-tutorial/03-embeddings-search.md

Lines changed: 18 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ parent: OpenAI Python SDK Tutorial
77

88
# Chapter 3: Embeddings and Search
99

10-
Embeddings convert text into vectors so you can perform semantic retrieval for RAG and search.
10+
Embeddings power retrieval quality in most production RAG systems.
1111

1212
## Create Embeddings
1313

@@ -16,71 +16,37 @@ from openai import OpenAI
1616

1717
client = OpenAI()
1818

19-
texts = [
20-
"How to rotate API keys safely",
21-
"Rate limits and retry policies",
22-
"How to design a deployment checklist",
19+
docs = [
20+
"Retry transient failures with exponential backoff.",
21+
"Use idempotency keys for side-effecting writes.",
22+
"Track p95 and p99 latency separately."
2323
]
2424

2525
emb = client.embeddings.create(
2626
model="text-embedding-3-small",
27-
input=texts,
27+
input=docs,
2828
)
2929

3030
vectors = [row.embedding for row in emb.data]
3131
print(len(vectors), len(vectors[0]))
3232
```
3333

34-
## Simple Similarity Search
35-
36-
```python
37-
import math
38-
from openai import OpenAI
39-
40-
41-
def cosine(a, b):
42-
dot = sum(x * y for x, y in zip(a, b))
43-
na = math.sqrt(sum(x * x for x in a))
44-
nb = math.sqrt(sum(y * y for y in b))
45-
return dot / (na * nb + 1e-12)
46-
47-
client = OpenAI()
48-
49-
docs = [
50-
"Use exponential backoff for transient failures",
51-
"Store credentials in env vars and rotate them",
52-
"Benchmark latency and tail percentiles",
53-
]
54-
55-
query = "How should I handle temporary API errors?"
56-
57-
all_vectors = client.embeddings.create(model="text-embedding-3-small", input=docs + [query]).data
58-
59-
doc_vectors = [x.embedding for x in all_vectors[:-1]]
60-
query_vec = all_vectors[-1].embedding
61-
62-
scores = [(i, cosine(query_vec, dv)) for i, dv in enumerate(doc_vectors)]
63-
for i, s in sorted(scores, key=lambda t: t[1], reverse=True):
64-
print(round(s, 4), docs[i])
65-
```
66-
67-
## Retrieval Pipeline Notes
34+
## Retrieval Pipeline Blueprint
6835

69-
- Chunk by meaning, not fixed bytes only.
70-
- Store metadata (source, timestamp, section).
71-
- Re-rank top candidates when quality matters.
72-
- Track retrieval hit quality over time.
36+
1. chunk source docs with semantic boundaries
37+
2. generate embeddings and store vectors + metadata
38+
3. retrieve top-k candidates by similarity
39+
4. re-rank or filter by business constraints
40+
5. pass compact context to generation layer
7341

74-
## Troubleshooting
42+
## Quality Controls
7543

76-
| Issue | Cause | Fix |
77-
|:------|:------|:----|
78-
| Poor matches | Bad chunking or noisy docs | Improve segmentation and cleaning |
79-
| High cost | Embedding everything repeatedly | Cache vectors and incremental updates |
80-
| Slow retrieval | No ANN index | Use a vector DB or optimized index |
44+
- maintain versioned chunking strategy
45+
- keep source timestamps for freshness checks
46+
- evaluate retrieval quality with labeled benchmark queries
8147

8248
## Summary
8349

84-
You can now generate embeddings and implement semantic retrieval.
50+
You now have the core pieces to build and evaluate a robust embeddings-backed retrieval system.
8551

86-
Next: [Chapter 4: Assistants API](04-assistants-api.md)
52+
Next: [Chapter 4: Agents and Assistants](04-assistants-api.md)

0 commit comments

Comments
 (0)