Public helpers
Public workflows built on the resource and common SDK APIs. These
functions compose requests, iteration, parsing or resource lifetime. Basic
Client/auth operations, Response parsing/accessors, Body readers, Stream pulls
and Page accessors remain in API.md. A name containing parse, stream or
fold alone does not determine the classification: files:retrieve_content
performs one direct HTTP operation.
- Buffered structured parsing
- Responses SSE streams
- Chat streaming helpers
- Polling comparison
- Files processing
- Chunked uploads
- Vector-store workflows
- Iteration and lifetime helpers
- Pure accumulators
Shared rules
Examples require a started openai application and an open Client
created as shown in Client setup. Params means a
caller-supplied valid parameter map for that method; IDs must name accessible
resources, paths must exist, and download directories must already exist.
Examples are independent, not one sequence to run against the same objects.
They can create chargeable remote resources; local cleanup never implies
remote deletion. No examples execute tools automatically.
Helpers return safe {error, openai:error()} tuples for SDK failures unless
otherwise stated. Application iteration callback exceptions propagate when
cleanup succeeds; Body cleanup failure has the exception behavior described
under iteration and lifetime helpers.
Validators instead produce a safe validator_failed. HTTP
status/transport errors retain the shared error contract.
Use the core metadata accessor for the returned Response/Page/Body/Stream;
polling returns metadata from the terminal retrieve, not the initial create.
Read Stream metadata before close and Body metadata before release. Immutable
models survive local cleanup; a repeated raw/Body parse follows the stored
wrapper's cache/cursor rules, not a new helper invocation.
Each underlying request uses Client retry/timeout policy unless the specific
helper accepts an override. Polling is additional HTTP, not a retry; no helper
restarts an entire failed workflow. Do not infer arbitrary normal/raw/Body mode
support from a direct method: the restrictions below are intentional.
The mapping lists public resource workflows, iteration helpers and accumulators separately from direct operations and common SDK primitives. The pinned Python SDK is an external behavioral reference, not an Erlang runtime dependency. Implementation, local/reference coverage and positive live coverage are distinct.
Buffered structured parsing
| Public function | Counterpart / result |
|---|---|
openai_chat_completions:parse/2,3 |
chat.completions.parse; normal immutable Response |
openai_beta_chat_completions:parse/2,3 |
Beta alias of the same implementation |
openai_responses:parse/2,3 |
responses.parse; normal immutable Response |
Each resource exports parse(Client, Params) and parse(Client, Params, Options).
Client has type openai:client(); Params/Options use the module's exported
parse_params()/parse_options() types (beta reuses Chat's types). Both return
{ok, openai_response:response() | openai_body:body()} | {error, openai:error()}.
Chat Params reuse create fields except stream; Responses adds text_format
and local output_parser. Options reuse request extras, retry/timeout and Body
limits. Default modes are parsed_chat_completion and parsed_responses.
The core parsed value accessor reads the separate
derived values; it is not another create/validation workflow.
A descriptor is #{name := binary(), schema := map(), parse := Validator}.
Validator receives original text/arguments bytes and returns {ok, Value} or
{error, Reason}. The application owns validation; no schema validator, class
inference or hidden JSON-type conversion is installed.
Schema = #{
<<"type">> => <<"object">>,
<<"properties">> => #{<<"ok">> => #{<<"type">> => <<"boolean">>}},
<<"required">> => [<<"ok">>],
<<"additionalProperties">> => false
},
Validate = fun(Bytes) ->
case json:decode(Bytes) of
#{<<"ok">> := true} = ParsedValue -> {ok, ParsedValue};
_ -> {error, invalid}
end
end,
TextFormat = #{name => <<"flag">>, schema => Schema, parse => Validate},
{ok, Response} = openai_responses:parse(
Client,
#{model => <<"gpt-6-luna">>, input => <<"Return ok=true.">>, text_format => TextFormat}
),
{ok, #{values := Values}} = openai_response:parsed(Response).
%% Example Values: [{[<<"output">>,0,<<"content">>,0,<<"text">>],
%% #{<<"ok">> => true}}]. Indices follow actual wire order.
Chat uses response_format => {typed, TextFormat}. Responses output_parser => Fun
overrides only local parsing; null disables it, and undefined inherits the
descriptor's parse callback.
It is never sent. A plain JSON format map does not imply typed parsing.
Strict function tools may carry a root parse => Validator, stripped from the
wire; without it, matching strict arguments use JSON decoding. Tools never execute.
For example, using descriptor TextFormat above and valid Chat messages/model,
openai_chat_completions:parse(Client, ChatParams#{response_format => {typed, TextFormat}})
creates one completion. openai_beta_chat_completions:parse(Client, ChatParams)
is the same helper implementation under the beta facade; it does not add a
second operation unless the caller invokes both. Normal parsing uses one POST
(/chat/completions or /responses), then local validation. Explicit repeated
parse on parsed-raw never sends another POST.
Validator failures return safe validator_failed, without their private reason.
Successful validator strings and object keys must be valid UTF-8, recursively;
invalid or truncated sequences also return validator_failed and are not cached.
Paths use binary keys/zero-based array positions identifying original text or
arguments. Derived false/0/empty/null values are retained. to_map/to_json
retain original server extras, not injected parsed members.
New parsed-raw differs from older raw methods: {raw, parsed_responses} or
{raw, parsed_chat_completion} returns Body with fully buffered bytes and lazy
validation. Chat also has {body, parsed_chat_completion} for lazy HTTP reading.
There is no openai_responses:parse/2,3 Body wrapper or typed SSE parse helper.
{ok, ParsedRawBody} = openai_responses:parse(
Client,
Params,
#{response_mode => {raw, parsed_responses}}
),
try
{ok, ParsedResponse} = openai_body:parse(ParsedRawBody),
% cached success; no HTTP/validator repeat
{ok, ParsedResponse} = openai_body:parse(ParsedRawBody),
{ok, Bytes} = openai_body:content(ParsedRawBody),
Metadata = openai_body:metadata(ParsedRawBody)
after
ok = openai_body:release(ParsedRawBody)
end.
openai_body:close/1 and openai:close/1 preserve complete cache/success until release;
materialized Response values survive release. Failed validation is not cached;
explicit parse retries validation only. Partial reading never enables replay.
The raw_bytes and decoded_bytes keys in the request body_limits map apply both to explicit parsed-raw
and to parsed-raw selected by the exact true raw header, including gzip bodies.
Invalid limits return invalid_argument before credential callbacks or HTTP.
See contracts and the
runnable example.
Responses SSE streams
openai_responses:stream(Client, Params) and stream(Client, Params, Options)
return {ok, openai_stream:stream()} | {error, openai:error()}. This call opens
the request immediately; Python's manager defers opening until context entry.
No separate Erlang manager process is needed. The helper requires
model and input for a new response. Alternatively supply response_id to
retrieve a stored stream, with optional include, include_obfuscation,
starting_after, tools and text_format. Do not mix new-response parameters
with response_id. The helper filters its cursor locally after accumulation;
ordinary streaming retrieve sends starting_after to the server. Neither reconnects.
{ok, Stream} = openai_responses:stream(
Client,
#{model => <<"gpt-6-luna">>, input => <<"Reply briefly.">>, store => false}
),
try
case openai_responses_stream:get_final_response(Stream) of
{ok, Response} -> openai_response:output_text(Response);
{error, Error} -> maps:get(kind, Error)
end
after
ok = openai_stream:close(Stream)
end.
| Operation | Result |
|---|---|
openai_responses_stream:until_done(Stream) |
ok \| {error, Error}; drains the same cursor |
openai_responses_stream:get_final_response(Stream) |
{ok, Response} \| {error, Error}; requires completed |
response.failed and response.incomplete are delivered as events, followed
by eos; they are not completion. Without response.completed, the final
helper returns response_not_completed. Transport/decode errors remain
separate. Metadata belongs to the opening HTTP request; read it before close.
Draining never closes or deletes a stored Response automatically, so retain
the try/after below even after a successful final result.
Events use binary JSON keys. Text/function delta wrappers add snapshot, text
done adds parsed, and completed carries the parsed response map. Locally use
openai_response:construct(EventMap, stream_event) with existing to_map/1,2
and to_json/1,2; this maps event model helpers without an HTTP request.
Its metadata status is undefined, not an invented server status. Streaming
final values carry real opening metadata but body/1 rejects them: an event
value is not a buffered copy of the original SSE HTTP body.
Optional text_format is #{name => Name, schema => StrictSchema, parse => Validator}.
The application supplies the supported strict schema and
fun((UTF8Bytes) -> {ok, JSONValue} | {error, Reason}) implementing validation,
coercion and defaults. SDK does not validate arbitrary JSON Schema. Only schema
is sent; conflicts with the <<"format">> key in the <<"text">> object are rejected. Callback failures become safe
validator_failed, without reason/text. Final-answer/null/missing phase is
parsed; commentary is not. Strict function arguments use JSON decoding; a local
parse callback on a typed tool supplies application validation, independently
of its wire strict flag. Tools are never executed.
The high-level helper skips only the confirmed service keepalive; raw preserves it. This is an explicit difference from pinned Python, not a generic unknown-event filter.
Options reuse phase timeout, optional total deadline, retries and extras;
stream_limits optionally sets nonnegative line_bytes, event_bytes,
snapshot_bytes or null, with no default byte cap. See
stream contracts for limits, errors and lifecycle.
Python counterparts: raw Stream,
Responses stream/state.
Typed text format
The application validates the decoded value; supplying a schema alone does not install a validator.
Format = #{
name => <<"Answer">>,
schema => #{
<<"type">> => <<"object">>,
<<"properties">> => #{<<"value">> => #{<<"type">> => <<"string">>}},
<<"required">> => [<<"value">>],
<<"additionalProperties">> => false
},
parse => fun(Bytes) ->
case json:decode(Bytes) of
#{<<"value">> := Value} = Data when map_size(Data) =:= 1, is_binary(Value) ->
{ok, Data};
_ ->
{error, invalid_answer}
end
end
},
{ok, Stream} = openai_responses:stream(
Client,
#{
model => <<"gpt-6-luna">>,
input => <<"Return value OK.">>,
text_format => Format,
store => false
}
),
try
openai_responses_stream:get_final_response(Stream)
after
ok = openai_stream:close(Stream)
end.
Streaming retrieve
Use an accessible stored Response ID. This helper accumulates first, then filters events locally; it still needs the original lifecycle events.
{ok, Stream} = openai_responses:stream(
Client,
#{response_id => StoredID, starting_after => 5}
),
try
NextEvent = openai_stream:next(Stream),
{NextEvent, openai_responses_stream:get_final_response(Stream)}
after
ok = openai_stream:close(Stream)
end.
The runnable local example demonstrates all three with fake credentials and saved captures.
Chat streaming helpers
openai_chat_completions:stream(Client, Params[, Options]) opens a high-level
Chat event cursor. Omit the stream parameter: this helper sets it itself.
openai_stream:next/1 returns {ok, EventMap}, eos, or a safe error tuple.
openai_chat_completions_stream:until_done/1 drains and returns {ok, Cursor};
get_final_completion/1 drains and returns {ok, Response} or an error.
current_completion_snapshot/1 reads the current immutable snapshot without
draining. close/1 aliases openai_stream:close/1. Close cursors in try/after.
Chat named top-level parameters accept atom/binary spellings; nested JSON
message/tool fields use binary keys, as in the resource examples.
Typed response_format is {typed, #{name := binary(), schema := map(),
parse := fun((binary()) -> {ok, JSONValue} | {error, term()})}}. The schema is
sent with strict=true; the application callback validates final content and
returns its parsed value. Partial JSON snapshots do not invoke this callback
and do not claim schema validity. No Pydantic or JSON Schema validator is built in.
Format =
{typed, #{
name => <<"Flag">>,
schema => #{
<<"type">> => <<"object">>,
<<"properties">> => #{<<"ok">> => #{<<"type">> => <<"boolean">>}},
<<"required">> => [<<"ok">>],
<<"additionalProperties">> => false
},
parse => fun(Bytes) ->
case json:decode(Bytes) of
#{<<"ok">> := Flag} = Value when is_boolean(Flag), map_size(Value) =:= 1 ->
{ok, Value};
_ ->
{error, invalid_answer}
end
end
}},
{ok, Stream} = openai_chat_completions:stream(Client, Params#{response_format => Format}),
try
openai_chat_completions_stream:get_final_completion(Stream)
after
ok = openai_stream:close(Stream)
end.
Strict function tools are parsed as JSON; an optional atom parse callback on
a binary-keyed strict function tool supplies application validation and is never
sent over HTTP. Tools are not executed. Invalid validators produce
validator_failed; typed length/content_filter finishes produce
length_finish_reason/content_filter_finish_reason, with an optional immutable
completion on the Error. EOF alone does not assert model completion.
For offline accumulation, new(Format, Tools) -> {ok, State}, then
handle_chunk(State, Chunk) -> {ok, NewState, Events} on
openai_chat_completions_stream; snapshot/final helpers also accept this state.
This pure API does not create HTTP metadata or establish transport completion.
Polling comparison
All intervals and maximum waits below are milliseconds. Polling does not add an HTTP deadline or delete remote objects. Inspect returned terminal data; a returned failed resource is not a successful processing outcome.
| Helper | Interval / default | Maximum wait / zero | Terminal failure | Request overrides |
|---|---|---|---|---|
openai_files:wait_for_processing/2,3 |
poll_interval_ms, 5000 |
max_wait_ms, 1800000; zero still retrieves initially and can wait/retrieve again before checking elapsed time |
error/deleted returned as Response |
Poll settings only; HTTP uses Client policy. |
openai_vector_stores_files:poll/2,3 |
Explicit interval, otherwise first server hint or 1000 | Optional max_wait_ms, unbounded by default; zero sends no poll GET |
Non-in_progress status returned, including failed/cancelled |
Poll settings only; create-and-poll HTTP overrides apply to creation only. |
openai_vector_stores_file_batches:poll/2,3 |
Explicit interval, otherwise first server hint or 1000 | Optional max_wait_ms, unbounded by default (Erlang extension); zero sends no poll GET |
Stops when the <<"in_progress">> value in the <<"file_counts">> object is zero; inspect failed counts/status |
Poll settings only; create-and-poll HTTP overrides apply to creation only. |
Vector-store maximum waits bound the loop/sleep, not an in-flight HTTP request. Only an explicitly supplied vector-store interval sets the custom poll header. Client close interrupts waiting. Upload-and-poll workflows have their own finite option sets; they do not forward arbitrary request overrides to every GET. See the individual sections for ordering, errors and remote ownership.
Files processing
openai_files:wait_for_processing(Client, FileID[, PollOptions]) maps Python
client.files.wait_for_processing. It initially calls openai_files:retrieve/2,3,
then additional GETs while processing remains nonterminal. It returns
{ok, Response}, including terminal error/deleted; inspect status rather
than assuming indexing succeeded. It does not create or delete a File.
{ok, File} = openai_files:wait_for_processing(
Client,
FileID,
#{poll_interval_ms => 5000, max_wait_ms => 1800000}
),
Status = maps:get(<<"status">>, openai_response:to_map(File)).
Poll options: poll_interval_ms => non_neg_integer() (5000 default),
max_wait_ms => non_neg_integer() (1800000 default). The initial terminal result
returns immediately. Otherwise the helper waits, retrieves, then checks elapsed
time; this is not an added HTTP deadline. Exhaustion returns timeout with
phase => file_processing. Client close interrupts waiting. See
polling and binary details.
Counterpart: pinned Files.
Both options accept nonnegative integers only; this helper has no per-request
raw/Body or HTTP-extra options. After a nonterminal initial result it sleeps,
retrieves, checks retrieval errors, then elapsed time, then the new status.
Thus max_wait_ms => 0 does not suppress the initial GET or guarantee only one
GET. Waiting does not cancel server processing; the caller retains ownership.
Chunked uploads
openai_uploads:upload_file_chunked(Client, Params[, Options]) maps Python's
same-named helper: POST Upload, sequential POST parts, POST complete. Params
are file, mime_type, purpose, with optional filename, bytes,
part_size and md5. Use a positive part_size; the default is 67108864 bytes.
It is a byte count, not an HTTP limit. The current finite contract also retains
reference edge cases: zero completes without parts; a negative value sends all
binary bytes in one part, while file sources support -1 for read-all and give
file_error for other negatives. null/undefined select the default.
The finite source forms here are bytes, {path, Path} (eager snapshot), or
{file, Path} (SDK-owned lazy file), not producer callbacks.
{ok, Upload} = openai_uploads:upload_file_chunked(
Client,
#{
file => {file, UploadPath},
mime_type => <<"text/plain">>,
purpose => <<"assistants">>,
part_size => 65536
},
#{max_retries => 0}
),
UploadData = openai_response:to_map(Upload).
Counterparts: client.uploads.create/complete/cancel/upload_file_chunked and
client.uploads.parts.create. The helper sends parts sequentially (default
67108864 bytes), closes local file I/O on error, and completes with ordered part IDs.
Binary source requires filename and bytes; {file,Path} infers basename/stat size,
explicit metadata wins. The helper does not retry the whole workflow or automatically
cancel a remote Upload. For explicit finally cleanup of IDs, use the low-level
methods as in uploads_chunked.erl.
Completed Upload contains a File; delete that File separately when no longer needed.
Explicit response_mode is rejected by this helper. Request extras and
timeout/retry overrides apply to each request; a legacy raw header is parsed
for intermediate IDs and can select the final raw result. Use direct operations
for Body-mode workflows. Stop at the first create/part/complete error. A failed
workflow can leave a remote Upload or File; errors do not provide the vector
helper's upload_summary. Use direct operations when the application must
persist every intermediate ID and explicitly cancel an unfinished Upload.
Vector-store workflows
Client is an open Client. FileIDs = #{vector_store_id => VectorStoreID, file_id => FileID}
and BatchIDs = #{vector_store_id => VectorStoreID, batch_id => BatchID} use accessible,
nonempty binary IDs. Sources must be readable. All results below are normal
{ok, Response} or safe errors, not selectable raw/Body result wrappers.
| Public signature (final Options may be omitted) | Base operations / Options |
|---|---|
openai_vector_stores_files:poll(Client, FileIDs, PollOptions) |
Retrieve attachment repeatedly; poll options only |
openai_vector_stores_files:create_and_poll(Client, FileIDs, Params, Options) |
Attach existing File once, then poll; attributes/chunking in Params; poll and create request overrides in Options |
openai_vector_stores_files:upload(Client, VectorStoreID, Params, Options) |
openai_files:create/2,3 with purpose assistants, then attach; file/chunking in Params; Options must be #{} |
openai_vector_stores_files:upload_and_poll(Client, VectorStoreID, Params, PollOptions) |
Upload, attach, poll; file/attributes/chunking in Params |
openai_vector_stores_file_batches:poll(Client, BatchIDs, PollOptions) |
Retrieve batch repeatedly; poll options only |
openai_vector_stores_file_batches:create_and_poll(Client, VectorStoreID, Params, Options) |
Create file batch once, then poll; create Params and create request/poll Options |
openai_vector_stores_file_batches:upload_and_poll(Client, VectorStoreID, Params, Options) |
Concurrent openai_files:create/2,3, then one batch create, then poll; required files, optional file_ids/chunking; max_concurrency (default 5, positive integer) and poll options |
openai_vector_stores_files:poll(Client, FileIDs, PollOptions) and
openai_vector_stores_file_batches:poll(Client, BatchIDs, PollOptions) return terminal
Response values, including failed/cancelled status. poll_interval_ms is an
optional nonnegative integer; absent uses the first openai-poll-after-ms hint,
then 1000ms default. Only an explicit interval sends the custom poll header.
max_wait_ms is optional, defaults unbounded; zero performs no poll GET.
It limits the loop/sleep, not the HTTP request's own timeout/retry policy.
The batch maximum is an Erlang extension.
File helpers (each final Options may be omitted):
{ok, Attached} = openai_vector_stores_files:create_and_poll(
Client,
FileIDs,
#{attributes => #{<<"checked">> => true}},
#{poll_interval_ms => 100}
),
{ok, Uploaded} = openai_vector_stores_files:upload(
Client,
<<"vs_example">>,
#{file => {<<"notes.txt">>, {file, UploadPath}, <<"text/plain">>}}
),
{ok, Indexed} = openai_vector_stores_files:upload_and_poll(
Client,
<<"vs_example">>,
#{file => {<<"notes.txt">>, <<"notes">>}},
#{max_wait_ms => 5000}
),
{ok, Batch} = openai_vector_stores_file_batches:create_and_poll(
Client,
<<"vs_example">>,
#{file_ids => [<<"file_example">>]},
#{max_wait_ms => 5000}
),
Result = openai_vector_stores_file_batches:upload_and_poll(
Client,
<<"vs_example">>,
#{
files => [{<<"a.txt">>, <<"a">>}, {<<"b.txt">>, <<"b">>}],
file_ids => [<<"already_uploaded">>]
},
#{max_concurrency => 5, max_wait_ms => 5000}
).
Uploads use purpose assistants; the caller owns every created remote File.
Invalid parent/path IDs fail before opening sources, credentials or HTTP; caller
mailbox messages and unrelated monitor notifications are preserved.
No automatic rollback occurs. Errors may contain upload_summary with original
error, acknowledged uploaded_files (input index/File ID/request ID),
unknown_inputs, not_started_inputs and local_cleanup => confirmed | unconfirmed.
Keep those IDs for manual cleanup. Ordinary upload failure drains the queue;
Client close/cancellation stops admission and cancels active work. No batch is
created when uploads fail. Unconfirmed local cleanup is an error, not success.
Poll time starts after creation/upload/attachment; no hidden helper HTTP deadline.
To poll existing attachments directly, use
openai_vector_stores_files:poll(Client, FileIDs, #{max_wait_ms => 5000}) or
openai_vector_stores_file_batches:poll(Client, BatchIDs, #{max_wait_ms => 5000}).
These calls do not upload or create a batch, and do not cancel remote indexing
when the local maximum expires.
These map the same-named Python vector-store helpers. Python file polling's
max_wait_seconds maps to integer max_wait_ms; the batch maximum is an
explicit Erlang extension. Poll options accept nonnegative integers (omission
or undefined leaves the default); null is not accepted. File polling stops
when status is not in_progress, including failure/cancellation; batch polling
uses the <<"in_progress">> value in the <<"file_counts">> object, not just status. Inspect terminal data yourself.
Missing/malformed polling data gives invalid_response.
Create request overrides apply to creation only, not subsequent polling.
Poll requests use Client HTTP policy; no response_mode option is accepted.
The caller owns uploaded Files independently of their VectorStore attachment:
deleting an attachment/store is not File deletion. Retain acknowledged IDs and
unknown outcomes for manual reconciliation. Ordinary concurrent upload errors
finish the queued work (sync mapping); cancellation/Client close stops admission
and confirms active worker cleanup within the existing bounded budget.
Iteration and lifetime helpers
These compose the common SDK primitives; they do not introduce endpoints or instantiate foreign manager objects. Callback state belongs to the caller. They never issue a second request to replay an already-open Body/Stream.
| Public function | Work, stopping and cleanup |
|---|---|
openai_stream:fold(Stream, Fun, Acc) |
Pull events, Fun(Event, Acc) returns next Acc or {halt, Acc}; returns {ok, Acc}/error and always closes Stream, including exceptions |
openai_stream:consume(Stream, Fun) |
Required arity-1 callback; stop halts, other values continue; returns ok/error and always closes; cleanup failure can replace normal result |
openai_page:fold(Page, Fun, Acc) |
Visit items, lazily fetch continuation pages as needed; returns {ok, Acc}/error |
openai_page:fold_pages(Page, Fun, Acc) |
Same, one callback per Page |
openai_body:fold(Reader, Fun, Acc) |
Pull chunks, Acc or {halt, Acc}; returns {ok, Acc}/error; always releases Body |
openai_body:with(Body, Fun) |
Return Fun(Body) result; finally release on return or exception |
openai_body:write_to_file(Body, Path) |
Same as stream_to_file with empty Options |
openai_body:stream_to_file(Body, Path, Options) |
iter_bytes then sequential file writes; ok/error; closes local file and releases Body |
Page callbacks also support {cont, Acc}. Early halt never requests the next
page. Exceptions propagate; Page owns no active cursor requiring release.
Each continuation can use the original Client's retry policy and preserves
request/query/options; repeated traversals can repeat HTTP. Loaded values
survive Client close, but continuation requires that Client context.
Continuation resets response_mode to page and removes the canonical
request raw marker; other request/query settings are retained. Client-default
raw markers still apply. Folds expect a Page from each continuation and return
invalid_response for a wrapper; use explicit get_next_page and parse/release
that wrapper when using those Client defaults.
For example, openai_page:fold_pages(Page, fun(PageValue, ItemCount) -> ItemCount + length(openai_page:items(PageValue)) end, 0)
counts loaded items across continuation pages. A Stream equivalent is
openai_stream:fold(Stream, fun(_Event, EventCount) -> EventCount + 1 end, 0), which closes the
cursor when it stops. openai_body:write_to_file(Body, DownloadPath) is the
default-options form of the file example below.
Stream/Body folds treat {cont, Acc} as an ordinary accumulator, not a control
marker. They attempt close/release even on early halt or callback exception. Body
release frees the cache and closes related cursors; it is stronger than
openai_body:close/1, which retains cache/parser buffers. Cleanup never deletes remote
resources. File helpers truncate the destination, do not create parents and
retain any partial file on failure. Options are iter_bytes options (chunk_size
positive integer/null/undefined), not new HTTP parameters.
Body cleanup failure: with/2 executes ok = openai_body:release(Body)
in after; fold/3, write_to_file/2 and stream_to_file/3 use this helper.
If release returns {error, CleanupError}, the helper raises
error:{badmatch, {error, CleanupError}}. This replaces a normal result,
including an error tuple, and can replace the original callback exception.
Only successful cleanup preserves the original result/exception. This is the
current implementation, not a guarantee that cleanup failures are returned as
error tuples. Changing that policy would require a separate runtime decision.
Stream folds differ: a cleanup error after normal return is returned as an error tuple; after a callback exception they attempt close and re-raise the original exception. Page folds have no cursor/cache owner to release.
{ok, First} = openai_page:fold(
Page,
fun(Item, _Acc) -> {halt, Item} end,
none
).
ok = openai_stream:consume(
Stream,
fun(Event) -> io:format("~p~n", [Event]) end
).
{ok, Reader} = openai_body:iter_bytes(Body, #{chunk_size => 65536}),
{ok, Count} = openai_body:fold(
Reader,
fun(Bytes, ByteCount) -> ByteCount + byte_size(Bytes) end,
0
).
{ok, Data} = openai_body:with(
Body,
fun(OpenBody) -> openai_body:json(OpenBody) end
).
ok = openai_body:stream_to_file(Body, DownloadPath, #{chunk_size => 65536}).
Prerequisites: an unconsumed Body or its complete cache, an owner-held Stream/Reader, an immutable Page, and a writable DownloadPath, as applicable. Python counterparts are stream iteration, auto-paging and response context/file helpers; these Erlang callback adapters and explicit release are language/lifetime mappings, not Python method aliases.
Pure accumulators
The public Chat accumulator uses new(Format, Tools) -> {ok, State} and
handle_chunk(State, Chunk) -> {ok, NewState, Events} | {error, Error}.
Chat snapshot/final functions also accept State. Input is decoded chunk
data, not arbitrary bytes. This exposes a pure Erlang state API inspired by
the pinned internal accumulator, not a direct public Python method. Responses
state transition exports marked -doc false are internal and are not part of
this usage reference. See stream contracts
and Chat helpers for parser/validator behavior.
{ok, State0} = openai_chat_completions_stream:new(#{}, []),
{ok, State1, Events} = openai_chat_completions_stream:handle_chunk(State0, Chunk),
Snapshot = openai_chat_completions_stream:current_completion_snapshot(State1).
Chunk must be a valid decoded Chat completion chunk. Pure state has no network ownership or local cleanup and cannot prove transport EOF, metadata or live completion. Preserve each returned state; do not use it as a second live cursor.
Runnable examples
See example commands for structured_parse, responses_stream, chat_completions_stream, pagination, http_body, uploads_chunked and vector_stores. Controlled fixtures and pinned comparisons are local evidence, not live E2E. Service availability and existing live gaps remain recorded separately; a live NOT RUN does not mean unimplemented.