OpenAI integration design
Start with an offline request and response
An API is a contract between your application and another service. The OpenAI Responses API accepts model input and produces response items. Imagine a server that turns fictional stockroom notes into draft labels. Keep the provider call behind an adapter: the same business logic can run against a fake client during tests and an authorized SDK client later. The mock below has a local create method, not a real SDK object; its model name is intentionally fictional. The returned dictionary is a simplified projection, not a captured provider payload. Its two printed lines show a label and invented usage. The mock does not estimate token counts from strings. No network, key or paid account is required.
class MockResponses: def create(self, **request): assert request["model"] == "offline-demo" assert request["store"] is False return {"status": "completed", "output_text": "Blue folder", "usage": {"input_tokens": 12, "output_tokens": 2}}
client = MockResponses()response = client.create(model="offline-demo", input="Name the folder: blue", instructions="Return a short label.", max_output_tokens=32, store=False)print(response["output_text"])print(response["usage"])Map the adapter to the documented SDK
The official Python SDK exposes OpenAI and client.responses.create(...); the HTTP resource is POST /v1/responses. The SDK response object exposes output_text as a convenience accessor, rather than a guarantee that every output item is text. Inspect status and typed output content before consuming it. Request fields include model, input, instructions, max_output_tokens and store. A documented model page for gpt-5.4-mini is an example of a model catalog entry, not a recommendation or guarantee of availability. Configure a currently approved exact model ID on the server and verify capabilities and retirement notices for that ID. Do not copy the mock model name into a live request.
The following is a deliberately inert SDK sketch (not executed). It shows a function definition only; invoking it requires an explicitly authorized server deployment, installed and pinned SDK, approved data, access and spend limit.
import osfrom openai import OpenAI
def request_label(approved_note): client = OpenAI(api_key=os.environ["OPENAI_API_KEY"], timeout=15.0, max_retries=0) return client.responses.create( model=os.environ["APPROVED_OPENAI_MODEL"], instructions="Return a short draft label.", input=approved_note, max_output_tokens=64, store=False)The key must never be embedded in browser JavaScript, a mobile app, Git or logs. Authenticate callers to your own server, authorize their data scope and enforce limits there. ChatGPT subscriptions and API billing are separate; any credits or access benefits depend on actual eligibility. The SDK timeout is not a complete application wall-clock deadline. store=False is not a universal zero-retention promise; review endpoint-specific data controls and organizational settings.
Structured responses and tool calls are different contracts
For Responses structured output, configure text.format (not the Chat Completions response_format field). For example, a JSON schema format can specify a name, type json_schema, schema and strict true; verify the model-supported schema subset and refusal/incomplete behavior first. Use the validation gates from Chapter 33. A function call is an output item with type function_call, a name, JSON-encoded arguments and a call_id. Your server validates arguments, checks permissions, dispatches only approved functions, and returns a function_call_output item with that call_id and an output value. This is not permission to run arbitrary commands or execute model-generated code. Preserve required response items according to the selected conversation state mode; do not confuse item IDs with call IDs. For embeddings, the documented Python surface is client.embeddings.create(model="text-embedding-3-small", input="fictional note"); this is an inert illustration, not a call. Embeddings return vectors, not prose. Check model and dimensionality before comparing vectors. Never send real documents in a demo.
Consume streaming events carefully
Streaming uses server-sent events, so the first text may arrive before the full response. The example consumes ordered dictionaries representing just one text item. response.output_text.delta contributes a fragment; response.completed ends the successful fixture. Failure, incomplete and refusal paths discard partial text. The stream may contain other events. The real adapter must handle transport errors, item and content indices, multiple output types, terminal status, schema checks and refusal content, using the current typed event definitions; this local collector is not a general SSE parser or production adapter. A missing terminal event is not success. The first result contains the combined label; the second discards a disconnected prefix. Never execute partial tool arguments or persist partial structured output as final.
def collect_text(events): # Single text item, ordered synthetic events only. parts = [] for event in events: kind = event["type"] if kind == "response.output_text.delta": parts.append(event["delta"]) elif kind == "response.completed": return "complete", "".join(parts) elif kind in ("response.failed", "response.incomplete", "error", "response.refusal.delta", "response.refusal.done"): return "review", "" else: continue return "review", ""
print(collect_text([{"type":"response.output_text.delta", "delta":"Blue "}, {"type":"response.output_text.delta", "delta":"folder"}, {"type":"response.completed"}]))print(collect_text([{"type":"response.output_text.delta", "delta":"Blue"}]))Practice: audit the integration contract
Trace the example request fields and output fields. Replace the first stream fragment with an empty string, then remove the completed event, then introduce a refusal. Predict the outputs before running the code. Design an adapter result with status, reviewed text, usage and request correlation ID; ensure an unknown status cannot become a draft. For local evaluation, retain labeled synthetic notes, expected labels and outcome categories; do not measure quality only by response success. Official documentation currently includes Evals create/run references but also announces deprecation of the Evals platform. Check migration and availability notices before relying on hosted evaluations; local fixture checks are preferred here. No live calls, hosted evaluations or tool actions are authorized in this lesson.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
OpenAI integration design quiz
Apply the offline API integration contract.
What does the offline-demo model ID represent?
Where does Responses structured output format belong?
Which identifier links a function result to the original Responses function call?
A stream ends after a text delta without completion. What is safe?
What can you conclude about retention when setting store=False?