Public contracts
This reference describes guarantees, limitations and intentional differences of
the current Erlang SDK. Use API.md for parameters, modes and defaults,
HELPERS.md for composed workflows, and the
API mapping for public methods and source links.
TRANSPORT.md covers architecture and developer build commands.
The behavioral reference is OpenAI Python SDK 3.52.0, pinned to
311924f055110122991cc23b988a1836793551a1.
Implementation, local/reference checks and positive live coverage are distinct.
Contents
- Reference scope and OpenAPI differences
- Lifetime, ownership and cleanup
- Configuration and precedence
- Requests, URLs and transport security
- Values, presence and serialization
- Bytes, decoding and limits
- Timeouts and retries
- Event streams
- Pagination
- Multipart sources and replay
- Authentication
- Structured parsing
- Resource-specific behavior
- Webhook verification
- Raw Realtime WebSockets
- Remaining limitations
Reference scope and OpenAPI differences
The pinned SDK contract is retained where it differs from the reviewed OpenAPI
snapshot (SHA-256 dafa58d27d20c67c4c479a463599929a386cbf11bb2a04ec91f073a10abab944).
The static comparison covered 224 explicitly enumerated operations, not every
public API, nested schema or response contract. It is not a full OpenAPI audit
or a claim of complete conformance. The deprecated API exclusion
is a separate release-scope decision.
| Erlang method / field | Reviewed OpenAPI snapshot | Pinned Python 3.52.0 | Current Erlang contract |
|---|---|---|---|
openai_conversations:create/2,3 — safety_identifier |
Field is present in CreateConversationBody |
No named parameter | No named parameter; pass the wire field through extra_body in Options |
openai_admin_organization_spend_limit:update/2,3 — notification_channel |
Field is present in the update body | No named parameter | No named parameter; pass the wire field through extra_body in Options |
openai_admin_organization_projects_spend_limit:update/3,4 — notification_channel |
Field is present in the update body | No named parameter | No named parameter; pass the wire field through extra_body in Options |
openai_skills:create/2,3 — files |
Required by CreateSkillBody |
May be omitted before sending the request | May be omitted before sending the request; no local required-field rejection |
openai_skills_versions:create/3,4 — files |
Required by CreateSkillVersionBody |
May be omitted before sending the request | May be omitted before sending the request; no local required-field rejection |
For the first three methods, unknown keys directly in Params are rejected with
invalid_argument, including binary spellings such as <<"safety_identifier">>
and <<"notification_channel">>. Use the existing extra_body key in Options,
for example #{extra_body => #{<<"safety_identifier">> => <<"user_example">>}};
this is a wire extension, not a named typed parameter or a guarantee of server
acceptance. Other required parameters still apply. Allowing omission of files
likewise does not establish that the server accepts an empty Skill upload.
Lifetime, ownership and cleanup
Handles and values are opaque. Their representation is not a public API.
An Error is an extensible map; its kind is an SDK atom and message a safe
UTF-8 binary. External names never create atoms.
| Value or handle | Lifetime and ownership |
|---|---|
| Client | Survives its creating process. openai:close/1 closes its HTTP context; application shutdown initiates cleanup of all contexts. openai:copy/2 and openai:with_options/2 share that context. Use openai:new/1 for independent lifetimes. |
| Active HTTP request | Belongs to its calling process; caller death, cancellation, Client close or application shutdown initiates cleanup. Sharing a Client does not transfer request ownership to its creator. |
| Response / loaded Page | Immutable, shareable values without a process. Data, metadata and serialization survive Client close and Body release. Fetching another Page requires the originating live HTTP context. |
| Body / Reader | The creating consumer owns read/parse/iterator pulls. Metadata, cached-only content and close/release need not be called by that owner. Owner death/application shutdown releases associated resources. Client close ends network I/O, not a complete cache. |
| Stream | The opening consumer owns reads. Any holder may close it. Owner death, Client close and application shutdown initiate cleanup, including retained completed cursors. |
| Realtime Connection | The opening process owns reads; other holders may send/close. Survives HTTP Client close, but owner death/application shutdown initiates its own cleanup. Closing it does not close the Client or neighboring sessions. |
| Explicit Auth | Independent owned context, shared only by opt-in. Survives its creator. Borrowing Client close does not close Auth, and Auth close does not close Clients. Application shutdown cleans Auth jobs/I/O. |
Start the openai application before Client work. Concurrent callers use separate
Erlang processes. A request blocks its caller,
not the VM; no separate async client is needed. Join workers before closing their
shared Client if their results are required. Client creation makes no network
request and has no hard overall startup deadline; suspended supervision can delay
it. A shutdown race may return a closed handle or a normalized unavailable error.
Contexts are not automatically restarted; old handles do not revive after restart.
Forgotten live Clients require explicit close or application shutdown.
openai:is_closed/1 reports false while running and true while closing/dead,
including stale handles after restart. It is neither atomic request admission
nor historical cleanup confirmation; invalid/unconfirmed queries fail safely.
HTTP context capacity
The current implementation fixes MAX_LEASES at 8: each HTTP context admits up
to eight ordinary HTTP requests and tracks up to eight connection entries.
Exhaustion returns capacity_exceeded immediately; there is no waiting pool or
public capacity setting. This is not a limit on conversations or on the number
of Clients in an application. openai:copy/2 and openai:with_options/2 share
these budgets with the original Client; each openai:new/1 creates a separate
context.
Request admission occurs before credential resolution or connection checkout,
so pending authentication also occupies request capacity. A buffered request
remains admitted until its driver has terminated and no longer owns connection
or authentication resources. An open Body/Stream
keeps admission while its driver owns a connection or authentication resources;
returning the handle to the caller does not free it. After I/O finishes and
check-in or destructive release is confirmed, a reported streaming driver no
longer consumes request admission even if its cursor remains. A retained complete
Body cache or materialized Response/Page is not itself an active request slot.
openai_body:close/1 and openai_stream:close/1 terminate their network I/O;
openai_body:release/1 also frees its cache and cursor resources. Cleanup must be
confirmed; merely requesting cancellation or observing an HTTP result does not
prove admission has been released.
Connection capacity is separate: connecting, busy, idle and stopping entries all count. Successful check-in makes a connection idle and reusable by a request with matching destination/transport settings; it does not remove that connection entry. An idle connection for different settings is not automatically evicted to make room. Destructive release removes the entry only after its worker and Gun process termination are confirmed. Internal authentication I/O has separate request-admission accounting to avoid deadlock behind ordinary requests; it does not increase the public request budget or remove the connection-entry limit.
Close confirmation and failures
For a live Client, successful openai:close/1 confirms its owned HTTP resources
and coordinator have terminated. An already-dead context returns idempotent ok
without proving historical cleanup. Independent Realtime Connections are excluded.
Concurrent close is safe. Acceptance timeout reports phase => acceptance and
close_state => unconfirmed; accepted-but-unfinished close reports
phase => termination and close_state => closing. Cleanup continues, new work
is rejected, and repeated close can wait for completion. A timeout never reopens
the context or proves cleanup. Active-close failures are normalized.
Application shutdown initiates cancellation and resource release with finite
supervision budgets; its return or forced termination alone is not a per-resource
graceful-cleanup acknowledgement. Monitored termination and the resource's cleanup
acknowledgement are distinct from sending a cancellation or receiving an EXIT.
Close uses cancellation, not implicit graceful draining. HTTP cleanup has its
separate finite budget; cleanup_timeout means unconfirmed cleanup.
Owner-only operations return safe not_owner/concurrent_read errors rather
than raw process/Gun exits. No ownership transfer is promised. Once Stream close
is accepted, new read, metadata and protocol-state operations return closed,
including while a validator runs or cleanup is pending. Close waiters cannot be
mistaken for readers or replaced by new operations. Joined close callers do not
restart cleanup's budget; successful close still requires confirmed driver DOWN,
including races with natural EOF/check-in. Closing one Stream cancels only its
request, not neighboring requests.
Body cache, close and release
openai_body:close/1 confirms network-driver cleanup while retaining complete
cache and already-received parser/Reader buffers. It permits no new network read.
openai_body:release/1 additionally closes associated cursors, frees cache and
confirms cache-owner DOWN. There is no implicit TTL, eviction or global registry.
Release explicitly, normally in try/after.
A full read caches decoded bytes separately from entity bytes. Cached
read/text/json/parse and decoded byte/text/line iteration remain available after
Body/Client close until release. Partial iteration creates no complete cache;
full read/ordinary parse afterward returns stream_consumed, without replay,
rewind or another HTTP request. Closing unread I/O yields closed. Reader
continuations carry a generation: use the returned Reader, not an older copy.
Raw iteration is consumed after full read even though the decoded cache can replay.
Original entity bytes remain stored independently.
Semantic SSE parse retains one cursor. After Body close, packed buffered events
can drain; a split event needing another network read cannot. An unread closed
Body fails closed. openai_stream:close/1 finally closes that cursor regardless
of buffered events. Repeated Body parse returns the same cursor, including its
closed state; release never destroys already materialized Response/Page values.
Page Body parsing retains its post-parser and rejects unsupported alternate casts.
Parsed-raw helpers alone return a buffered Body: bytes and network cleanup are
complete before return, validation is lazy. A successful parse is cached; errors
are not. Reentrant parsing fails with concurrent_read, foreign parsing with
not_owner. Close invalidates an in-flight cache commit; release ends cache
ownership. Complete cache/success survives Body/Client close, not release.
Callbacks run in the consumer; there is no new timer or forced termination of
arbitrary caller code. Ordinary raw Response values need no release and are
repeatably parsed without I/O. These are different contracts.
openai_body:with/2, openai_body:fold/3 and file helpers finally release on
success, early halt and
consumer exceptions. Currently they use ok = release(Body) in after: a
cleanup error can raise badmatch and replace the result or original exception.
See helper cleanup behavior.
openai_body:text/1 racing release returns decoded text or a safe closed error,
never a badmap exception. File helpers do not create missing parent directories;
write/truncate is local,
and a partial destination remains after an error.
Local cleanup never deletes remote objects. Record newly created IDs before later work and arrange remote cleanup separately, including on unknown outcomes. Delete acknowledgement, GET404 and physical data erasure are different claims.
Configuration and precedence
Supported keys, types and defaults are in API Options.
Unknown options, binary spellings of Client control keys and unsupported
null/omit positions fail explicitly. There is no caller-injected HTTP client,
replacement transport, mutable configuration property or configurable waiting pool.
Request overrides win over immutable derived settings, then original Client
settings. Missing/undefined inherits where supported. Replacement settings replace
the whole value: a complete timeout map is not a per-phase merge. Header/query
replacement clears custom defaults, not generated SDK defaults. Original and
sibling handles remain unchanged.
Environment and copy rules
| Setting | Construction | Copy / derivation |
|---|---|---|
| API key / base URL | Absent/null/undefined uses environment, then the documented fallback; explicit invalid input never falls back | Effective value is inherited without re-reading its environment; null/empty follows the option's inheritance rule |
| Organization / project | Absent/null/undefined reads its environment; binary, including empty, wins; omit suppresses the generated header |
Absent/undefined/null/omit/empty inherits; only nonempty binary replaces. Inherited null re-reads environment; inherited empty/omit stays. Neither copy null nor omit is a general clearing operation |
| Admin key / webhook secret | Absent/null/undefined reads its own environment; explicit binary, including empty, wins | Absent/undefined/null/empty inherits; inherited null re-reads environment, inherited empty stays. No callable or omit value |
| Custom headers | Read OPENAI_CUSTOM_HEADERS, then overlay explicit/inherited pairs |
Environment is re-read on each derivation; old matching values remain, new environment names can appear. Empty replacement permits current environment values to apply |
| Default query | No environment source; shallow logical map | Merge or whole replacement; empty map clears inherited defaults |
| TLS | Snapshot explicit settings or eligible certificate environment | Empty copy inherits snapshot; only explicit TLS replacement re-reads eligible environment |
An empty openai:with_options/2 can therefore observe changed header or
organization/project/admin/secret environment and can fail if it is invalid.
Organization and project resolve independently. Invalid credential/account text
is rejected eagerly without echoing values. Handle/config printing and VM
introspection can expose secrets despite controlled diagnostics redaction.
Header defaults merge by exact, case-sensitive names and preserve dictionary
positions. Generated account headers are inserted between custom-header passes;
canonical custom OpenAI-Organization/OpenAI-Project can override them, while a
differently cased earlier entry can lose to the later generated entry. Only the
final wire merge is case-insensitive. Request headers override or omit last;
omitted headers are not regenerated. Header environment splits at LF and the
first colon, trims surrounding whitespace, ignores colonless lines, and replaces
repeated exact names in place. Malformed/forbidden headers fail safely.
Default header/query null adds no constructor values and inherits on copy;
set_default_* null also inherits. Use empty replacements to clear. Merge and
replacement controls cannot both supply effective values. Custom headers are
ready binary bytes, including non-UTF-8; credential/account text has stricter
validation. This is not pinned SDK Unicode-header wire parity.
Residency and destination selection
data_residency selects an HTTP base URL, not a storage/compliance guarantee.
The supported regions/URLs are in API. A region overrides an
inherited URL and OPENAI_BASE_URL, even if that environment is invalid.
It adds no credential, header, query or body field. Explicit base_url, even
null or the same URL, conflicts with a non-null region before normalization;
absent/undefined does not. Null residency means no new selection, not global reset.
Unknown/case-mismatched names and omit fail. Copies can select another region or
an explicit root without mutating siblings. No mutable region property exists.
Regional routing does not itself prove delivery/storage location. WebSocket and
X.509 routing have additional rules below.
Requests, URLs and transport security
Request shape/mode/options validate before credential evaluation and checkout, subject to the documented multipart-selector edge below. Known named fields and binary JSON keys are method-specific; duplicate atom/binary spellings fail. Required presence is not server policy/range validation: explicit null is supplied, omit/undefined absent. Model IDs remain open binaries. Unknown API data belongs in documented extras; no API response creates new atoms.
Encoding, headers and query
JSON is compact UTF-8 with binary keys/text. Whole-body missing/null/undefined/omit sends no JSON body; nested null is encoded. Raw body and present JSON are mutually exclusive, including GET. The generated Content-Type is application/json even without a body or with raw bytes, unless overridden/omitted. JSON map key order is not Python insertion order. Body/query extras shallowly replace named objects; top-level supported omit removes, undefined adds no override, explicit null remains. Arbitrary dictionaries/arrays do not recursively prune sentinels or shorten arrays.
Host, Content-Length, Transfer-Encoding and Connection are reserved. Other
outbound names/values reject malformed names and NUL/CR/LF without exposing data.
Late generated retry-count/read-timeout headers override Client defaults; explicit
request values/omit win, undefined inherits. Read-timeout is emitted in seconds
only for non-null read settings. Platform headers identify Erlang/OTP and the
actual package version, not Python; missing application version is unknown.
X-Stainless-Async: false describes returning functions, not a ban on concurrency.
Omitting User-Agent leaves none on the Erlang wire; Python's backend may add its own.
Queries merge logical values before encoding. Top-level omit removes inherited values; null replaces and emits nothing; undefined inherits. Empty lists/maps emit nothing, empty strings remain. Nested nulls are omitted, nested sentinels rejected. Arrays use bracketed repeated names; nested objects use bracket names. Ordered request pairs preserve scalar repetitions/order and replace all defaults of the same name. Duplicate keys mixed with omit/undefined reject as ambiguous. Map order is deterministic Erlang order, not Python insertion order.
URL and redirect boundaries
Public HTTP requires absolute HTTPS base URLs without userinfo/query/fragment;
request URLs additionally permit query. Relative paths join the effective base
path; absolute URLs use their own path (empty becomes /). Unicode is URI-encoded,
valid assembled percent escapes retained, literal/encoded dot segments rejected.
Raw path IDs are nonempty UTF-8 binaries escaped exactly once: slash/percent are
data, and %2e becomes %252e. No invented ID-prefix validation is applied.
Scheme-relative and non-HTTPS request URLs are unsupported.
A direct absolute foreign origin requires explicit final request Authorization omit; Client-only omission or a replacement value does not qualify. Origin means scheme, case-insensitive host and effective port (443 if absent), not DNS aliases. Rejection happens before credential callback/checkout. Allowed foreign requests still evaluate a selected ordinary bearer callback; its failure prevents sending. They do not inherit Client custom/account headers or target client certificates; explicit request headers remain caller-controlled and CA verification remains. An explicitly configured Client base URL itself defines the trusted destination. This restriction is intentionally stricter than Python forwarding credentials.
If effective structured query is empty, embedded URL query bytes remain untouched. Otherwise URL query becomes a mapping (first repeated value wins), structured defaults/overrides merge, then encoding runs. Omit is removed before this URL merge, so it cannot erase a same-named embedded parameter; null can replace it then disappear in encoding. Clear inherited query and add no structured values when preserving a signed URL. No signature repair or anonymous mode is implied.
Redirects follow the configured max_redirects limit (default 20). Relative Location uses
the current URL. 301 POST, 302 except HEAD/QUERY, and 303 except HEAD become GET
without a body; 307/308 preserve method/body. Headers come from the previous wire
request, not rebuilt credentials/query. Cross-origin Authorization/account and
inherited custom headers are stripped and not restored on return to the original
origin; target client certificates are removed. The preceding connection is
released with confirmation before acquiring another. Invalid/downgrade Location
fails with invalid_redirect, exhausted hops with too_many_redirects. Redirects
share the original total deadline; they are not transport retries. Cookie jars,
Set-Cookie processing and redirect-cookie parity are absent.
TLS and proxy isolation
Peer and hostname verification are mandatory. Explicit trust wins over
SSL_CERT_FILE, then SSL_CERT_DIR when trust_env permits. Default OTP system
trust loads lazily; a CA directory eagerly loads valid matching OpenSSL-style
subject_hash.N PEM files in deterministic order, ignoring unhashed files.
Certificate/key/password values are immutable snapshots loaded before context
initialization; changing a file does not mutate a handle. TLS replacement changes
connection identity; API keys do not. Transport mTLS alone is not workload token
exchange or special mTLS endpoint selection.
HTTPS CONNECT proxies have independent trust, client certificates, headers/auth.
Proxy credentials go only to CONNECT; API credentials go only inside target TLS.
Proxy gun_up is not target readiness: a correlated tunnel-up is required.
Reuse is confined to the same context, origin and effective target/proxy TLS/auth
identity. There is no direct fallback or automatic reconnect. HTTP/SOCKS proxies,
proxy-environment/NO_PROXY routing and WSS proxy integration are unsupported.
Pending CONNECT cleanup can exceed close confirmation budget; no timeout proves
tunnel-process termination. Blocked-send guarantees remain limited as stated below.
Values, presence and serialization
Response values retain API data, field presence, finite descriptors and separate
HTTP metadata. JSON objects use binary-key maps, arrays lists, strings UTF-8
binaries, numbers integers/floats, booleans true/false and JSON null null.
Date strings remain binaries, not Python datetime objects. Non-object JSON can
remain JSON-native; successful text fallback is not an artificial model/map.
Supported model coercions can change scalar types: raw bytes remain independent.
Missing, null, undefined and omit are distinct. Missing preserves absence;
maps:find/2 distinguishes it from null. Sentinels act only at documented SDK
merge/TypedDict positions. Unsupported sentinel positions fail explicitly.
Older Responses named Params require known atom keys; finite builders may accept
known binary spellings too. API JSON keys themselves are never renamed globally.
Supported map projections use native (default) or json, not python.
mode => python and exclude_none fail with unsupported_option; no aliases.
Use exclude_null. Ordinary Responses retain their own supported-option boundary;
a selector name does not enable unavailable nested projections. openai_response:to_json/1,2
accepts no mode option, supports documented indentation, and promises neither
Python key order nor byte-identical float/JSON formatting.
Default serialization uses API names, excludes unset fields, retains defaults
when explicitly set, and retains null. exclude_unset => false exposes known
missing defaults (including null for required fields in loose construction).
exclude_defaults compares declared defaults; exclude_null acts on supported
model fields, not arbitrary dictionary entries or array elements. Presence is
not mutated. Unavailable descriptor traversal returns unsupported_option;
opaque branches retain JSON under default serialization rather than pretending
to implement a complete schema namespace.
For ordinary Responses this includes remaining tool/input unions, annotations,
logprobs/misalignment and fields such as access_programs, non-string instructions,
conversation, image, input_transformations, moderation, prompt, prompt_cache_diagnostics,
prompt_cache_options, tool_usage, tool_choice and tools. Their model-specific
aliases/defaults/exclusions are not implied by JSON retention; scalar/null/empty-list
branches need no unavailable nested traversal.
API-name serialization preserves unknown extras, including literal model-name
keys such as async_=false on a function call with unknown status. This retention
is an intentional difference from pinned Python projection. Named view
use_api_names => false is potentially lossy: schema/schema_ and
async/async_ collisions can overwrite values or omit extras depending on the
checked/loose branch. A lone schema_ does not establish presence of wire schema;
when both arrive, API-name output keeps both, while named view can keep only the
extra value under schema_. Extra nulls follow their supported exclusion rule.
Finite union selection checks required fields, enums, scalar/container kinds and
nested alternatives. Failed checks choose loose construction, not response
rejection. A matching original scalar kind wins over earlier coercible branches:
file-search attribute booleans remain boolean, while a float branch converts an
integer to float. Nested containers use the same selection. Native/JSON projection
can still differ (a filter [2,null] can retain integer native but emit float JSON).
An Any alternative can retain an unconverted object beyond model-only exclusions.
No general Pydantic validation or Python-object framework is provided.
openai_response:output_text/1 concatenates non-null text of output_text content
in message output items, in order without separators; no matches gives <<>>.
Malformed selected text/messages return invalid_response. It is not a generic
accessor for every resource or for compaction/count models.
Metadata is never API JSON. Headers retain repetitions as binary pairs; request-ID lookup is case-insensitive, absent ID is undefined. Top-level values receive originating metadata, nested objects do not inherit request IDs; each Page fetch has its own metadata. Stream metadata stays outside events and remains available after natural completion while the cursor lives, not after explicit close or lifecycle cleanup.
Errors are not response models. Without an HTTP response they invent no status,
headers or body. HTTP classification unwraps a JSON error field; otherwise body
is decoded JSON or trimmed non-JSON text/binary. raw_body independently retains
original bytes, including whitespace. Non-UTF-8 remains binary. Error code keeps
its JSON type, including arrays/objects/null; missing stays absent. This differs
from pinned Python's string projection of non-null codes. The separate finite
Page continuation formatter is unchanged. Messages expose status/safe categories,
not appended payloads, credentials, headers or callback reason/stack; explicit
data fields remain available for deliberate inspection, not automatic logging.
Bytes, decoding and limits
Entity bytes mean bytes after HTTP transfer framing but before Content-Encoding.
Decoded bytes are separate. Resource binary results return decoded bytes; ordinary
generic Client binary mode retains an opaque buffered Response. Raw containers
retain entity bytes/metadata and parse to the endpoint's selected result.
openai_response:body/1 does not re-encode model JSON or return decoded text.
Finite None casts consume/retain bytes as applicable and return null for any
successful body, including empty/non-JSON/non-UTF-8. HTTP errors classify first.
JSON media types ending in json require valid JSON. Other/missing Content-Type
returns text in JSON mode; model modes try JSON, then text fallback. JSON detection
uses byte encoding/BOM, not HTTP charset. Non-JSON fallback decodes original bytes
with HTTP charset, without prior JSON transcoding. Final error-body text decoding
precedes JSON error classification.
Supported text families are UTF-8/UTF-8-SIG, ASCII, Latin-1, UTF-16 and UTF-32,
including their current finite aliases and generic BOM/explicit LE/BE forms.
Lookup normalizes case/hyphens/underscores only. Missing charset means UTF-8;
explicit unsupported/non-text charset returns unsupported_option, even on an
empty body, unlike Python's unknown-charset UTF-8 fallback. Invalid/truncated
text uses replacement characters; generic UTF-16/32 requires a BOM. Known codecs
emit complete characters promptly; only incomplete BOM/multibyte sequences wait.
Text chunk sizes count characters; line splitting handles CRLF/separators/EOF.
SSE UTF-8 framing is strict instead of replacement decoding.
Identity/gzip/deflate decode incrementally, in reverse supported coding order, with raw-deflate fallback. Unknown coding labels follow pinned ignore-unknown behavior. Only gzip/deflate are advertised; optional br/zstd are unsupported. Forcing them can fail later JSON/UTF-8 parsing. Buffered/SSE decoding retains its five-supported-layer bound; lazy Body has no added five-layer cap. These are CAP-0041 boundaries, not a full codec registry or total-memory guarantee.
| Path / limit | Boundary |
|---|---|
| Legacy buffered normal/raw | Internal accumulated-body and buffered decoder limit of 1 MiB. Responses create does not apply explicit body_limits identically to Body. Media list Pages retain the generic buffered boundary. CAP-0042 remains open. |
| Body / materialized media | No default aggregate byte cap; full read/text/json/parse intentionally materializes. Media wire normal/raw/header-raw can use Body internally without changing generic text paths. |
Request body_limits |
Optional cumulative raw_bytes before coding, decoded_bytes after coding, line_bytes in returned UTF-8 excluding delimiters. Missing/undefined/null is unbounded; zero permits zero bytes. Invalid key/type/negative rejects before credentials/HTTP on supported paths. |
SSE stream_limits |
Optional UTF-8 line bytes excluding terminators, retained event field/data bytes, and snapshot budgets; no default queue or byte cap. Snapshot bound applies independently to each retained snapshot, final Response and ordered completed-item collection, including parsed values/extras but excluding metadata; duplicate representations are not summed. Zero rejects nonempty values. |
| HTTP context admission | Fixed 8 ordinary requests and 8 connection entries per shared context; the two budgets have different release/reuse rules. Immediate capacity_exceeded, no waiting pool. See HTTP context capacity. |
Body overflow returns body_too_large; SSE overflow stream_limit_exceeded.
Neither retries nor fabricates complete results. Final non-2xx bodies are fully
read/decoded/classified; a user limit failure must not present a truncated error
body as complete. Intermediate retryable responses may close without reading.
Both explicit and header-selected parsed-raw enforce raw/decoded limits, including
gzip, before publishing cache; no validator runs on refusal. Header-selected
parsed-raw starts from an already buffered legacy result; explicit parsed-raw can
reject during network reading. Those limits are not equal peak-memory bounds.
Gun credits count messages, not bytes; a chunk/in-flight data can overshoot a remaining budget. Incremental decoding quantum, admission and flow control do not bound total VM memory, mailbox/transient calls or all retained views.
Without an explicit Body mode, the exact effective marker
X-Stainless-Raw-Response: true selects the buffered raw path; absent/empty does
not. Other nonempty modern raw-marker values are unsupported on this ordinary
buffered path.
Explicit Body mode follows a different selection after the final header merge:
the canonical stream marker returns a lazy Body; effective true escapes to
the existing raw wrapper; an empty marker returns the ordinary result. For
non-SSE requests, other nonempty markers return a fully read Body that still
requires openai_body:release/1, rather than an unsupported-option error.
See Body marker behavior.
Wrappers replace their exact canonical marker in place or append it before the final case-insensitive merge; later differently cased values can still win. Parsed-raw/header-selected parsed-raw has its separate buffered Body contract in parsing, not the ordinary raw Response contract.
Timeouts and retries
HTTP time units are integer milliseconds; API lists defaults and accepted settings. Phase map replacement requires all four fields; scalar sets all phases, null disables them, missing/undefined inherits. Request settings win over derived/original Client settings. No timeout environment variable applies.
total_timeout_ms is a separate optional monotonic operation deadline, disabled
by default. It starts at operation entry and covers preparation, admission,
credentials, redirects, attempts, reading and retry backoff. Progress never
renews it. Disabling phase timeouts does not disable an inherited total deadline.
The existing timeout_ms spelling aliases total timeout; both spellings together
reject, even with undefined. No implicit overall checkout cap replaces HTTP phase
settings or the explicitly selected total deadline.
Each DNS/TCP/TLS operation gets its connect budget; proxy TLS and target TLS are separate. CONNECT sends use write, CONNECT response waits use read, and reuse skips completed connection phases. Read waiting starts after transport send and resets on observable response start/headers/nonempty data, not service messages. It measures Gun event/data progress, not every raw socket byte or total transfer. For streams it does not charge paused consumer idle time; enabled total deadline still covers idle time until natural I/O completion disarms operation timers.
Write timing spans the transport send, not the return of asynchronous request submission. Send acknowledgement never proves peer receipt. SDK write timeout, cancellation and confirmed cleanup under blocked HTTPS CONNECT send remain integration-unverified, including finite/disabled write timeouts. Autonomous direct blocked-write TLS child/socket cleanup is separately unverified. Neither multipart ordering nor a suspended-sender check proves real TCP backpressure cleanup. Failed/timed-out connections are excluded from reuse.
Zero expires at phase entry; a reused ready connection skips connect. Credential callbacks precede phases, so only an enabled total deadline/lifecycle cancellation bounds arbitrary callback code. With all timers disabled a request can wait indefinitely. Pool timeout is inapplicable to HTTP admission without a queue; capacity refusal is not PoolTimeout. Native Google refresh-lock waiting is a separate documented use of that setting. Timeout errors expose phase connect/read/write/total, not private callback/peer state. Cleanup has its own finite 2000ms budget; timeout is not cleanup confirmation.
Retry decisions and replay
max_retries counts additional attempts; zero disables. Null, negative, float
and boolean values fail (Python's bool-as-int is not adopted). Statuses
408/409/429/500–599 retry by default. Exact x-should-retry: true can permit
other errors, false suppresses; values are case-sensitive, names insensitive.
Successful 2xx never retry. A finite parsed server delay above 120 seconds vetoes
retry before that hint.
Delay priority is Retry-After-ms, numeric Retry-After, then HTTP date. Parsed
zero/negative/nonfinite numeric selects backoff without trying lower-priority
headers; invalid numbers may fall through. Positive numeric overflow vetoes,
literal inf/nan selects backoff. Positive finite delays up to 120 seconds are
honored without jitter. Otherwise use min(500 * 2^retry_index, 8000) ms reduced
by uniform 0–25% jitter, rounded upward to milliseconds. Dates use wall time;
waiting uses monotonic time. Existing numeric leniency is unchanged.
Connection failures and connect/read/write timeouts can retry. Redirect-hop
exhaustion can retry the original operation, retaining too_many_redirects on
exhaustion. Validation/security/callback errors, cancellation, close, total
deadline, capacity/byte limits and unconfirmed cleanup do not retry. Malformed
successful JSON/model parsing does not retry HTTP. Exhaustion returns the last
HTTP result or transport error, not an invented exhaustion wrapper.
Attempts restart the original prepared request/effective configuration, refresh ordinary bearer callbacks, and restart actual phase budgets, never the total deadline. Redirect hops within an attempt do not reevaluate callbacks. Every verb, including POST, can retry; replayability is not exactly-once execution. No automatic idempotency header is generated. Explicit Idempotency-Key persists subject to redirect isolation; retry-count is zero-based and unchanged per hop. The previous connection must be checked in or destructively released with confirmation before backoff. Backoff holds request admission, not a busy connection; total deadline and lifecycle cancellation remain active. After successful Body headers/Stream opening, read/decode errors never replay the request.
Event streams
Raw SSE and high-level helpers share transport/admission/auth/opening retries.
Repeated raw parse returns the same cursor, without HTTP or rewind. The SDK does
not record an entire SSE body for openai_response:body/1. There is no ready-event
queue: consume the decoded/unparsed tail before granting more data credit.
See canonical ownership and
limits.
SSE handles CR/LF/CRLF, multiline data, comments, persistent IDs and retry fields
after Content-Encoding decoding. EOF validates the last buffered UTF-8 line,
including split multibyte sequences, but does not dispatch an unfinished event.
Invalid/incomplete UTF-8 returns invalid_response, adapting UnicodeDecodeError.
Transport/decode/protocol errors are reported once, then the cursor is exhausted.
[DONE] stops parsing without replaying trailing bytes. Python sync close is
the mapping; async background draining for connection reuse is not emulated.
Responses completion and heartbeat
Failed/incomplete responses are events followed by normal eos, not completion.
openai_responses_stream:until_done/1 drains; its final getter requires a genuine
completed event or returns response_not_completed. Completed alone does not
stop reading before EOF/[DONE]. New drain errors propagate; an already observed
error does not erase an existing completed cache. Partial snapshots never satisfy
completion. The high-level accumulator requires response.created before domain
events, unlike raw forward-compatible event delivery.
One narrow adaptation skips a confirmed service heartbeat without changing state: exactly type=keepalive plus nonnegative integer sequence_number, SSE event name absent or keepalive, no extra fields. Raw preserves it. Pinned Python raises before created and exposes it afterward; this adaptation is intentional. Malformed JSON, unknown types, extra/domain payload and mismatched event names retain normal delivery/error behavior. Heartbeat is not completed and does not disable total deadline/cancellation or add a timer.
With high-level starting_after, domain events need an integer sequence_number; missing/null/float/bool/other values fail safely through cleanup. Numbers are not renumbered. This is stricter than Python's non-strict comparison. Without filtering, unknown events retain forward-compatible delivery. Four high-level wrappers rebuild their pinned fields and can drop extras; raw event roots pass through. This event-wrapper projection is distinct from model extras retention.
Chat and media streams
Chat uses a separate pure accumulator, not Responses sequence/completed rules. It merges indexed choices/tools, refusal/content/logprobs and usage-only chunks; chunk events precede derived deltas/done events in reference order. Valid EOF can return the available snapshot, not proof of a finish reason. Empty input, malformed JSON/UTF-8 and length/content-filter cases retain their typed/plain error distinctions; available completion is an immutable error data field. Only tools addressed by the current delta receive partial-argument updates; other tools keep previously validated results.
Partial JSON is pure Erlang. Parsed NaN/Infinity/-Infinity use json_nan, json_positive_infinity and json_negative_infinity; Chat native maps retain them, Chat JSON projection/to_json emits null. Raw content/argument bytes never change; requests reject these markers. Partial parsed snapshots are not schema validation.
Semantic transcription/image streams reuse the SSE cursor with finite event models but no snapshot accumulator; snapshot_bytes has no retained view to bound. Unknown events/extras and non-map JSON non-strict values remain; malformed data still errors. Speech stream_format=sse remains binary/Body bytes/text/lines, not a typed speech event stream. Inconsistent high-level opening via an independently requested raw-header wrapper is closed and rejected; explicit supported resource raw modes remain available.
Pagination
Pages are immutable and have no owner process, prefetch or new page limit. Traversal visits loaded data first and fetches only when continuing; early halt issues no next request. Consumer exceptions propagate without an active retained HTTP request. Traversing twice can fetch subsequent pages twice.
| Page kind | Continuation |
|---|---|
| single | None |
| cursor | Last model item's non-null id becomes after; empty binary remains a candidate. JSON-mode maps do not implement Python attribute access |
| conversation_cursor | Truthy last_id becomes after |
| next_cursor | Truthy next becomes after |
| token | Truthy next becomes page |
Falsy data stops traversal. Cursor kinds construct supported non-strict has_more
booleans from booleans, numeric 0/1 and case-insensitive strings 0/1, false/true,
f/t, off/on, n/y, no/yes. Whitespace is not trimmed; invalid values stay as received.
Predicates and serialization use that effective value. Effective false stops
iteration, but direct openai_page:next_page_info/1/openai_page:get_next_page/1
consult continuation independently and can fetch despite has_more=false.
No continuation returns no_next_page without HTTP, instead of RuntimeError.
Non-strict data iteration preserves the original serialization/continuation data: falsy values yield no items, strings yield Unicode-character binaries, objects yield binary keys in Erlang map order; truthy non-iterables yield invalid_response. This is not arbitrary Python-object emulation.
Parameter continuation shallow-merges retained query; JSON continuation merges mapping bodies only. URL continuation overwrites same-named query, takes the first repeated value, collapses retained arrays/repetitions, drops empty arrays and turns null/bare keys into empty strings using the existing finite Python-style scalar/container formatter. Erlang object order differs. Unrelated ordered pairs survive parameter continuation. Each fetch retains original method/body/security/ options with a fresh operation timeout/retry/auth evaluation; it does not derive a Client or re-read environment.
Following a raw Page selects ordinary Page mode and removes a truthy canonical request raw marker. A Client-default marker can remain and return another raw wrapper; parse it explicitly. Folds fail safely on this edge rather than claiming to have traversed ordinary Pages. Repeated raw parse itself performs no HTTP.
Multipart sources and replay
Descriptors and workflow use are in API and HELPERS. Binary sources retain exact bytes; path snapshots read eagerly in the cancellable source worker before credentials/ network, while file sources open lazily and are SDK-owned. Borrowed opaque IO objects and arbitrary iterables are unsupported. Producer callbacks run in the source worker; caller-created external resources remain caller responsibility.
Names/filenames are UTF-8 with HTTPX-compatible escaping. Cowlib MIME inference is finite, not a host Python registry: for example .md can become octet-stream rather than text/markdown. Explicit part headers override tuple MIME; null/empty filename omits inferred Content-Type, unknown suffix uses octet-stream. Ordered file pairs retain order/repetition; map form fields have Erlang map order.
The effective multipart Content-Type marker is selected after header merge. Without a boundary it generates one; explicit boundary stays. Only that marker converts an ordinary JSON map into form fields, even without files. Raw body plus that marker rejects; an ordinary credential callback can run before this specific rejection, but no source opens. Files can still encode multipart without silently rewriting an unrelated JSON body or explicit non-multipart header. Omitted Content-Type is supplied by the encoder. Arrays use bracketed fields, including the pinned initial-empty-repeat replacement. Endpoint-specific encoded JSON/text parts shallow-merge extras, preserve nested/null data, prune supported sentinels and use raw fallback only for the sole eligible field without existing files.
One source descriptor is retained per logical request; retries do not reopen a
possibly replaced path. Seekable files begin at zero. Binary/path snapshots replay
prepared bytes; producer reset promises identical bytes. Confirm network cleanup
before reset and before new credentials/checkout/headers. Check all sources for
replayability before any reset. Reset/source errors do not become transport retries.
Body-changing redirects discard the source; preserving redirects require reset.
Non-replayable producer redirects/auth replay return body_not_replayable rather
than a second send, an intentional difference from HTTPX exhausted-part behavior.
On non-replayable retry/exhaustion, the previous HTTP status remains available.
Known length uses Content-Length, unknown length chunked HTTP/1. Declared length is checked. Operational pulls up to 64 KiB wait for same-sender Gun ordering after preceding data; this orders direct TLS/CONNECT transport sends, not peer receipt, HTTP/2 backpressure or total memory. Total/lifecycle bounds source code; write applies during sending, read after request completion. SigV4 streaming requires incremental prehash/reset and replayability, never unsigned fallback.
Successful cleanup needs source close/worker DOWN plus network acknowledgement. A blocked/failed close can yield cleanup_timeout; killing a worker does not prove release of arbitrary external resources it created. SDK-owned OTP files close with that worker. This adds no hidden source cap or new timeout default and does not resolve the separate blocked-send cleanup limitations.
Authentication
API keys, admin credentials and callbacks
Construction requires a regular or admin credential. Admin-only Client is valid; an absent/empty regular environment permits it when admin is available, but an explicit invalid regular key never falls back. Webhook secret alone is not auth. Credential callback runs lazily once per enabled bearer attempt, including header override/omit, not during Client creation/copy or each redirect hop. Its monitored worker observes total deadline/cancellation, not a new callback phase timer. Failure returns credential_provider_failed without reason/stack/value/environment fallback. Worker DOWN does not cover arbitrary child processes started by user code.
Generic security defaults enable bearer and admin; an explicit security map replaces them and absent flags in it mean false. With both enabled nonempty bearer wins, then admin if bearer is absent/empty. Bearer-only never falls back to admin; admin-only skips bearer callbacks/providers. Resources select their pinned auth explicitly, never by URL. Checkpoint permissions select bearer, administration selects admin. Ordinary Responses reject caller security override.
Generated Authorization participates in normal header merging. Only explicit request Authorization omit permits final absence. Client-only omission without that exemption returns missing_credentials before network (Python can raise TypeError); a later request header can restore it. Empty callback result permits admin fallback only when enabled, unlike a callback exception. Foreign-origin isolation applies equally to admin credentials. Connections are keyed by origin/ TLS, not API/admin key. These flags do not implement provider/workload WSS auth.
Provider selection and native credentials
Factories are immutable definitions, not credential processes/registries. Vertex captures explicit truthy project/location or their environment, unless an explicit HTTPS root bypasses those fields; global/regional host selection differs. It owns Authorization, rejects final account/project/api-key headers, confines auth to its origin and disables redirects. Supplied token must be nonempty printable ASCII without spaces. Erlang follows sync timing: total/cancellation bounds callback, HTTP read begins afterward. Pinned async applies read timeout to callback too; no full timing parity is claimed, including read=0.
Bedrock distinguishes Mantle/Runtime and partitions. Bearer, token callback and explicit AWS modes are mutually exclusive. Absent factory api_key can select AWS_BEARER_TOKEN_BEDROCK; explicit null suppresses it. Selection is captured but selected bearer environment is re-read per attempt. Factory base_url absence uses AWS_BEDROCK_BASE_URL; null suppresses it. Region resolves explicit, environment, then profile; files may be read at Client construction/copy but token acquisition is lazy. Canonical endpoint/region conflicts and empty explicit credentials fail.
Providers reject top-level API/admin/workload/routing overrides and do not inherit account or custom-header environment. Explicit Client headers merge normally; changing provider clears inherited custom/account defaults, same-provider copy inherits. Custom Authorization must be absent before provider preparation; provider auth can restore it after omission, so omission does not disable it. SigV4 signs final method/URL/query/headers/body with frozen credentials and fresh UTC date per attempt, replacing signing headers. It includes attempt headers, supports session credentials and rejects redirect enabling. Supplied AWS callbacks are interruptible one-shot workers; static/binary paths need none.
Native AWS covers environment/static profiles, legacy files, AssumeRole chains, web identity, legacy/session SSO/OIDC, Login/DPoP and ECS/IMDS. Explicit profile skips top-level environment credentials. Quoted profiles, indentation and nested service settings retain structure. Source selection/snapshots remain fixed on refresh; configured unsupported modes do not silently fall through. Static credentials cache per view; ordinary copy has independent lazy state. Expiring environment uses 15-minute advisory/10-minute mandatory windows: advisory failure can retain unexpired credentials, mandatory failure propagates. No idle eviction or chain reselection is introduced.
Native service retries are separate from OpenAI retries: legacy five attempts, standard three with per-client quota, configurable native settings. Adaptive and AWS_NEW_RETRIES_2026 reject. Service endpoint/environment, STS regional/legacy signing region, partition/FIPS/dual-stack selection remain source-specific. MFA and executable AWS/Google discovery return unsupported_option before STS/input or process launch; supplied callbacks are separate, not native discovery. No terminal prompt, native helper or OS-child cleanup guarantee is implied. OTP port DOWN alone would not prove OS-child exit.
ECS defaults to three 2-second attempts; IMDS to one 1-second attempt with its source environment controls. IMDSv2 precedes role retrieval; disabling v1 prevents fallback. Empty/invalid metadata JSON retries within source budget. IMDS expiry extension retains its 15-minute window plus 120–600-second jitter; ECS does not. Metadata never receives API credentials/certificates or falls through to bearer.
Google file/info descriptors select finite credentials without arbitrary objects. Explicit source skips ADC; default discovery checks GOOGLE_APPLICATION_CREDENTIALS, Cloud SDK ADC, then basic GCE metadata. Configuration/updated refresh_token stays in a view rather than re-reading files on every cached request. A validated source survives first refresh failure; ordinary copy rediscovers independently. Default external-account ADC can perform Resource Manager project lookup using file quota project before environment override; explicit file/info construction does not. Impersonation source tokens cache separately from impersonated tokens. File loading requests cloud-platform scope, IAM source scopes for impersonation; quota project snapshots environment before file value and sends x-goog-user-project if nonempty.
Covered flows include authorized-user OAuth, RS256 service accounts, external file/HTTPS text/JSON subjects and STS, external authorized-user, impersonation and ES256 GDCH. GDCH requires format1/key ID and uses its exchange CA without invented audience. Nondefault-universe service accounts use scoped self-signed JWTs. Subjects can use AWS signing, approved metadata or certificate sources. Workforce userProject applies only without Basic client auth. Certificate discovery freezes its own key/cert, never borrows API client certs. OAuth uses reference three-attempt retry conditions/jitter; external STS is one request. Google HTTPS redirects use the 30-hop Requests bound, verified HTTPS and no downgrade; metadata never redirects. Token-usage metrics retain the source credential type, not a Python runtime identity. Expiry absent/null is unbounded; refresh threshold is 225 seconds. A token with accepted zero expiry serves the current native call and refreshes next lookup; native token headers do not use the stricter supplied-Vertex-callback rule.
GCE checks metadata flavor, obtains account info/scoped token, with none/default/ strict mTLS selection and dedicated cert paths. Default can fall back to approved HTTP metadata after TLS/HTTP failure; strict cannot. Agent Identity obeys source opt-out and SPIFFE trust-domain validation; certificate startup polling is limited to its well-known directory and cancellable. No project/region is inferred from successful API calls. Waiting on another native Google refresh uses pool timeout as credential-lock budget, bounded by total; the active refresh uses connect/read. This lock is separate from HTTP admission, which has no pool queue. Explicitly shared Google Auth is opt-in and already scoped for Vertex; native-token access is internal and cannot be used as OpenAI workload identity.
Subject exchange and shared refresh
Subjects use supplied jwt/id callbacks or lazy Kubernetes files. Refresh reads
the subject, performs a separate verified HTTPS JSON grant and caches token with
monotonic expiry. Buffer defaults to 1200 seconds; delay is
max(expires_in - min(buffer, expires_in / 2), 0). Pinned boolean expiry behavior
is retained; nonpositive expiry is unusable, nonfinite JSON numbers unsupported.
Timing is represented in milliseconds. Subject exchange borrows no API credentials,
custom headers or client certificates; it has separate trust/proxy and 10-second
phases, no redirects/exchange retries, bounded by the API caller's total deadline.
Ordinary identity/provider copies allocate independent views lazily. Used view cache/source/error data remains until shared HTTP context close, without idle processes/timers, eviction or an eight-view cap. Same-view callers share refresh; dead/deadline waiters detach, last waiter cancels. Replacement waits for job DOWN and tracked auth I/O cleanup. Private auth work shares resource tracking, not public admission slots, avoiding credential deadlock behind eight API requests. Explicit shared Auth ownership follows the canonical lifetime table; its close wait is two seconds after acceptance, ordinary Client close's wait one second.
Only selected auth can exchange/replay. Explicit final Authorization or request omit bypasses subject acquisition; Client-only omission fails before acquisition; admin-only selects admin without subject. An authenticated 401 conditionally invalidates the actual token, confirms prior request cleanup and replays original request once inside that attempt. A second 401 invalidates its rejected token, without a third auth-driven send; next independent request refreshes. Stale 401 must not discard a newer token. Ordinary retry limits/total deadline remain separate.
The pinned subject-Client copy(api_key="") transition disables workload auth
and sends literal Bearer workload-identity-auth, without subject callback/exchange
or changing the original Client. That transition alone produces the placeholder;
it is not an exchange credential, ordinary workload key or validation bypass.
OAuth 400/401/403 returns oauth_error plus explicit body/raw_body/code when present,
but a generic diagnostic message, not Python's error_description projection.
Azure subject metadata is fixed to 169.254.169.254:80 and /metadata/identity/oauth2/token; GCP uses its fixed identity path on metadata.google.internal/169.254.169.254:80. They use direct approved-IP routing, no DNS retargeting, proxy/redirects, API/account auth, cookies or client certificates. Only source metadata headers/query are sent; unknown overrides reject. Independent source budgets default to 10000ms, null disables; API cancellation/total still applies. This narrow metadata exception does not enable arbitrary public HTTP.
X.509 workload identity
Protected X.509 exchanges at https://mtls.auth.openai.com/oauth/token using the API Client's verified TLS/client certificate, stripped of API auth/headers/query. It sends x509 token type without subject_token. Phases are min(request phase, 10000ms), disabled phases capped at 10000; retries min(Client max_retries,2), not request retry override. Delay hints allow zero through 120 seconds, no jitter. OAuth 400/401/403 does not retry and preserves explicit error-only body/raw bytes. Token/type/positive finite expiry validate. Transient proactive refresh failure can retain unexpired token and retry refresh after 500ms; terminal/expired cannot.
API requests stay at configured origin, validate Host and reject API-key/proxy credential headers including underscore spellings. Explicit Authorization/omit bypasses exchange, not these checks; redirects are disabled. Ambient Authorization is filtered on construction/transition; explicit Client/request overrides remain. URL/residency provenance lets mode changes remap default/global/us/eu mTLS roots, without rewriting explicit roots. Certificates never become foreign credentials. Transport mTLS is not a substitute for this protocol; provider/workload WSS auth remains unimplemented.
Structured parsing
Descriptor syntax, examples and helper composition are in HELPERS. Schema plus application validator replaces class-derived schema/Pydantic; the SDK does not validate arbitrary schemas or coerce JSON types to emulate objects. Validators own validation/defaults and must return JSON-native values or the supported nonfinite markers. Recursively invalid/truncated/overlong/surrogate UTF-8 strings or map keys fail safely with validator_failed, without private callback data. Raw binary transport is unaffected.
openai_response:parsed/1 returns a separate ordered path/value component with
zero-based original positions. False/zero/empty/null survive; applicable unparsed
slots contain null and ordinary unparsed values give an empty list. It does not
overwrite server parsed/output_parsed/parsed_arguments extras or metadata.
Custom/unknown calls remain rather than being dropped as by pinned Chat parsing.
Computed first-truthy output_parsed is not implemented or confused with a server
extra/first-non-null getter. Parsed-raw cache/ownership is canonical above.
HTTP errors classify before validation; parser/callback errors do not retry HTTP. Malformed envelopes give invalid_response; callback error/exception/bad return/ non-JSON result gives validator_failed without reason/stack/text. Refusal/empty content skips content validation. Chat examines every choice for length/content filter; any retained completion is explicit immutable error data. Stream validation runs in the consumer, so another holder can still close transport while it blocks. No automatic tool execution occurs.
Buffered Chat parse sends stream=false and requires strict=true function input tools. Root local parse callbacks are stripped from the wire; matched arguments otherwise decode JSON. Generated helper header can be overridden/omitted. Responses parse adds no such helper header, matches namespaces/deferred self-namespace, and parses only final_answer or absent/null phase, not commentary or unknown phase. Typed-tool callbacks validate independently of wire strict flag.
Responses text_format conflicts with the format key in its text object, even null. Local output_parser absent/undefined inherits, null disables text parsing. Effective extra_body input participates in latest configuration_update: plain-text reset disables inferred parsing, explicit parser plus reset rejects, changed schema requires explicit parser or null. Other parser context uses original Params, independent of wire extras. Buffered failed/incomplete need not follow Stream's completed-only final rule. Buffered Responses parse with stream=true retains its buffered post-parser choice, not a semantic Stream; SSE/non-model envelopes fail safely. Supported high-level wrapper projections remain finite, not full schema closure.
Resource-specific behavior
Method catalogues, results and mode support are in API, with composed polling/uploads in HELPERS. The following differences affect how applications interpret results; they do not add server policy validation.
- Responses failed/incomplete HTTP success remains a successful Response value with error/incomplete_details retained. Server cancellation is distinct from local I/O cancellation; completion can win. No cancellation helper invents a cancelled status, polls automatically or generates a replacement.
- Compaction is stateless; encrypted output stays opaque/in order and its ID is not an ordinary stored Response ID. Count generates no answer/stored object and is not a local tokenizer. Their distinct defaults/descriptors remain; unavailable nested alias/exclusion traversal fails rather than pretending to be complete. Body modes exist where documented; semantic SSE is not implied.
- Named Responses input/message/text/format/reasoning/prompt-cache TypedDict positions support omission; other tool/input/conversation/annotation/logprob unions can remain JSON pass-through. Schemas, metadata and arbitrary user dictionaries are not recursively pruned. Extra-body GET data is allowed; delete has no named body to prune. None delete parse cannot itself prove deletion. Removed SDK DELETE Accept falls back to /; Authorization omission is separate.
- Embeddings with omitted encoding_format send base64 and auto-decode string vectors into native-endian IEEE float32. Explicit float/base64/null never auto-decodes; original named choice, not extra_body wire override, selects it. Numeric vectors stay unchanged; malformed automatic buffers/null/empty data fail safely. ASCII non-alphabet bytes are ignored, final padding required, decoding stops at completed padding: AAAAAA= rejects, AAAAAA==garbage gives one zero float; non-ASCII rejects. Native/json maps preserve nonfinite markers; to_json emits null. This differs from Chat parsed-value JSON projection and never permits those markers in requests.
- File create extracts its source before form extra-body merge; a file key in extras can coexist rather than replacing it. Structured expires_after uses bracketed form fields, without invented retention. Content returns decoded bytes, unlike the Python legacy wrapper; upload permission does not imply download permission. Explicit Body enables progressive reading.
- Audio text/srt/vtt uses decoded UTF-8 text and Body materialization for supported normal/raw/header-raw/Body paths, not the generic text path's legacy cap. Unknown formats use non-strict base fallback. Voice create requires name+audio_sample+consent or name+prompt+type before credentials/HTTP, without extra enum/account-policy validation. Base64 image output remains a wire string, not an image decoder/player.
- Polling returns terminal models even on failed/cancelled status; inspect data. Files wait checks retrieval errors, elapsed time, then subsequent terminal status; a subsequent terminal response can still time out. Vector-store maximum wait starts after create/upload/attach, zero prevents the first poll, and an in-flight terminal result can survive clock expiry. Batch max wait is an explicit Erlang extension. Only an explicitly supplied interval sets a custom-interval header. Request overrides in creation apply only there, not every poll. Full intervals/zero/default rules are in HELPERS.
- Bulk upload ordinary errors finish the queued uploads under the sync mapping; cancellation/Client close starts no new uploads and confirms active cleanup. Mailbox receive only handles its own aliases/monitors. Parent/composite IDs validate before source opening/credentials/HTTP, intentionally earlier than Python. upload_summary preserves original error, confirmed File IDs, unknown outcomes and local cleanup status. No batch create follows upload failure; no remote rollback.
- Grader content supports singular/array text/image/audio variants. Optional image detail stays unset by default, null only when missing defaults are requested; no invented auto value. Vector-store content is a JSON Page, not File bytes.
- Conversation children require explicit deletion before parent. Skill default version must change before its deletion; parent deletion may cascade but is not a per-child delete check. Project archive is not deletion. No implicit grants, policy restoration or remote rollback occurs. Issued secrets are private data; issuance alone does not open a session or invent a revoke operation.
- Platform None casts yield null independently of successful body format; legacy binary wrappers map to bytes plus existing raw/Body. Ordinary completion SSE uses the shared Stream; repeated parse shares the cursor. Model output_text is not a generic platform accessor. HTTP SDP uses raw SDP if session is omitted, multipart for explicit null/present session. Computed Content-Type wins; caller Accept can override/omit. No WebRTC media engine is included.
- Administrative auth is explicit even when a project-role path omits /organization; regular callbacks do not run. External-key creation uses its pinned alternative presence groups before credentials/HTTP. Certificate POST Pages retain their method/body on continuation; usage/cost arrays can be model values rather than Pages. Local success is not proof of remote privileges, persistence or cleanup.
Webhook verification
Verification uses the Client's immutable secret snapshot, including after HTTP close, without API-key callbacks/network. Explicit secret, even empty, overrides; absent/null/undefined inherits. Original UTF-8 payload bytes and ordered header pairs are required, not re-encoded JSON. Required header names are case-insensitive, first matching pair wins. Tolerance is integer seconds, default 300; inclusive Now±tolerance accepts, zero means current second and negative rejects all. Current timestamp parsing accepts signs/whitespace/leading zeroes, Unicode decimal digits and underscores; original text is used in signing. Stricter parsing is not implemented by this documentation change.
Signed bytes join ID, original timestamp and body with dots. A whsec_ secret uses the existing permissive Base64 suffix decoder (ignored non-alphabet ASCII, surplus padding); malformed encoding is an input error. HMAC-SHA256/Base64 checks whitespace-split candidates in order after stripping a leading v1, per candidate; bare/other-version candidates are still compared. Equal-length ASCII content uses crypto:hash_equals/2; a reached non-ASCII candidate is an input error. Mismatch/window/timestamp failure is invalid_webhook_signature; missing/malformed inputs or unknown options invalid_argument, never private diagnostics. This is local verification, not unwrap, typed events, an HTTP receiver or proof of delivery.
Raw Realtime WebSockets
openai_realtime:connect/2 opens the stable raw Realtime connection immediately,
requiring a live Client config snapshot. Opening from a closed HTTP Client is an
Erlang restriction. No deferred manager queue, typed event engine or reconnect.
Connection lifetime is independent once opened; use the canonical ownership rules.
Routing and authentication
Absent/null/undefined websocket_base_url derives from effective HTTP base/residency; empty constructor value yields relative routing, while copy empty/null/undefined inherits. A region conflicts with explicit non-null WS override, including empty, before normalization; regional copy clears inherited override. Explicit HTTPS/WSS selects its own credential destination, HTTPS becomes WSS; trailing slashes are stripped and /realtime appended before query. Relative nonempty URLs, WS/HTTP, userinfo/fragment and literal/encoded dot segments reject. No HTTP foreign-origin policy is applied to this explicitly configured destination. Handshake redirects are not followed/replayed; failure uses the HTTP error layer.
WS defaults shallow-merge logical query with HTTP encoding, selected URL query overrides encoded keys, then per-call extra_query retires whole same-named defaults and overrides URL. Per-call null is blank and arrays repeat keys; default arrays use brackets. Ordered repetitions remain; ambiguous omit/undefined repeats reject.
Bearer selection is independent of URL. Callback runs once at opening, even for Authorization override/omit, with the shared safe worker; admin never falls back. An empty callback/admin-only Client can reach the endpoint without Authorization, as pinned Realtime does. Platform/account/custom defaults then connection headers follow normal merge/omit rules; one final Authorization or none. Handshake secret configuration is discarded after upgrade. Provider/workload/X.509 auto-auth is absent.
Budgets and outcomes
The fixed network-opening budget is 10000ms after callback, covering DNS/TCP/TLS/ upgrade without progress resets. Optional total_timeout_ms starts at invocation and includes config/callback/startup/network; supervision queue waiting cannot be preempted. Config lookup retains 1000ms, worker registration/init 2000ms budgets. HTTP phase timeout/max_retries is not WS policy; callback without total can wait indefinitely until lifecycle cancellation.
Send acknowledgement has a 10000ms queue/transport budget; one application send is in flight. Matching send completion means transport return, not peer receipt. Timeout/error closes the session without retry, even if bytes were already sent. A 12000ms caller guard aborts an unresponsive driver without claiming cleanup. Receive defaults unbounded; milliseconds/null/zero are extensions. The driver makes absolute timeout decisions and leaves undelivered data queued rather than losing late replies to a separate caller timer.
Close defaults code 1000/empty UTF-8 reason, validates codes and ≤123 reason bytes. Peer-handshake budget is 10000ms, then separate 2000ms cleanup; shutdown skips peer wait. Active success needs worker/Gun termination and marked driver DOWN; unmarked failure is not success, dead close no-op no historical proof. Other operations fail safely while closing. Normal close returns closed with available ws_close code/reason; abnormal transport returns connection_error, preserving available close details without inventing them. Protocol/API error messages remain received data, not automatic transport failure or reconnection policy.
Fixed limits: one message 1 MiB, incoming queue 16 messages/1 MiB, admitted outgoing queue 8 messages/1 MiB including in-flight work. Oversized/full outgoing work rejects without closing. Incoming message/queue overflow closes transport, fails waiters, retains already accepted bounded bytes for owner reads, then reports terminal error until explicit close. No silent drop/truncation. Credits replenish on consumption/closing; socket/in-flight data can overshoot queue budget, and mailboxes/parser/VM memory are not bounded. These are explicit Erlang restrictions, not Python's unbounded max_size or native WebSocket high-water semantics.
websocket_connection_options must be empty; compression/extensions/subprotocol, proxy and transport mTLS reject before callback/network. Verified CA/hostname remains mandatory. Gun assembles messages and handles ping/pong; complete fragmentation/heartbeat/pong-timeout parity is unverified. No typed iterator, automatic reconnect/replay, cookies or other WS namespaces are implied.
Remaining limitations
The implemented method list is in the mapping, not a promise of full pinned schema/Pydantic or positive live parity. Finite model coercion, named-view collisions, Page formatting/truthiness, timestamp/Retry-After leniency and charset aliases retain their current behavior. Optional codecs and buffered limits remain CAP-0041/CAP-0042 boundaries. CONNECT write validation and direct blocked-TLS cleanup remain separate CAP-0039/CAP-0040 concerns.
Typed Realtime events/helpers/reconnect, webhook unwrap/event models, a dedicated Azure OpenAI client, native executable/MFA discovery and provider/workload WSS authentication are not implemented. Supplying credential callbacks is separate. No planned interface should be treated as an available call.
Positive service coverage can require permissions, real consent recordings, cloud metadata/roles or an available endpoint. Deprecated operations excluded from the first release are recorded in release notes; complete reproduction of deprecated pinned SDK APIs is no longer a first-release goal. Historical evidence remains history, not positive coverage of the new release scope. Upload success does not establish download; completed-before-cancel does not establish cancellation; empty lists do not prove nonempty-list data behavior. Stored-lifecycle/attribute-consistency investigations do not justify a server-cause assumption or an SDK workaround. Historical local, reference and live evidence remain separate; these text changes close no live gap.