Public API reference
- Pinned Python → Erlang API mapping
- Public helpers
- Reading the catalogue
- Organization administration
- Platform resources
- Buffered structured parsing
- openai:new/1
- openai:with_options/2
- openai:copy/2
- openai:is_closed/1
- openai:close/1
- openai:platform_headers/0
- Client request methods
- Multipart and upload sources
- Request security
- Basic resources
- Embeddings
- Models and moderations
- Files
- Responses
- openai_responses:create/2,3
- Responses SSE streams
- openai_responses:retrieve/2,3,4
- openai_responses:delete/2,3
- openai_responses:cancel/2,3
- openai_responses:compact/2,3
- openai_responses_input_tokens:count/2,3
- Chat Completions
- Buffered Chat methods
- Raw Chat streaming
- Chat streaming helpers
- Pagination and list resources
- Lazy HTTP bodies
- Realtime raw WSS
- openai_realtime:connect/2
- openai_realtime_connection
- Webhooks
- openai_webhooks:verify_signature/3,4
- Response values
- Options
- HTTP providers
- Subject workload authentication
- X.509 workload authentication
- TLS, proxy and redirects
- OpenAI and AsyncOpenAI
- Error values
- Media resources
- Audio
- Images
- Uploads
- Batches, fine-tuning and vector stores
This reference covers direct resource operations and common SDK APIs.
Public helpers documents composed parsing, polling, uploads,
accumulation, traversal and lifetime workflows. Classification follows behavior,
not function names. Local signature verification and model accessors remain here.
Start the openai application before Client operations. Client creation and
option derivation do not open network connections.
See CONTRACTS for shared lifecycle, cleanup guarantees and Python compatibility rules, and examples for exact compile/run commands. Client handles are opaque; do not inspect their fields. The canonical API mapping links pinned Python methods to current Erlang exports and usage sections. The tables here are usage summaries; they do not claim complete SDK parity.
Reading the catalogue
| Term | Meaning |
|---|---|
| Client | Opaque configuration handle sharing an HTTP context; close it when its work is finished. |
| Params | Method-specific request data; required fields and defaults depend on the method. |
| Options | Request controls such as timeout, retries, headers and supported result mode. |
| IDs | Nonempty binary path identifiers, or a named map for composite paths. |
| Response | Materialized model value with serialization and metadata accessors. |
| Page | Immutable list result; another page is fetched only on demand. |
| Stream | Pull cursor for events; close it to terminate reading and confirm cleanup. |
| Body | Lazy HTTP body handle; release it to free I/O, cursors and cached bytes. |
Named Params/Options keys shown as atoms are SDK controls or known request fields.
Nested JSON normally uses binary wire keys, for example
#{messages => [#{<<"role">> => <<"user">>, <<"content">> => <<"Hello">>}]}.
Some finite resource builders also accept known binary spellings; older Responses
builders use atom keys. Follow each method's Params contract rather than converting
all keys uniformly. Omission, undefined and JSON null are not interchangeable.
| Choose | Use | Result / ownership |
|---|---|---|
| Normal | Materialize the method's default value | Response, Page, binary or null, as documented per method. |
| Raw | Inspect bytes and metadata, then parse | Usually RawResponse; parsed-raw helpers instead return a buffered Body requiring openai_body:release/1. See parsed-raw lifetime; cache/modes are method-specific. |
| Body | Read HTTP chunks or materialize explicitly | Body; explicit release is required. |
| SSE | Pull semantic events from a streaming endpoint | Stream; close after consumption, including errors. |
These are choices only where a method supports them, not universal modes. Raw HTTP body iteration and SSE event iteration are different operations. Limits and buffering also differ by path; see the specific method below.
Organization administration
The 35 openai_admin_organization_* modules implement 143 direct HTTP methods.
See the compact administration method tables.
They reuse Client/Response/Page/Body; no call polls, grants access or rolls back
remote resources implicitly. Service permissions/availability remain separate.
Examples in this reference are independent. Bind the required IDs and request
data and supply a separate open Client for each example. The following example
requires an authorized AdminKey and OrgID; its AdminClient is closed locally
and is not the Client used in subsequent snippets.
{ok, AdminClient} = openai:new(#{
api_key => <<>>,
admin_api_key => AdminKey,
organization => OrgID,
max_retries => 0,
follow_redirects => false
}),
try
{ok, Page} = openai_admin_organization_groups:list(AdminClient, #{limit => 20}),
io:format("Groups: ~p~n", [length(openai_page:items(Page))])
after
ok = openai:close(AdminClient)
end.
All 143 select admin authentication explicitly; an ordinary credential/provider is not fallback and its callback is not invoked. AdminKey may instead come from OPENAI_ADMIN_KEY. Existing constructor/copy/env and header override/omission semantics remain unchanged; security is never inferred from URL.
| Family | Module and methods |
|---|---|
| admin_api_keys | openai_admin_organization_admin_api_keys: create, delete, list, retrieve |
| audit_logs | openai_admin_organization_audit_logs: list |
| certificates | openai_admin_organization_certificates: activate, create, deactivate, delete, list, retrieve, update |
| data_retention | openai_admin_organization_data_retention: retrieve, update |
| external_keys | openai_admin_organization_external_keys: create, delete, list, retrieve, validate |
| external_storage | openai_admin_organization_external_storage: create, delete, list, retrieve, validate |
| groups | openai_admin_organization_groups: create, delete, list, retrieve, update |
| groups.roles | openai_admin_organization_groups_roles: create, delete, list, retrieve |
| groups.users | openai_admin_organization_groups_users: create, delete, list, retrieve |
| invites | openai_admin_organization_invites: create, delete, list, retrieve |
| projects | openai_admin_organization_projects: archive, create, list, retrieve, update |
| projects.api_keys | openai_admin_organization_projects_api_keys: delete, list, retrieve, update |
| projects.certificates | openai_admin_organization_projects_certificates: activate, deactivate, list |
| projects.data_retention | openai_admin_organization_projects_data_retention: retrieve, update |
| projects.groups | openai_admin_organization_projects_groups: create, delete, list, retrieve |
| projects.groups.roles | openai_admin_organization_projects_groups_roles: create, delete, list, retrieve |
| projects.hosted_tool_permissions | openai_admin_organization_projects_hosted_tool_permissions: retrieve, update |
| projects.model_permissions | openai_admin_organization_projects_model_permissions: delete, retrieve, update |
| projects.rate_limits | openai_admin_organization_projects_rate_limits: list_rate_limits, update_rate_limit |
| projects.roles | openai_admin_organization_projects_roles: create, delete, list, retrieve, update |
| projects.service_accounts | openai_admin_organization_projects_service_accounts: create, delete, list, retrieve, update |
| projects.service_accounts.api_keys | openai_admin_organization_projects_service_accounts_api_keys: create |
| projects.service_tier_settings | openai_admin_organization_projects_service_tier_settings: retrieve, update |
| projects.spend_alerts | openai_admin_organization_projects_spend_alerts: create, delete, list, retrieve, update |
| projects.spend_limit | openai_admin_organization_projects_spend_limit: delete, retrieve, update |
| projects.users | openai_admin_organization_projects_users: create, delete, list, retrieve, update |
| projects.users.roles | openai_admin_organization_projects_users_roles: create, delete, list, retrieve |
| roles | openai_admin_organization_roles: create, delete, list, retrieve, update |
| spend_alerts | openai_admin_organization_spend_alerts: create, delete, list, retrieve, update |
| spend_limit | openai_admin_organization_spend_limit: delete, retrieve, update |
| usage | openai_admin_organization_usage: audio_speeches, audio_transcriptions, code_interpreter_sessions, completions, costs, decisions, embeddings, file_search_calls, images, moderations, vector_stores, web_search_calls |
| users | openai_admin_organization_users: delete, list, retrieve, update |
| users.roles | openai_admin_organization_users_roles: create, delete, list, retrieve |
| workload_identity_providers | openai_admin_organization_workload_identity_providers: create, delete, list, retrieve, update |
| workload_identity_providers.federation_rules | openai_admin_organization_workload_identity_providers_federation_rules: create, delete, list, retrieve, update |
Path IDs are nonempty unescaped binaries; compound IDs are exact named typed maps.
Params accept atom/binary wire names; duplicates fail locally. Required presence,
omit/undefined and null stay distinct. openai_admin_organization_external_keys:create/2,3 accepts the four
pinned AWS/GCP/Azure/OCI required groups; presence validation does not verify cloud
configuration or add server policy rules. Exported specs describe nested maps.
{ok, RawResponse} = openai_admin_organization_groups:retrieve(
Client,
GroupID,
#{response_mode => {raw, admin_groups_retrieve}}
),
{ok, Group} = openai_response:parse(RawResponse),
{ok, Group} = openai_response:parse(RawResponse),
Metadata = openai_response:metadata(RawResponse),
{ok, Binding} = openai_admin_organization_projects_groups_roles:retrieve(
Client,
#{project_id => ProjectID, group_id => ExistingGroupID, role_id => RoleID}
).
Groups/role lists use next-cursor Page: next becomes after only on explicit
get_next_page/traversal. Query/options/security are retained; no prefetch. Four
certificate activate/deactivate operations return single Pages via POST. Usage/
costs return Response models, not Pages despite data arrays. Page wrappers use
{raw,page} / {body,page}. Unix time filters and expiry use seconds; HTTP options
use milliseconds, without new polling/deadline defaults.
{ok, Body} = openai_admin_organization_usage:completions(
Client,
#{start_time => StartSeconds, end_time => EndSeconds, limit => 1},
#{response_mode => {body, admin_usage_completions}}
),
try
{ok, Usage} = openai_body:parse(Body),
{ok, Usage} = openai_body:parse(Body),
io:format("Usage: ~p~n", [openai_response:to_map(Usage)])
after
ok = openai_body:release(Body)
end.
Non-page models retain the non-strict successful text fallback: handle {ok,Text}
when is_binary(Text) before model helpers. Metadata/raw bytes, Body cache/
close/release and materialized values follow common contracts.
openai:close/1 only cleans local resources; remote deletion is explicit. The
runnable local example uses
fake credentials and no real organization changes.
Platform resources
All functions below use the existing Client pipeline and return {ok, Value} or
{error, Error}. Options is optional (omit its final argument for defaults).
Params accept atom or binary wire names; duplicate spellings are rejected.
Composite identifiers are named maps with exactly the documented keys.
No call polls, creates children or deletes remote resources implicitly.
Model casts retain the shared non-strict text fallback: a successful non-JSON
response can be a decoded binary rather than a Response. Check the value before
calling model helpers. none still returns null; binary casts return decoded
body bytes, with original entity bytes retained by raw/Body.
| Public signature | Required Params | Normal result / raw or Body cast |
|---|---|---|
openai_completions:create(Client, Params, Options) |
model, prompt |
Response / completion |
openai_containers:create(Client, Params, Options) |
name |
Response / container_create_response |
openai_containers:delete(Client, ID, Options); IDs: container_id |
none | null / none |
openai_containers:list(Client, Params, Options) |
none | Page / page |
openai_containers:retrieve(Client, ID, Options); IDs: container_id |
none | Response / container_retrieve_response |
openai_containers_files:create(Client, ID, Params, Options); IDs: container_id |
none | Response / file_create_response |
openai_containers_files:delete(Client, IDs, Options); IDs: container_id, file_id |
none | null / none |
openai_containers_files:list(Client, ID, Params, Options); IDs: container_id |
none | Page / page |
openai_containers_files:retrieve(Client, IDs, Options); IDs: container_id, file_id |
none | Response / file_retrieve_response |
openai_containers_files_content:retrieve(Client, IDs, Options); IDs: container_id, file_id |
none | binary / binary |
openai_content_provenance_checks:create(Client, Params, Options) |
file |
Response / content_provenance_check |
openai_conversations:create(Client, Params, Options) |
none | Response / conversation |
openai_conversations:delete(Client, ID, Options); IDs: conversation_id |
none | Response / conversation_deleted_resource |
openai_conversations:retrieve(Client, ID, Options); IDs: conversation_id |
none | Response / conversation |
openai_conversations:update(Client, ID, Params, Options); IDs: conversation_id |
metadata |
Response / conversation |
openai_conversations_items:create(Client, ID, Params, Options); IDs: conversation_id |
items |
Response / conversation_item_list |
openai_conversations_items:delete(Client, IDs, Options); IDs: conversation_id, item_id |
none | Response / conversation |
openai_conversations_items:list(Client, ID, Params, Options); IDs: conversation_id |
none | Page / page |
openai_conversations_items:retrieve(Client, IDs, Params, Options); IDs: conversation_id, item_id |
none | Response / conversation_item |
openai_decisions:create(Client, Params, Options) |
input, model, questions |
Response / decision |
openai_live:create(Client, Params, Options) |
session, transport |
Response / live_create_response |
openai_live_sessions:accept(Client, ID, Params, Options); IDs: session_id |
session |
null / none |
openai_live_sessions:download_recording(Client, ID, Options); IDs: session_id |
none | binary / binary |
openai_live_sessions:fork(Client, ID, Params, Options); IDs: session_id |
transport |
Response / session_fork_response |
openai_live_sessions:hangup(Client, ID, Options); IDs: session_id |
none | null / none |
openai_live_sessions:refer(Client, ID, Params, Options); IDs: session_id |
target_uri |
null / none |
openai_live_sessions:reject(Client, ID, Params, Options); IDs: session_id |
status_code |
null / none |
openai_realtime_calls:accept(Client, ID, Params, Options); IDs: call_id |
type |
null / none |
openai_realtime_calls:create(Client, Params, Options) |
sdp |
binary / binary |
openai_realtime_calls:hangup(Client, ID, Options); IDs: call_id |
none | null / none |
openai_realtime_calls:refer(Client, ID, Params, Options); IDs: call_id |
target_uri |
null / none |
openai_realtime_calls:reject(Client, ID, Params, Options); IDs: call_id |
none | null / none |
openai_realtime_client_secrets:create(Client, Params, Options) |
none | Response / client_secret_create_response |
openai_realtime_translations_client_secrets:create(Client, Params, Options) |
session |
Response / realtime_translation_client_secret_create_response |
openai_safety_alerts:retrieve(Client, ID, Options); IDs: id |
none | Response / safety_alert |
openai_safety_cases:retrieve(Client, ID, Options); IDs: id |
none | Response / safety_case |
openai_skills:create(Client, Params, Options) |
none | Response / skill |
openai_skills:delete(Client, ID, Options); IDs: skill_id |
none | Response / deleted_skill |
openai_skills:list(Client, Params, Options) |
none | Page / page |
openai_skills:retrieve(Client, ID, Options); IDs: skill_id |
none | Response / skill |
openai_skills:update(Client, ID, Params, Options); IDs: skill_id |
default_version |
Response / skill |
openai_skills_content:retrieve(Client, ID, Options); IDs: skill_id |
none | binary / binary |
openai_skills_versions:create(Client, ID, Params, Options); IDs: skill_id |
none | Response / skill_version |
openai_skills_versions:delete(Client, IDs, Options); IDs: skill_id, version |
none | Response / deleted_skill_version |
openai_skills_versions:list(Client, ID, Params, Options); IDs: skill_id |
none | Page / page |
openai_skills_versions:retrieve(Client, IDs, Options); IDs: skill_id, version |
none | Response / skill_version |
openai_skills_versions_content:retrieve(Client, IDs, Options); IDs: skill_id, version |
none | binary / binary |
{ok, RawResponse} = openai_conversations:retrieve(
Client,
ConversationID,
#{response_mode => {raw, conversation}}
),
{ok, Value} = openai_response:parse(RawResponse),
{ok, Value} = openai_response:parse(RawResponse),
Data = openai_response:to_map(Value),
Metadata = openai_response:metadata(RawResponse),
{ok, Body} = openai_containers_files_content:retrieve(
Client,
#{container_id => ContainerID, file_id => FileID},
#{response_mode => {body, binary}}
),
try
{ok, Bytes} = openai_body:parse(Body),
{ok, Bytes} = openai_body:parse(Body)
after
ok = openai_body:release(Body)
end,
{ok, Items} = openai_conversations_items:list(
Client,
ConversationID,
#{limit => 10}
),
FirstItems = openai_page:items(Items),
Continuation = openai_page:next_page_info(Items).
openai_completions:create/2,3 with stream => true returns the existing
Stream (or raw/Body parsing to the same cursor). Read with openai_stream:next/1
and close in after; release an enclosing Body as well. It has no Chat/Responses
accumulator. Legacy service availability is independent of this local contract.
HTTP SDP signaling is openai_realtime_calls:create(Client, #{sdp => SDP}, Options).
It returns SDP bytes, not a media connection. Session omitted sends SDP directly;
session null/present uses multipart. The encoder owns Content-Type; extra Accept
overrides the endpoint default. No WebRTC engine, SIP call creation, NIF or automatic
session connection is provided. Secret values are sensitive: do not print them.
See platform_resources.erl for a runnable local example and Platform contracts for lifecycle, schema coverage and cleanup responsibilities.
Buffered structured parsing
openai:new/1
Signature: openai:new(openai:options()) -> {ok, openai:client()} | {error, openai:error()}.
Validate options and create an independent Client context under the running application. On success, the returned opaque handle may be used by different processes. No network or credential callback is invoked.
{ok, _} = application:ensure_all_started(openai),
{ok, Client} = openai:new(#{api_key => <<"fake-example-key">>}),
try
ok
after
ok = openai:close(Client)
end.
Errors include option/credential errors, application_not_started,
client_start_failed or timeout on startup failures.
Supervisor startup has no hard overall deadline; see the lifecycle contract.
openai:with_options/2
Signature: openai:with_options(openai:client(), openai:options()) -> {ok, openai:client()} | {error, openai:error()}.
Return a derived handle with immutable overrides. It shares the original
context's lifecycle; it does not mutate the original or other derived handles.
openai:with_options(Client, #{}) inherits effective options, subject to the
documented environment rules: custom headers are re-read, and absent/null
organization/project or an inherited null admin key/webhook secret may read their environment again. This can change the
derived configuration or produce a validation error. API-key/base-URL environment
is not re-read. An explicit API key replaces an inherited binary or callback;
absent/undefined preserves it. See Options and
CONTRACTS.
{ok, Client} = openai:new(#{api_key => <<"fake-example-key">>}),
try
{ok, Derived} = openai:with_options(Client, #{base_url => <<"https://example.com/v1">>}),
ok = openai:close(Derived)
after
ok = openai:close(Client)
end.
Errors include invalid_argument for an invalid handle/value,
unsupported_option, closed for an unavailable context, and normalized
timeout/internal_error failures. No callback is evaluated here.
openai:copy/2
Signature: openai:copy(openai:client(), openai:options()) -> {ok, openai:client()} | {error, openai:error()}.
Alias of with_options/2, including validation, environment
re-read rules and errors. It creates no new context or process. For example,
openai:copy(Client, #{max_retries => 0}) derives a handle sharing close lifecycle.
Python copy and with_options
are also aliases; the supported Erlang options remain those in Options.
openai:is_closed/1
Signature: openai:is_closed(openai:client()) -> boolean() | {error, openai:error()}.
Return false for a running context and true for closing/terminated contexts,
including a coordinator that crashed or belongs to an earlier application run.
The result is a snapshot, not a reservation for another request or confirmation
of cleanup. Invalid handles return invalid_argument; unexpected/query timeout
failures remain normalized errors. Example: true = openai:is_closed(Client)
after close. Python counterpart:
is_closed().
openai:close/1
Signature: openai:close(openai:client()) -> ok | {error, openai:error()}.
Close the shared HTTP context through any original or derived handle.
Repeated close of a completed context safely returns ok. For an active
context, ok confirms resource cleanup and coordinator termination; for an
already dead context it is a no-op without historical cleanup confirmation.
See CONTRACTS for concurrent close,
failure and application shutdown semantics.
Example: ok = openai:close(Client) (also used in every try/after above).
An invalid handle returns invalid_argument. Timeout errors distinguish
phase => acceptance, close_state => unconfirmed from
phase => termination, close_state => closing. Timeout does not confirm
cleanup. Active-close failures may return closed or internal_error.
openai:platform_headers/0
Signature: openai:platform_headers() -> nonempty_list({binary(), binary()}).
Return six ordered binary pairs for language, package version, OS, architecture,
runtime and runtime version. No Client is needed. The package version is unknown
if the application is not loaded. Actual requests include these defaults, with
Client/request header override/removal rules. Example:
Headers = openai:platform_headers().
Python client.platform_headers()
describes Python; ours identifies Erlang/OTP. See the
platform contract for values and differences.
Client request methods
| Function | Signature |
|---|---|
| Generic request | openai:request(openai:client(), openai:request(), openai:request_options()) -> openai:result() |
| GET | openai:get(openai:client(), binary(), openai:verb_options()) -> openai:result() |
| POST | openai:post(openai:client(), binary(), openai:verb_options()) -> openai:result() |
| PUT | openai:put(openai:client(), binary(), openai:verb_options()) -> openai:result() |
| PATCH | openai:patch(openai:client(), binary(), openai:verb_options()) -> openai:result() |
| DELETE | openai:delete(openai:client(), binary(), openai:verb_options()) -> openai:result() |
All return {ok, Value} | {error, openai:error()} through the same Client,
timeout/retry and Response/error pipeline. Python counterparts are
request, get, post, put, patch, delete.
These are low-level Client methods; buffered Responses create is documented below.
openai:request() requires atom method (get, head, post, put, patch,
delete, options) and binary path. Optional fields are query, headers,
json, body and files. json is JSON-native input; binary body is raw bytes, the
counterpart of Python content. All verbs, including GET, reject simultaneous
JSON and raw bodies. GET supports either body. Content-Type defaults to
application/json unless overridden or omitted. Body omission/null rules are in the
serialization contract.
An internal request reference is generated; callers do not supply one.
request_options() requires response_mode. It also accepts security, timeout,
total_timeout_ms, max_retries, and follow_redirects; absent/undefined
timing/retry options inherit Client values. verb_options() additionally accepts
query, headers, json and body; the verb fixes method and takes path as
its second argument. TLS/proxy settings belong to Client options. Arbitrary
casts and unknown options are explicitly rejected. stream => true
is supported with responses / {raw,responses} and the same optional
stream_limits; it selects the SSE cursor described below.
response_mode |
Successful return value |
|---|---|
responses |
Audited ordinary Response wrapper for a JSON object; JSON-native values or decoded binary text on the non-strict branches below |
compaction / input_token_count |
Distinct CompactedResponse / InputTokenCountResponse wrapper for an object; the same non-strict fallback branches |
json |
{ok, openai_request:json_value()}; maps, lists, scalars and null; no wrapper metadata |
text |
{ok, binary()}; decoded UTF-8 text, including replacement characters; use raw mode for original bytes/metadata |
binary |
{ok, openai_response:response()}; original bytes via body/1, including empty/non-UTF-8 data |
none |
{ok, null} for successful status, without interpreting the body; Python NoneType cast |
{raw, Mode} |
{ok, openai_response:response()}; buffered bytes/metadata now, parse/1 later using the stored mode |
These are common generic casts. Resource methods expose their own finite casts
listed in the mapping, and
{body, Cast} uses the Body contract. Raw does not
turn HTTP errors into successes: non-2xx statuses are classified after retries.
For JSON Content-Type, malformed JSON returns invalid_response. With a non-JSON
or missing Content-Type, json returns decoded text; model modes first attempt
JSON, otherwise return decoded text. Non-object JSON remains JSON-native data.
These are the pinned non-strict branches, not a promise of full model coercion.
An empty body is usable as text/binary/raw; JSON decoding still depends on these
rules. All values remain usable after close. See decoding
for supported charsets and raw-marker precedence. Any explicitly unsupported charset and
header-only modern wrapper requests without an explicit Body mode return unsupported_option.
Use Body mode for lazy wrappers.
This mode selection is a limited analogue of Python's required
cast_to, not arbitrary Pydantic coercion or complete model parity.
The exact X-Stainless-Raw-Response: true request marker selects a buffered raw
value even for a parsed mode. Explicit raw modes insert the canonical marker as
Python's raw helper does; other nonempty values without an explicit Body mode
require an unsupported modern-wrapper selection and are rejected. Explicit
{body, Cast} selects the implemented Body lifecycle. An explicit raw mode still
works if the marker is absent.
{ok, Models} = openai:get(Client, <<"/models">>, #{response_mode => json}),
{ok, RawResponse} = openai:request(
Client,
#{method => get, path => <<"/models">>},
#{response_mode => {raw, json}}
),
#{status := 200} = openai_response:metadata(RawResponse),
{ok, Models} = openai_response:parse(RawResponse).
Paths can be relative to the API base URL or absolute HTTPS URLs under the URL/security contract. An absolute URL uses its own path; foreign origins require explicit request Authorization omission. For example, `openai:get(Client, <<"https://api.openai.com/v1/models">>,
{response_mode => json})` matches a Client using that origin. This is a call
example, not a request automatically run by the SDK.
Handle results with case, including authentication_error, rate_limit,
status/transport/timeout errors; inspect safe kind/status rather than logging
the entire Error. See errors, contracts
and the runnable sequential/concurrent example.
Multipart and upload sources
openai:request/3 and the verb helpers accept files => [{Field, Part}].
Use ordered binary pairs for repeated file fields. For an ordinary multipart form,
set Content-Type to multipart/form-data and supply form values through json:
openai:post(Client, <<"/files">>, #{
response_mode => json,
headers => [{<<"Content-Type">>, <<"multipart/form-data">>}],
json => #{<<"purpose">> => <<"user_data">>},
files => [{<<"file">>, {<<"smoke.txt">>, {file, Path}, <<"text/plain">>}}]
}).
This illustrates the generic Client API; dedicated Files methods use the same encoder. Remote objects require endpoint-specific cleanup. In particular, an upload200 does not imply that the service permits downloading that purpose.
openai_upload:source() is a binary, {path, Path}, {file, Path} or
{producer, Spec}. Path is file:filename_all(): path takes an eager byte
snapshot during request preparation; file opens an SDK-owned binary file in
the request's source worker. Raw body accepts the same sources.
Part is a source or {Filename, Source}, {Filename, Source, MIME},
{Filename, Source, MIME, Headers}. Filename and MIME are binary or null;
null/empty filename omits filename. MIME null selects inference using cowlib;
explicit part Content-Type wins over MIME. Part headers are ordered binary pairs.
A producer Spec requires open/0, next/2 and close/1 callbacks; optional
reset/1 enables replay, and optional nonnegative length declares exact bytes.
open() returns {ok, State} or {error, Reason}. next(State, MaxBytes)
returns {ok, NonemptyBinary, NewState}, {eof, NewState} or
{error, Reason, NewState}; the binary must fit MaxBytes. reset(State) returns
{ok, NewState} or {error, Reason, NewState}; close(State) returns ok or
{error, Reason}. Callbacks run in a cancellable request-owned worker, not the
calling process. Callback errors never append their Reason or state to diagnostics.
If open fails before returning State, the callback owns its partial-resource cleanup.
Without reset, retryable HTTP status is returned without another attempt;
body-preserving redirect/auth replay fails with body_not_replayable.
Local source failures use upload_source_failed; unconfirmed close/cleanup uses
cleanup_timeout. A reset failure before retry preserves the previous HTTP error.
The multipart selector can encode a form without files; it cannot be combined
with raw body. Use a suitable raw Content-Type for a raw source.
See ownership, framing, replay and differences
and the local runnable example.
Python counterparts: pinned file conversion
and Client replay/building.
Request security
openai:security() is a map with only optional boolean fields bearer_auth
and admin_api_key_auth. Absent security defaults to both true for generic
Client requests, matching Python FinalRequestOptions. An explicit map replaces
that default; missing flags are false. With both enabled, a nonempty regular key
wins, otherwise admin key is used. Admin-only never evaluates the API-key
callback or falls back to it. Bearer-only never falls back to admin. No URL-path
heuristic selects credentials.
All implemented Responses resource methods select bearer-only internally;
they do not accept a caller security override. Existing header precedence,
override/omission and missing-auth errors still apply. See the
detailed security contract.
{ok, Client} = openai:new(#{
admin_api_key => <<"fake-admin-key">>,
base_url => LocalBaseURL,
tls => #{cacertfile => LocalCAFile}
}),
try
openai:get(Client, <<"/organization/projects">>, #{
security => #{admin_api_key_auth => true},
query => #{<<"limit">> => 1},
response_mode => json
})
after
ok = openai:close(Client)
end.
Use a local fixture/fake key for the runnable example.
Real administration calls require an appropriate admin credential and permissions.
This is a generic JSON request, not an implemented administration resource or Page.
Python counterpart: SecurityOptions and default flags.
Basic resources
These modules use the existing Client authentication, retries, timeouts and error
classification. Resource calls select Bearer authentication; an admin key is not
a fallback. Options supports extra_headers, extra_query, extra_body,
timeout, total_timeout_ms, max_retries, follow_redirects, body_limits
and the method's finite response_mode. Parameter maps accept atom or binary
names; duplicate spellings are rejected. No server model/input defaults or token
limits are injected. Unknown wire fields belong in extras.
Model results are {ok, openai_response:response()}; non-strict responses can
instead return a binary or JSON-native value. All methods can return
{error, openai:error()}. For model mode M, {raw,M} returns an immutable
Response retaining entity bytes/metadata and repeatable parse; {body,M} returns
an HTTP Body, not SSE. Materialized values survive close/release.
See detailed contracts and the runnable
local example.
Embeddings
openai_embeddings:create(Client, Params) and create(Client, Params, Options)
accept required input, model, optional dimensions, encoding_format, user.
Input is a binary, list of binaries, token integers or lists of token integers.
Modes: embedding_response (default), {raw,embedding_response},
{body,embedding_response}.
case
openai_embeddings:create(Client, #{
model => <<"text-embedding-3-small">>,
input => <<"SDK smoke">>,
dimensions => 8
})
of
% Model or admitted non-strict fallback
{ok, Value} -> {ok, Value};
{error, Error} -> {error, maps:get(kind, Error)}
end.
Omitted encoding_format requests base64 and automatically decodes encoded vectors
to float32 numbers. Explicit <<"float">>, <<"base64">> or null bypasses that
post-parser. Raw bytes are retained. Decoded non-finite float32 values use
json_nan, json_positive_infinity, json_negative_infinity: native/json maps
retain them, to_json emits null. They are not valid request values.
Python counterpart: pinned embeddings resource.
Models and moderations
| Call | Default result / parameters |
|---|---|
openai_models:list(Client) / list(Client, Options) |
Single Pagepage, {raw,page}, {body,page} |
openai_models:retrieve(Client, ID) / retrieve(Client, ID, Options) |
Model; model, {raw,model}, {body,model} |
openai_models:delete(Client, ID) / delete(Client, ID, Options) |
ModelDeleted; model_deleted and raw/Body variants. Deletes a fine-tuned model; explicit permission required |
openai_moderations:create(Client, Params) / create(Client, Params, Options) |
ModerationCreateResponse; moderation_response and raw/Body variants. Required input, optional model |
IDs are nonempty unescaped binaries. Moderation input can be a binary, binary list,
or text/image objects such as #{type => <<"text">>, text => <<"hello">>} and
#{type => <<"image_url">>, image_url => #{url => URL}}. URLs/data URIs are passed
as supplied; the SDK does not fetch them. Category slash/hyphen aliases are
preserved by default; use_api_names => false selects field names under the
serialization contract.
{ok, RawResponse} = openai_models:retrieve(
Client,
<<"text-embedding-3-small">>,
#{response_mode => {raw, model}}
),
{ok, Model} = openai_response:parse(RawResponse),
{ok, Model} = openai_response:parse(RawResponse),
ModelData = openai_response:to_map(Model, #{mode => native}).
Counterparts: pinned Models, Moderations.
Files
| Call | Params / default result |
|---|---|
openai_files:create(Client, Params) / create(Client, Params, Options) |
Required file/purpose; optional expires_after with anchor/seconds. FileObject, file_object and raw/Body variants |
openai_files:retrieve(Client, ID) / retrieve(Client, ID, Options) |
FileObject, file_object and raw/Body variants |
openai_files:delete(Client, ID) / delete(Client, ID, Options) |
FileDeleted, file_deleted and raw/Body variants |
openai_files:list(Client, Params) / list(Client, Params, Options) |
after/limit/order/purpose; CursorPagepage and raw/Body variants |
openai_files:content(Client, ID) / content(Client, ID, Options) |
Decoded binary bytes; binary, {raw,binary}, {body,binary} |
openai_files:retrieve_content(Client, ID) / retrieve_content(Client, ID, Options) |
Deprecated text counterpart; UTF-8 binary, text and raw/Body variants |
file uses the source/part descriptors, for example
#{file => {<<"smoke.jsonl">>, {file, Path}, <<"application/jsonl">>}, purpose => <<"batch">>}.
Create does not submit a batch, start training or use the file in another resource.
Only delete objects you explicitly own; use try/after cleanup in applications.
content returns bytes after Content-Encoding decode. Raw body/1 retains
the original entity bytes; raw parse/1 returns decoded binary and metadata
remains separate. This maps the reference's legacy binary wrapper to binary plus
existing raw/Body helpers, rather than exposing a foreign object. retrieve_content
returns decoded text and retains its different Accept default. Service permission
to upload a purpose does not guarantee permission to download it.
{ok, Body} = openai_files:content(Client, FileID, #{response_mode => {body, binary}}),
try
openai_body:stream_to_file(Body, DownloadPath, #{})
after
ok = openai_body:release(Body)
end.
See Files processing helper for polling options, terminal statuses and timeout ordering.
Responses
Buffered model methods use openai_responses:result():
{ok, openai_response:response() | openai_request:json_value()} | {error, openai:error()}.
Usually the value is a model wrapper, but pinned non-strict parsing may return
binary text or another native value. Use model helpers only on model results;
raw mode preserves metadata/bytes when the parsed result has no wrapper.
openai_responses:create/2,3
create(Client, Params) -> openai_responses:result().
create(Client, Params, Options) has the same return type; /2 uses #{}.
Client is openai:client(), Params is openai_responses:create_params(),
and Options is openai_responses:create_options().
Creates a buffered Response with POST /responses. All named parameters from
the pinned Python create signature are accepted as JSON-native values with known
atom keys. Neither model nor input is required locally; no server defaults are
inserted. Missing/undefined/omit omit a named parameter, while explicit null
remains JSON null. Nested API dictionaries use binary keys. See the exported type
for the full parameter list and schema boundaries
for supported conversions and opaque unions.
Params = #{
model => <<"gpt-6-luna">>,
input => <<"Reply with exactly OK.">>,
max_output_tokens => 32,
reasoning => #{<<"effort">> => <<"none">>},
store => false,
stream => false
},
case openai_responses:create(Client, Params) of
{ok, Text} when is_binary(Text) -> {non_json_success, Text};
{ok, Response} -> openai_response:output_text(Response);
{error, Error} -> {error, maps:get(kind, Error)}
end.
Options accept extra_headers (ordered binary pairs), extra_query (the existing
map/ordered-pair query type), and extra_body (binary-key map). Extra body fields
shallowly override named fields; headers/query have request precedence over Client
defaults. Whole-extra null/undefined means no extra override. Existing timeout,
max_retries, total_timeout_ms and follow_redirects request overrides apply.
body_limits supplies optional raw/decoded/line byte limits for the applicable
Body path. The legacy buffered normal/raw openai_responses:create/2,3 path retains its
internal 1 MiB accumulated-body limit and does not enforce explicit body_limits
in the same way as Body. Explicit Body mode has no default aggregate byte cap;
stream_limits separately supplies optional SSE limits. This buffered limitation
remains under CAP-0042; see transport limits.
Do not generalize it to media or structured parsing, which can materialize
normal/raw results through Body internally.
Timeout units are milliseconds; the latter two and per-request retries reuse the
documented Erlang extensions rather than adding generated Python kwargs.
response_mode defaults to responses; {raw, responses} and
{body, responses} are also supported. Body success returns
{ok, openai_body:body()} and follows the Body lifecycle.
Raw success returns the same opaque Response type with original buffered bytes
and metadata, deferring model parsing:
{ok, RawResponse} = openai_responses:create(
Client,
Params,
#{response_mode => {raw, responses}, max_retries => 0}
),
Metadata = openai_response:metadata(RawResponse),
Bytes = openai_response:body(RawResponse),
{ok, Parsed} = openai_response:parse(RawResponse).
Parsing is repeatable and does not send another request. Values remain usable after
Client close. Non-2xx statuses are classified after retries, subject to the
selected path's limits described above; the limits are not uniform across modes.
The body and raw_body keys in the error map remain separate. A successful HTTP response whose
Response status is failed or incomplete remains {ok, Response}. Handle errors
with case as in the runnable local example.
The named stream => true returns a pull cursor instead
of a buffered Response. {raw,responses} preserves opening metadata and
parse/1 returns that same cursor, without a request or rewind. See
Responses SSE streams. Lazy HTTP bodies
use an explicit Body mode. Tool execution and non-JSON Python objects remain unsupported. As in Python,
extra_body changes wire JSON, not the independently selected return mode;
extra_query on retrieve likewise does not change the named stream selection.
Python counterparts: Responses.create / with_raw_response,
request types.
Responses SSE streams
Direct create/retrieve with stream => true return a pull-based Stream
(or raw/Body wrapper according to Options). openai_stream:next/1 returns
{ok, Event}, eos or {error, Error}; metadata/1 reads opening metadata,
close/1 confirms bounded cleanup. Reads belong to the creating process; close
may be called by another holder. Read metadata before closing. No replay or
reconnect occurs. A raw parse returns the same cursor even after it is closed.
Semantic media streams use their finite event cast, not a Responses accumulator.
See stream contracts and the
high-level Responses helper.
Raw streaming
Repeated parse returns the same cursor, including after reads; it does not rewind.
{ok, RawResponse} = openai_responses:create(
Client,
#{model => <<"gpt-6-luna">>, input => <<"Hi.">>, stream => true, store => false},
#{response_mode => {raw, responses}}
),
{ok, Stream} = openai_response:parse(RawResponse),
try
{ok, Stream} = openai_response:parse(RawResponse),
Event = openai_stream:next(Stream),
{ok, Stream} = openai_response:parse(RawResponse),
{openai_response:metadata(RawResponse), Event}
after
ok = openai_stream:close(Stream)
end.
Typed text format
Streaming retrieve
Direct openai_responses:retrieve(Client, ID, #{stream => true,
starting_after => SequenceNumber}, Options) sends the cursor to the server. The
high-level retrieve helper instead accumulates
lifecycle events before filtering locally. These are different operations.
openai_responses:retrieve/2,3,4
retrieve(Client, ID), retrieve(Client, ID, Params) and
retrieve(Client, ID, Params, Options) return
openai_responses:result().
Client is openai:client() and ID is a nonempty UTF-8 binary used as one raw
path segment; do not pre-encode it. No resp_ prefix validation is imposed.
Params is openai_responses:retrieve_params() with optional include (binary
list), include_obfuscation (boolean), starting_after (integer) and stream
(boolean/null/absent). There are no inserted query defaults. undefined/omit
omit a named parameter; query null removes an inherited value at encoding.
Options use openai_responses:create_options(): responses default or
{raw,responses} or {body,responses}, optional body_limits/stream_limits,
extra headers/query/body and existing timing/retry overrides.
Extra query overrides named query before Client merge; arrays use brackets,
ordered pairs retain explicit repetitions. GET sends no JSON body/Content-Type,
including when valid JSON extra_body is supplied. stream=true supports SSE;
lazy HTTP bodies use {body,responses}. Retrieval requires a stored, accessible response; store=false
create IDs must not be assumed retrievable.
{ok, Response} = openai_responses:retrieve(Client, StoredID),
{ok, RawResponse} = openai_responses:retrieve(
Client,
StoredID,
#{},
#{response_mode => {raw, responses}}
),
{ok, Parsed} = openai_response:parse(RawResponse).
openai_responses:delete/2,3
delete(Client, ID) -> {ok, null} | {error, openai:error()}.
delete(Client, ID, Options) -> {ok, null | openai_response:response() | openai_body:body()}
| {error, openai:error()}. Options are openai_responses:delete_options():
the same extras/timing/retry fields and body_limits, with none default,
{raw,none} or {body,none}. Body parse returns {ok, null}; release it after
use. Body/raw wrappers expose metadata independently of that null value.
Python cast_to=NoneType determines the success value, irrespective of empty,
JSON or non-JSON server acknowledgement. It does not decode a deleted field.
Raw mode retains the exact body bytes and metadata; repeated parse returns
{ok,null} without HTTP. Non-2xx statuses are classified before either cast.
Loaded values survive Client close. Generated Accept: */* and the DELETE
backend fallback follow the detailed contracts.
{ok, RawDeleteResponse} = openai_responses:delete(
Client,
StoredID,
#{response_mode => {raw, none}}
),
Bytes = openai_response:body(RawDeleteResponse),
Metadata = openai_response:metadata(RawDeleteResponse),
{ok, null} = openai_response:parse(RawDeleteResponse).
Server deletion is distinct from openai:close/1, which closes local HTTP
resources. The local lifecycle example attempts
deletion in after, then closes Client; a failed delete is not successful cleanup.
Python counterparts: retrieve/delete and raw wrappers,
query types.
openai_responses:cancel/2,3
cancel(Client, ID) and cancel(Client, ID, Options) return
openai_responses:result(). ID is a nonempty raw
UTF-8 binary escaped once. Options are openai_responses:create_options():
responses (default), {raw,responses} or {body,responses}, plus optional
body_limits/stream_limits and existing extras/timing/retries. Body success
is {ok, Body}; parse/release it using the shared Body lifecycle.
There are no named body parameters; extra_body can supply JSON properties.
This is server-side cancellation of a background Response, not cancellation of the local HTTP request. Completion can win the race; inspect the returned status rather than treating HTTP 200 as proof of cancellation. Deletion remains a separate server operation.
{ok, Result} = openai_responses:cancel(Client, ResponseID),
State = maps:get(<<"status">>, openai_response:to_map(Result)).
Python counterpart: responses.cancel.
openai_responses:compact/2,3
compact(Client, Params) and compact(Client, Params, Options) return
openai_responses:result() for CompactedResponse.
Params is openai_responses:compact_params(): required model (binary or null);
optional image, input, instructions, previous_response_id,
prompt_cache_key, prompt_cache_options, prompt_cache_retention, service_tier.
No local requirement for input and no invented server defaults.
Options are openai_responses:compact_options() with compaction default or
{raw,compaction} or {body,compaction}, optional body_limits/stream_limits,
and the existing extras/timing/retry fields. Body success is {ok, Body} and
must be released. The model has
id/created_at/object/output/usage and optional image; it is not ordinary
Response. Preserve opaque encrypted output; output_text is unsupported.
Standalone compaction does not create an ordinary stored Response to delete.
{ok, RawResponse} = openai_responses:compact(
Client,
#{model => <<"gpt-6-luna">>, input => <<"Hi.">>},
#{response_mode => {raw, compaction}}
),
{ok, Compacted} = openai_response:parse(RawResponse),
Window = maps:get(<<"output">>, openai_response:to_map(Compacted)).
Python counterpart: responses.compact.
See the schema and serialization boundaries.
openai_responses_input_tokens:count/2,3
count(Client, Params) and count(Client, Params, Options) return
openai_responses:result() for InputTokenCountResponse.
Params is openai_responses_input_tokens:count_params(); all twelve fields are
optional: conversation, input, instructions, model, parallel_tool_calls,
personality, previous_response_id, reasoning, text, tool_choice, tools,
truncation. #{} matches the pinned SDK no-argument call; the server can reject it.
Options are openai_responses_input_tokens:count_options(): input_token_count
default, {raw,input_token_count} or {body,input_token_count}, plus optional
body_limits/stream_limits and existing extras/timing/retry fields. Body success
is {ok, Body}; repeated parse returns the count model until release.
The model has input_tokens and object; it does not generate an answer or
return a stored Response ID. output_text is unsupported.
{ok, Count} = openai_responses_input_tokens:count(
Client,
#{model => <<"gpt-6-luna">>, input => <<"Hi.">>}
),
Tokens = maps:get(<<"input_tokens">>, openai_response:to_map(Count)).
Python counterpart: responses.input_tokens.count.
Both new models share buffered body/metadata/request_id, repeated raw parse and
post-Client-close value lifetime. See contracts
and the local example.
Chat Completions
Counterparts: pinned Python chat.completions
and its stream helpers.
These methods reuse Client headers/query/security, retries, timeouts and HTTP errors.
See the detailed Chat contract
and local runnable examples.
Buffered Chat methods
| Signature | Parameters | Default successful result |
|---|---|---|
openai_chat_completions:create(Client, Params[, Options]) |
Map with model and messages; optional named Chat parameters |
{ok, Response}; non-strict fallback can return {ok, Binary} |
openai_chat_completions:retrieve(Client, ID[, Options]) |
Nonempty binary, unescaped stored ID | Same buffered result |
openai_chat_completions:update(Client, ID, #{metadata => MapOrNull}[, Options]) |
Required metadata replacement, including null |
Same buffered result |
openai_chat_completions:delete(Client, ID[, Options]) |
Nonempty binary, unescaped stored ID | {ok, Response} with ChatCompletionDeleted fields; binary fallback remains possible |
Client is openai:client(). Params accepts atom or binary spellings of named
keys, with duplicates rejected. All 37 named create body parameters are accepted;
see the pinned counterpart for server-side meanings. undefined/omit omit
typed request fields; null is explicit JSON null. Nested application JSON is
not validated against a model. No model, token cap, storage or reasoning defaults
are invented by these methods.
Options defaults to #{}: extra_headers, extra_query, extra_body,
timeout, total_timeout_ms, max_retries, follow_redirects, body_limits,
stream_limits and response_mode.
Body extras override named wire fields; see CONTRACTS for position-specific
omission. Default mode is chat_completion, or chat_completion_deleted for
delete. {raw, Mode} returns an immutable raw Response with original bytes,
metadata and repeatable openai_response:parse/1; HTTP errors are classified
before parsing. {body, Mode} returns {ok, openai_body:body()} for the method's
chat_completion or chat_completion_deleted cast. Parse can return the model
or the non-strict binary/JSON fallback; release the Body after use. Create with
stream => true yields a Stream (raw/Body parse returns the same cursor).
Arbitrary casts remain unsupported. These direct resource modes do not widen
the narrower parse/stream helper contracts.
Params = #{
model => <<"gpt-6-luna">>,
messages => [#{<<"role">> => <<"user">>, <<"content">> => <<"Reply OK.">>}],
store => false,
reasoning_effort => <<"none">>,
max_completion_tokens => 64
},
case openai_chat_completions:create(Client, Params) of
{ok, Bytes} when is_binary(Bytes) -> {text_fallback, Bytes};
{ok, Completion} -> openai_response:to_map(Completion);
{error, Error} -> {error, maps:get(kind, Error)}
end.
Raw Chat streaming
create/2,3 with stream => true returns {ok, openai_stream:stream()};
response_mode => {raw, chat_completion} instead returns a raw wrapper. It
parses to the same forward-only cursor each time, including after consumption.
Chunks are JSON maps, with an optional usage-only chunk and [DONE] terminator.
Optional stream_limits is the same explicit setting used by Responses streams.
{ok, RawResponse} = openai_chat_completions:create(
Client,
Params#{stream => true},
#{response_mode => {raw, chat_completion}}
),
{ok, Cursor} = openai_response:parse(RawResponse),
try
{ok, Cursor} = openai_response:parse(RawResponse),
openai_stream:consume(Cursor, fun(Chunk) ->
io:format("Choices: ~p~n", [maps:get(<<"choices">>, Chunk)])
end)
after
ok = openai_stream:close(Cursor)
end.
Chat streaming helpers
See Chat accumulation and typed streaming.
Pagination and list resources
The Python chat.completions.list, chat.completions.messages.list and
responses.input_items.list counterparts return immutable Pages here:
| Erlang signature | Named Params, all optional |
|---|---|
openai_chat_completions:list(Client, Params[, Options]) -> openai_page:result() |
'after', limit, metadata, model, order |
openai_chat_completions_messages:list(Client, ID, Params[, Options]) -> openai_page:result() |
'after', limit, order |
openai_responses_input_items:list(Client, ID, Params[, Options]) -> openai_page:result() |
'after', include, limit, order |
IDs are nonempty, unescaped binaries. Params are maps with atom or binary keys;
two spellings of the same name are invalid. Values use the common JSON/query
mapping, including omission/null; no server defaults are inserted. Options have
type openai_page:resource_options(): extra_headers, extra_query,
extra_body, body_limits, timeout, total_timeout_ms, max_retries, follow_redirects,
and response_mode => page | {raw,page} | {body,page} (default page). Extras override named
query parameters. Resource requests use Bearer security through the Client.
The result is {ok, Page | RawResponse | Body} or {error, Error}; status errors are classified
before Page parsing. Legacy raw-response headers can also select Raw.
{ok, RawResponse} = openai_chat_completions:list(
Client,
#{limit => 1},
#{response_mode => {raw, page}}
),
{ok, Page} = openai_response:parse(RawResponse),
% same value, no HTTP
{ok, Page} = openai_response:parse(RawResponse),
Items = openai_page:items(Page).
Use has_next_page/1 before ordinary traversal and get_next_page/1 to fetch
explicitly. Page folds compose lazy
traversal and early stopping; repeated traversals may repeat HTTP requests.
| Page function | Result |
|---|---|
items(Page) |
List of model Response values or JSON-native items; safe error for non-iterable data |
metadata(Page) |
This page's HTTP metadata |
has_next_page(Page) |
boolean() | {error, Error} |
next_page_info(Page) |
null | {params, Query} | {url, Binary} | {json, Map} | {error, Error} |
get_next_page(Page) |
{ok, Page | RawResponse | Body} | {error, Error}; parse/release wrappers according to their mode |
to_map(Page[, Options]), to_json(Page[, Options]) |
API data map/JSON binary or safe error; common model serialization options |
Loaded items, serialization, metadata and raw parse survive Client close.
Following a page requires its originating HTTP context to remain open.
No continuation returns no_next_page without HTTP. Client-default raw markers
also apply to later requests; see the pagination contract.
openai:get_api_list(Client, Path, Options) -> openai_page:result() maps Python
get_api_list with required page_kind => single | cursor | conversation_cursor |
next_cursor | token and item_mode => openai_page:item_mode(), including
json, chat_completion, chat_completion_store_message and response_item.
The exported finite type also lists the implemented Files/media/platform/admin
item casts. The openai_page:options() type
also accepts method (default get), query, headers, json, body,
security and request timeout/retry/redirect options. It reuses Client URL and
credential policies; it does not instantiate arbitrary Python classes.
Pinned sources: pagination.py, messages, input_items. See the runnable local example.
Lazy HTTP bodies
Body lifetime, fold and file helpers
compose these primitives; read, parse and iterator pulls remain core APIs.
All implemented Chat Completions and Responses resource methods accept
response_mode => {body, Mode} in their existing Options argument. For list
methods Mode is page; other modes are the method's ordinary model or none.
Client request/verb methods also accept {body,json|text|binary|none} and the
existing model casts. In the canonical helper-marker lane, a successful call returns {ok, openai_body:body()} after
headers, before reading the body. HTTP errors are read and classified first.
This maps Python .with_streaming_response, not semantic SSE by itself.
See the pinned wrapper
and detailed contract.
{ok, Body} = openai_chat_completions:retrieve(
Client,
ID,
#{response_mode => {body, chat_completion}}
),
try
{ok, Bytes} = openai_body:read(Body),
{ok, Completion} = openai_body:parse(Body),
ok = openai_body:close(Body),
{ok, Completion} = openai_body:parse(Body)
after
ok = openai_body:release(Body)
end.
| Function | Result / purpose |
|---|---|
read(Body), content(Body) |
{ok,binary()} decoded bytes; read materializes/cache, content is cache-only |
text(Body) |
{ok,binary()} decoded UTF-8 text |
json(Body) |
{ok,JSONValue}; JSON byte encoding is independent of Content-Type charset |
parse(Body), parse(Body,Mode) |
{ok,Response|Page|JSONValue|binary()|null|Stream} according to the finite resource cast; non-strict model fallback retained |
metadata(Body), is_closed(Body) |
metadata map / boolean |
iter_bytes(Body[, Options]), iter_raw(Body[, Options]) |
{ok,Reader} decoded/original entity bytes |
iter_text(Body[, Options]), iter_lines(Body) |
{ok,Reader} UTF-8 text/lines without delimiters |
next(Reader) |
{ok,Chunk,NextReader} / eos; use NextReader for continuation |
close(Body) |
ok; confirms network cleanup, retains full cache/parser buffers |
release(Body) |
ok; finally closes I/O/cursors, frees cache, confirms owner DOWN |
All operations can return {error,openai:error()}. Iterator Options support
chunk_size => positive_integer() | null | undefined; bytes count bytes, text
counts Unicode characters. Partial iteration does not create full cache: later
read/parse returns stream_consumed. Always continue with NextReader: reusing
an older streaming Reader returns stream_consumed. Full read permits repeated cached access
after Body/Client close, until release. stream=>true resource parse returns
the same raw SSE Stream cursor on every parse, including after openai_stream:close/1;
it never rewinds or issues another HTTP request.
As in HTTPX, iter_raw does not replay a completed read cache: its next pull
returns stream_consumed. Use bytes/text/lines for cached iteration. Page Body
parse supports its original Page cast; alternate finite casts return
unsupported_option, rather than bypassing the Page post-parser. Use json(Body)
for JSON-native Page data.
Read/parse/iterator pulls belong to the creating process; close/release can be
called by another process. Metadata and materialized immutable values are shareable.
Mixed-case ordered headers preserve the pinned raw-marker escape lanes: an
effective exact true returns the existing raw wrapper, an empty marker the
ordinary result; other nonempty markers give a fully read Body for non-SSE.
The ordinary helper sets canonical X-Stainless-Raw-Response: stream.
Request-only body_limits => #{raw_bytes=>ByteLimit, decoded_bytes=>ByteLimit,line_bytes=>ByteLimit} is
optional; each field defaults to unbounded (null/undefined), zero permits
zero bytes. No new timeout defaults. Full read/text/json/parse intentionally
materialize data; iterators pull gradually. See runnable local example.
Realtime raw WSS
openai_realtime:connect/2
openai_realtime:connect(Client, Options) -> {ok, Connection} | {error, openai:error()}.
Connection is an opaque openai_realtime_connection:connection(); the call
returns after verified TLS and WebSocket upgrade. Python counterpart:
client.realtime.connect(...).enter() / async context entry.
There is no separate async Client or lazy manager API.
Options (openai_realtime:connect_options()) supports optional binary model
and call_id (omit/undefined means absent), extra_query and extra_headers
(the existing query/map and ordered header-pair types, empty by default).
extra_query can override model; explicit call_id overrides the query call_id.
Neither is locally required. websocket_connection_options must be empty and
on_reconnecting null; other native/reconnect settings return unsupported_option.
total_timeout_ms is an opening-only Erlang extension: nonnegative milliseconds
or null, absent/undefined inherits the Client total. It covers config/startup
elapsed time, callback and network opening; it is not a session lifetime limit.
Supervisor queue waiting still has no hard caller deadline.
{ok, Connection} = openai_realtime:connect(
Client,
#{model => <<"your-compatible-model">>, total_timeout_ms => 15000}
).
This subset is direct WSS only. Configured proxy or client-certificate TLS
settings fail explicitly before callback/network; CA/hostname verification remains
mandatory. A live HTTP Client is needed for opening; an opened Connection survives
openai:close/1. Opening owner death cancels a pending connect; no separate connect
cancel API is provided. An API-key callback runs once before networking, including
Authorization override/removal. Admin key is never an automatic fallback; as in
Python Realtime, an admin-only Client or empty callback may send no Authorization
and receive a server authentication error. Header overrides still apply.
Errors include safe invalid_argument, unsupported_option,
credential_provider_failed, connection_error, timeout and closed.
Rejected HTTP upgrades use the existing status Error classification with original
body/metadata. No handshake redirect following or automatic retry occurs.
Detailed URL, credential, timing and queue differences are in
CONTRACTS.
openai_realtime_connection
| Function | Result and parameters |
|---|---|
send_raw(Connection, {text, UTF8Binary} \| {binary, Bytes}) |
ok \| {error, Error}. Explicit Python str/bytes mapping; no JSON serialization. ok confirms transport send completion, not server receipt. |
recv_bytes(Connection) |
{ok, binary()} \| {error, Error}. Original bytes of one complete application message; no read timeout. Only the opening owner may receive. |
recv_bytes(Connection, TimeoutMsOrNull) |
Same result. Erlang extension: nonnegative milliseconds/null; zero polls already-buffered data. Timeout preserves undelivered data. |
close(Connection) |
ok \| {error, Error}. Defaults code 1000 and empty reason; any holder may close. |
close(Connection, #{code => Code, reason => UTF8Binary}) |
Same result; valid RFC client code, reason at most 123 bytes. Active success confirms resource/driver DOWN. Repeat close is safe. |
All functions above belong to openai_realtime_connection.
try
%% Event bytes are supplied by the application; this example does not
%% imply that this event is valid for every OpenAI session/model.
ok = openai_realtime_connection:send_raw(Connection, {text, EventBytes}),
openai_realtime_connection:recv_bytes(Connection, 5000)
after
ok = openai_realtime_connection:close(Connection)
end.
Raw server JSON error events are bytes, not automatic SDK errors or a reason to
close. Peer normal close returns closed after queued messages; abnormal closure
returns connection_error, with available ws_close code/reason. Non-owner reads
return not_owner. Queue exhaustion/oversized messages are explicit errors;
see the fixed buffer budgets.
Typed send/recv/parse_event, handlers, reconnect and other WS namespaces are
not implemented. Fragmentation coverage is incomplete. Python counterparts:
RealtimeConnection,
send_raw/close.
Use the runnable local echo example with the
commands to exercise this subset
without contacting OpenAI.
Webhooks
openai_webhooks:verify_signature/3,4
Signatures:
verify_signature(Client, Payload, Headers) -> ok | {error, openai:error()}.verify_signature(Client, Payload, Headers, Options) -> ok | {error, openai:error()}.
Client is an openai:client(), Payload the original UTF-8 binary HTTP body,
and Headers an ordered list of {binary(), binary()} pairs. Pass the bytes
received, without decoding/re-encoding JSON. Verification is local: it makes no
request, invokes no Bearer provider, and remains available after HTTP Client close.
Options (openai_webhooks:options()) are secret => binary() | null | undefined
and tolerance => integer(). An absent/null/undefined secret uses the Client's
immutable snapshot; an explicit binary, including empty, overrides it. Tolerance
is seconds, default 300; the boundaries are inclusive. Negative tolerance
rejects every timestamp. Unknown options and invalid inputs, missing secret/header,
invalid UTF-8 or malformed secret encoding return invalid_argument.
Invalid/stale/future timestamps and signature mismatches return
invalid_webhook_signature. Errors do not include inputs.
%% OriginalBody and IncomingHeaders come from your HTTP receiver.
openai_webhooks:verify_signature(Client, OriginalBody, IncomingHeaders),
openai_webhooks:verify_signature(
Client,
OriginalBody,
IncomingHeaders,
#{secret => <<"whsec_c3ludGhldGlj">>, tolerance => 300}
).
See the runnable synthetic example and
detailed contract.
Python counterparts: synchronous client.webhooks.verify_signature(...) on both
OpenAI and AsyncOpenAI.
unwrap and webhook event models are not implemented.
Response values
openai_response:parsed(Response) returns {ok, #{values := [{Path, Value}]}}
or a safe error for supported parsed values. It only reads already-derived
values; resource parsing helpers
perform schema/validator workflows.
openai_response:construct(Data, Mode) returns {ok, Response} or a safe
error for the finite supported model modes, without HTTP. It adds no server
metadata: for example construct(EventMap, stream_event) wraps an already
decoded event; it does not open or accumulate a stream.
openai_response:response() is an opaque immutable value, without a process.
Public Client requests and buffered Responses create/retrieve produce these values.
The examples below describe operations on a
Response obtained through that pipeline. Values remain usable after Client close.
| Function | Return type | Example value |
|---|---|---|
openai_response:to_map(Response) |
map() \| {error, openai:error()} |
#{<<"id">> => <<"resp_example">>} |
openai_response:to_map(Response, Options) |
map() \| {error, openai:error()} |
With #{exclude_null => true}, omit null model fields |
openai_response:to_json(Response) |
binary() \| {error, openai:error()} |
UTF-8 JSON, indent 2 |
openai_response:to_json(Response, Options) |
binary() \| {error, openai:error()} |
#{indent => compact} selects compact JSON |
openai_response:metadata(Response) |
openai_response:metadata() \| {error, openai:error()} |
#{status => 200, headers => [], request_id => undefined} |
openai_response:request_id(Response) |
binary() \| undefined \| {error, openai:error()} |
<<"req_example">> or undefined |
openai_response:body(Response) |
binary() \| {error, openai:error()} |
Original buffered bytes, including for a model value |
openai_response:parse(RawResponse) |
{ok, Parsed} \| {error, openai:error()} |
A model/binary wrapper, JSON-native value or decoded UTF-8 binary text, according to the stored mode and non-strict rules |
openai_response:output_text(Response) |
binary() \| {error, openai:error()} |
<<"hello">> or <<>> when no output text exists |
The model-based helpers accept the audited ordinary Responses subset.
openai_response:options() has boolean use_api_names, exclude_unset,
exclude_defaults and exclude_null; defaults are respectively true, true,
false, false. openai_response:json_options() additionally accepts
indent => non_neg_integer() | compact. exclude_null omits applicable null model
fields; the former exclude_none name returns unsupported_option, without an alias.
For example: openai_response:to_map(Model, #{exclude_null => true}).
An option is not silently ignored when
the selected nested model lacks its required descriptor: return unsupported_option.
to_map/to_json reject native fallback values and binary/raw wrappers rather
than inventing model objects.
Chat, Page and basic-resource descriptors also accept mode => native (default)
or mode => json in to_map. The old name python is unsupported, without an
alias. to_json selects JSON serialization directly and does not accept mode.
The ordinary Responses subset retains its existing serialization-option limits.
Default/API-name serialization retains unknown input extras, including literal
schema_ or async_ keys. Existing field/default and exclusion rules still apply.
The optional use_api_names => false projection can be lossy: an extra schema_
or async_ can collide with a renamed field. Use API names to retain those
distinct keys; raw bytes remain available separately.
Metadata is never part of API data. output_text concatenates only
the <<"text">> values of output_text content within output messages, in order, skipping null text,
without separators; it does not search arbitrary dictionaries for text.
Python counterparts: BaseModel.to_dict/to_json,
Response.output_text.
See value contracts for the
descriptor boundary, JSON-native differences and raw modes. A runnable public
request/Response example is available in responses_create.erl.
Options
Options are maps with only the atom keys below. Unknown or binary keys return
unsupported_option; invalid values or a non-map return invalid_argument.
The SDK owns its Gun transport context. Supplying an existing HTTP client via
http_client is unsupported in both new/1 and with_options/2, including
undefined/null, and returns unsupported_option. This differs from Python
OpenAI(http_client=...).
Shared lifecycle/reuse cover only those behaviors, not client injection or full
HTTPX configuration parity. See transport scope.
| Key | Accepted value | new/1 default |
with_options/2 when absent/undefined |
|---|---|---|---|
provider |
Factory value from openai_providers:vertex/1 or bedrock/1; see supported modes below |
null; account credential/routing environment is not inherited by a provider |
Preserve factory, configure a fresh auth view; explicit null exits provider mode |
workload_identity |
Subject/X.509 identity map or explicit openai_auth:auth(); see below |
null; a configured identity suppresses API-key environment fallback |
Preserve identity; ordinary identity copies have independent caches; an explicit Auth is shared |
api_key |
UTF-8 binary without NUL/CR/LF, callback, null or undefined; empty needs another configured credential |
Absent/null/undefined reads OPENAI_API_KEY once; explicit empty does not |
Null/empty/undefined inherits the ordinary key or callback; subject-auth transition is described below |
admin_api_key |
UTF-8 binary without NUL/CR/LF, including empty, or null/undefined; no callable |
Read OPENAI_ADMIN_KEY for absent/null/undefined |
Inherit; inherited null re-reads environment |
webhook_secret |
UTF-8 binary (including empty), null or undefined; no callable |
Read OPENAI_WEBHOOK_SECRET for absent/null/undefined |
Inherit; an inherited null re-reads environment; explicit empty also inherits |
websocket_base_url |
HTTPS/WSS binary URL (query allowed), empty binary, null or undefined |
Derive from effective HTTP base; no dedicated environment variable | Inherit for absent/undefined/null/empty; a nonempty explicit URL replaces WS routing |
base_url |
Absolute HTTPS URL without userinfo/query/fragment; null/undefined; empty allowed only as a copy inheritance argument |
Absent/null/undefined reads OPENAI_BASE_URL, otherwise default OpenAI URL |
Null/empty/undefined preserves the inherited URL |
data_residency |
<<"global">>, <<"us">>, <<"eu">>, <<"ae">>, <<"au">>, <<"in">>, <<"jp">>, null or undefined |
Absent/null/undefined: no region selection |
Preserve URL when absent/null/undefined; a region replaces it |
organization |
UTF-8 binary without NUL/CR/LF (including empty), null or omit |
Read OPENAI_ORG_ID for absent/undefined/null; otherwise use the explicit value |
Inherit; an inherited null reads environment again |
project |
Same values as organization |
Read OPENAI_PROJECT_ID for absent/undefined/null; otherwise use the explicit value |
Inherit; an inherited null reads environment again |
default_headers |
Ordered {binary(), binary() \| omit \| undefined} pairs or null; values are ready header bytes |
Merge environment and explicit pairs; null means no explicit pairs | Null inherits; pairs merge and re-read header environment |
set_default_headers |
Same pairs or null, only in with_options/2 |
Rejected with unsupported_option |
Null inherits; empty list clears inherited pairs; environment still applies |
default_query |
Binary-key query map or null |
Empty map; no query environment variable | Null inherits; map merges shallowly |
set_default_query |
Same map or null, only in with_options/2 |
Rejected with unsupported_option |
Null inherits; empty map clears; map replaces inherited query |
follow_redirects |
Boolean | true, matching the Python SDK wrapper |
Preserve inherited value |
max_redirects |
Nonnegative integer | 20 |
Preserve inherited value |
max_retries |
Nonnegative integer; booleans and null are invalid |
2 (up to three attempts) |
Preserve inherited value; 0 disables retries |
tls |
Typed TLS map; see below | System trust, subject to certificate environment | Preserve loaded settings; an explicit map replaces TLS settings |
trust_env |
Boolean | true for certificate environment |
Preserve; changing it resolves TLS settings again |
proxy |
null, HTTPS binary URL or typed proxy map |
null (direct) |
Preserve; null selects direct transport |
timeout |
Nonnegative integer milliseconds, null, or a complete phase map |
#{connect => 5000, read => 600000, write => 600000, pool => 600000} |
Preserve inherited value |
total_timeout_ms |
Nonnegative integer milliseconds or null |
null (disabled) |
Preserve inherited value |
At new/1, an absent, null or undefined key uses environment fallback. An explicit
valid binary or callback takes precedence; an invalid explicit value fails
without fallback. A Client with only admin credentials is allowed. Missing both
credentials returns missing_credentials; invalid environment values return
invalid_argument. An empty key/environment without an admin credential returns
missing_credentials. with_options/2 never re-reads the API-key environment.
Whole default_headers/default_query null means no explicit constructor defaults;
in copy both those and set_default_* null inherit. Empty list/map in a replacement
clears inherited defaults. Only non-null merge/replacement pairs conflict.
Other null/omit positions retain their individually documented rules.
The URL policy is a current implementation restriction.
websocket_base_url only changes Realtime WS routing; it does not rewrite HTTP
base_url. Construction preserves empty binary, which ultimately uses HTTP routing;
copy follows Python's given-or-inherited rule. A regional data_residency copy
clears inherited WS routing. Explicit non-null WS URL, including empty, conflicts
with a region. For example, openai:copy(Client, #{websocket_base_url =>
<<"wss://your-endpoint.example/custom?route=a&route=b">>}) selects
/custom/realtime on that configured endpoint. See
full URL/query contract and the pinned
constructor/copy source.
Explicit admin key overrides its environment, including an empty binary.
Copy/with_options uses Python's given-or-inherited rule: absent, undefined, null
and empty admin values inherit; if that result is null, environment is read again.
There is no mutable client.admin_api_key property; derive a handle instead.
webhook_secret follows the same constructor/copy given-or-inherited rules,
but is only for local signature verification,
never HTTP authentication. A webhook secret alone is not an API credential.
For example, openai:copy(Client, #{webhook_secret => <<"synthetic-secret">>})
replaces the snapshot without changing the original Client.
An empty callback result is a missing Bearer key: generic requests can use an
enabled admin key; bearer-only returns missing_credentials unless headers
provide/explicitly omit authentication. Exceptions or invalid callback values
remain credential_provider_failed, without environment/admin fallback.
Python counterparts: constructor/copy,
admin header.
timeout maps require exactly connect, read, write and pool; all values
are nonnegative integer milliseconds or null (openai:duration_ms()).
The complete value has type openai:request_timeout(). A scalar supplies all four phase
values; a map replaces the whole value. null disables phase timers, while
undefined inherits. total_timeout_ms is a separate Erlang extension and is
disabled by default; a scalar timeout does not create a total deadline.
Pool waiting is inapplicable because capacity refusal is immediate. Write-timeout
guarantees through HTTPS CONNECT remain unverified. See the detailed
timeout contract and Python
OpenAI / AsyncOpenAI timeout counterpart.
For example, create with openai:new(#{api_key => Key, timeout => 10000}), then
derive with openai:with_options(Client, #{timeout => null, total_timeout_ms => 30000}).
The first sets phase limits without a total cap; the derived handle instead has
only a total cap. Neither call sends a request. Close the shared Client in after.
max_retries controls additional attempts, with no environment variable.
For example, create with openai:new(#{api_key => Key, max_retries => 2}), then
derive with openai:with_options(Client, #{max_retries => 0}) to disable retries
for that handle without changing the original. undefined inherits.
The shared mechanism maps both Python
OpenAI and AsyncOpenAI.max_retries.
See the retry contract for statuses, server hints,
callback refresh, replay and cancellation. Retries can repeat side effects;
the SDK does not automatically send an Idempotency-Key.
organization supplies the OpenAI-Organization header. Python counterpart:
OpenAI(organization=...) and copy(organization=...).
Construction accepts an empty binary as an empty header; copy treats it, null
and omit as inheritance. See the organization contract
for environment, omission and header precedence details.
project independently supplies OpenAI-Project with the same construction/copy
rules, using OPENAI_PROJECT_ID. Python counterpart:
OpenAI(project=...) and copy(project=...).
See the project contract for detailed rules and differences.
{ok, Client} = openai:new(#{
api_key => <<"fake-key">>, organization => <<"org-example">>, project => <<"proj-example">>
}),
try
{ok, Derived} = openai:with_options(Client, #{project => <<"proj-other">>}),
ok = openai:close(Derived)
after
ok = openai:close(Client)
end.
For base_url, new/1 uses an explicit value first, then OPENAI_BASE_URL
when absent/undefined, then the standard URL when the variable is unset.
An invalid explicit URL never falls back; an empty or invalid environment URL
returns invalid_argument. with_options/2 inherits the effective URL without
reading environment again. Request paths add a missing trailing slash to the
base path, preserving existing slashes and percent-encoded segments. Unlike
Python's URL object and mutable setter, Erlang stores a binary and uses
immutable overrides; the stored binary need not end in /.
data_residency selects a named HTTP endpoint before environment fallback;
it cannot be combined with explicit base_url, including null. base_url =>
undefined means absent and does not conflict. A later with_options may replace
the selected URL explicitly. Python counterpart:
OpenAI(data_residency=...) / with_options(data_residency=...).
See the detailed HTTP residency contract.
Endpoint selection does not certify where data is processed or stored.
{ok, Regional} = openai:new(#{api_key => <<"fake-key">>, data_residency => <<"eu">>}),
try
{ok, Global} = openai:with_options(Regional, #{data_residency => <<"global">>}),
ok = openai:close(Global)
after
ok = openai:close(Regional)
end.
default_headers uses ordered binary pairs. Copy merges them; set_default_headers
replaces them. OPENAI_CUSTOM_HEADERS is read at construction and copy; request
headers override defaults within the supported transport rules. For validation,
casing, parsing and omit/undefined rules, see
header serialization.
Authorization overrides use the same merge and produce at most one header.
Explicit request omission can suppress it; Client-only omission may return
missing_credentials. Bearer callbacks still run when headers override or remove
Authorization. See the contract for these distinctions and safe failure behavior.
{ok, Client} = openai:new(#{
api_key => <<"fake-key">>, default_headers => [{<<"X-Example">>, <<"base">>}]
}),
try
{ok, Merged} = openai:with_options(Client, #{
default_headers => [{<<"X-Example">>, <<"derived">>}]
}),
{ok, Replaced} = openai:with_options(Merged, #{set_default_headers => []}),
ok = openai:close(Replaced)
after
ok = openai:close(Client)
end.
default_query supplies binary-key map defaults. with_options shallow-merges
them; set_default_query replaces them (#{} clears them). Request query has
precedence. Python counterparts are pinned
OpenAI(default_query=...) and copy(default_query=... / set_default_query=...).
See the detailed query contract
for encoding, nested values, omission and ordered-pair differences.
{ok, _} = application:ensure_all_started(openai),
{ok, Client} = openai:new(#{
api_key => <<"fake-example-key">>, default_query => #{<<"limit">> => 20}
}),
try
{ok, Merged} = openai:with_options(Client, #{
default_query => #{<<"limit">> => 5, <<"tag">> => [<<"example">>]}
}),
{ok, Replaced} = openai:with_options(Merged, #{set_default_query => #{}}),
ok = openai:close(Replaced)
after
ok = openai:close(Client)
end.
This creates and closes handles only; it sends no requests.
A binary is a ready key value; a callback provides the value later:
BinaryOptions = #{api_key => <<"fake-example-key">>},
CallbackOptions = #{
api_key => fun() ->
<<"fake-example-provider-key">>
end
}.
Pass either map to openai:new/1 or openai:with_options/2.
A callback is stored without evaluation by both Client functions. Evaluation
occurs only for a Bearer-authenticated request, before connection checkout.
It must return a valid binary key. Failure is normalized as
credential_provider_failed without environment fallback or revealing the
exception reason, stack or value. Public request methods evaluate it for each
Bearer attempt. The lifecycle-only callback example still makes no request. Callback lifecycle
and the difference from Python's mutable last-key property are described in
CONTRACTS.
HTTP providers
openai_providers:vertex(Options) and openai_providers:bedrock(Options) return
{ok, openai_providers:provider()} | {error, openai:error()}. Pass the factory
value as openai:new(#{provider => Provider}). Top-level api_key,
admin_api_key, base_url, data_residency and workload_identity cannot
also configure a provider's credentials/routing. Provider options belong inside
the factory. No callback/network operation occurs at construction/copy;
profile-based region resolution may read local configuration.
Implemented request modes:
| Provider | Configuration | Authentication |
|---|---|---|
| Vertex | base_url, or project/location with Google environment fallback |
token_provider => fun(() -> binary()), evaluated once per attempt |
| Bedrock | endpoint => mantle (default) or runtime, region and optional base_url |
api_key binary, token_provider, or selected AWS_BEARER_TOKEN_BEDROCK |
| Bedrock SigV4 | Same endpoint settings | access_key_id + secret_access_key, optional session_token; or credential_provider returning an atom-keyed map with those binary values |
| Bedrock native subset | Explicit profile, or default AWS source selection |
Environment/static/legacy files, ordinary AssumeRole/web identity, cached/session SSO, Login/DPoP and ECS/IMDS, per auth view |
| Vertex Google file subset | credentials => #{file => Path} or #{info => JSONMap}; optional separate tls, trust_env, proxy in that descriptor |
Authorized-user refresh, service-account JWT, external-account file/HTTPS/certificate/AWS subjects, external authorized user, impersonation and GDCH exchanges |
Native executable discovery remains unsupported; supplied callbacks are a
separate mechanism. MFA is not implemented, and a configured mfa_serial is
rejected before STS without a prompt. Advanced native configuration remains
limited; see CONTRACTS.
Google explicit-file or GOOGLE_APPLICATION_CREDENTIALS/Cloud SDK/GCE discovery
is lazy. The configured Google file types have the subset described in
CONTRACTS, not arbitrary
Python Credentials objects or complete native parity.
An explicitly shared Google credential runtime uses the same owned Auth context:
{ok, Auth} = openai_auth:new(#{google_credentials => Descriptor}), then
openai_providers:vertex(#{base_url => URL, credentials => Auth}). Close Auth
explicitly after its borrowing Clients. This is opt-in sharing with a separate
lifetime, not the default for ordinary descriptor/copy handles. Native token
retrieval/invalidation is internal: public get_token/invalidate_token reject
this Auth kind with invalid_argument. It is not a workload_identity value.
Configured unsupported sources return unsupported_option before execution or
network acquisition. Executable programs are never launched. This is not full
provider/native compatibility. Current static profile parsing does not implement
the complete botocore configuration surface. The implementation uses Erlang/OTP
only; no native executable cleanup helper is included.
{ok, Provider} = openai_providers:vertex(#{
project => <<"example-project">>,
location => <<"global">>,
token_provider => fun() -> <<"supplied-bearer-token">> end
}),
{ok, Client} = openai:new(#{provider => Provider}).
Close Client in try/after when using it. See the
local fake-key examples,
detailed auth contract,
and pinned Vertex
and Bedrock.
Subject workload authentication
An identity has binary identity_provider_id and service_account_id, a
provider => #{token_type => jwt | id, get_token => fun(() -> binary())}, and
optional numeric refresh_buffer_seconds (default 1200, seconds).
Use openai:new(#{workload_identity => Identity}) for a context-owned lazy cache.
No subject evaluation or exchange occurs at new/copy. Every ordinary identity
copy has an independent cache; concurrent uses of the same handle share refresh.
X.509 authentication is described below. GCP and Azure helpers return lazy typed
subject-provider descriptors; they do not contact metadata at construction.
For the pinned subject-auth copy transition only, copy(Client, #{api_key => <<>>})
disables workload auth and sends the reference literal Bearer workload-identity-auth.
It does not evaluate the subject or change the original Client.
For explicit sharing and a separate lifetime:
Identity = #{
identity_provider_id => <<"idp_example">>,
service_account_id => <<"sa_example">>,
provider => #{token_type => jwt, get_token => fun() -> <<"subject-token">> end}
},
{ok, Auth} = openai_auth:new(Identity),
{ok, Client} = openai:new(#{workload_identity => Auth}).
Close Client and then Auth in try/after. Client close does not close a
borrowed Auth. Auth close does not close borrowing HTTP clients; later token
acquisition returns closed. This explicit shared object is an Erlang extension.
Active Auth close has a separate two-second cleanup wait; timeout does not
confirm cleanup. It does not change the ordinary Client close budget.
| Function | Result / parameters |
|---|---|
openai_auth:new(Identity) / new(Identity, Options) |
{ok, auth()} | {error, openai:error()}; options: HTTPS token_exchange_url, separate tls, trust_env and HTTPS proxy; default exchange is https://auth.openai.com/oauth/token |
openai_auth:get_token(Auth) / get_token(Auth, #{total_timeout_ms => TimeoutMilliseconds}) |
{ok, binary()} | {error, openai:error()}; TimeoutMilliseconds is nonnegative milliseconds or null; default null; source HTTP phases retain their separate 10-second budget |
openai_auth:invalidate_token(Auth) / invalidate_token(Auth, Expected) |
ok | {error, openai:error()}; binary invalidates only that cached token, null always invalidates; no exchange |
openai_auth:close(Auth) |
ok | {error, openai:error()}; confirmed owned-resource cleanup for an active context, safe dead-context no-op with the same historical-cleanup limit as Client close |
openai_auth:k8s_service_account_token_provider() / ...(Path) |
{ok, subject_provider()} | {error, openai:error()}; UTF-8 binary path, default /var/run/secrets/kubernetes.io/serviceaccount/token; refresh reads and strips the file, not construction or each cached use |
openai_auth:gcp_id_token_provider() / ...(Options) |
Lazy ID-token descriptor; audience binary defaults to https://api.openai.com/v1; timeout milliseconds or null, default 10000 |
openai_auth:azure_managed_identity_token_provider() / ...(Options) |
Lazy JWT descriptor; binary resource defaults to https://management.azure.com/, api_version to 2018-02-01; optional binary/null object_id, client_id, msi_res_id; millisecond/null timeout, default 10000 |
Errors include safe subject_token_provider_failed, credential_provider_failed,
oauth_error, timeout, closed and transport errors. Messages do not contain
subject/access tokens or callback exception details. See
CONTRACTS and pinned
subject helper/cache.
Sync/async callers use this same Erlang mechanism in separate calling processes.
X.509 workload authentication
Identity = #{
type => x509,
identity_provider_id => <<"idp_example">>,
service_account_id => <<"sa_example">>
},
{ok, Client} = openai:new(#{
workload_identity => Identity,
tls => #{certfile => <<"client.pem">>, keyfile => <<"client-key.pem">>}
}).
Use try/after to close Client. The default API endpoint is
https://mtls.api.openai.com/v1; data_residency supports global/us/eu for this
mode. The authentication endpoint is fixed and cannot be replaced through
token_exchange_url. Identity IDs must be nonempty binaries; optional
refresh_buffer_seconds is nonnegative, default 1200. API TLS settings supply
the client certificate, with peer/hostname verification. This authenticates tokens
using X.509 and is distinct from merely enabling transport mTLS.
See protected exchange/lifecycle rules
and pinned X.509 implementation.
TLS, proxy and redirects
The SDK still owns Gun; these options do not inject an HTTP client. Python
counterparts are
DefaultHttpxClient / DefaultAsyncHttpxClient.
{ok, Client} = openai:new(#{api_key => <<"fake-key">>, trust_env => false}),
try
{ok, Derived} = openai:with_options(Client, #{
follow_redirects => false,
max_redirects => 3,
proxy => #{
url => <<"https://localhost:8443">>,
auth => {<<"fake-user">>, <<"fake-password">>}
}
}),
ok = openai:close(Derived)
after
ok = openai:close(Client)
end.
This example creates and closes handles without connecting to a proxy. File
downloads use the public Files methods. Redirect following defaults to true;
disabling it returns the original response. The hop limit is independent of
retries; HTTPS downgrade is rejected.
tls accepts one of cacerts => [DERBinary], cacertfile => PEMPathBinary or
capath => DirectoryBinary; omitting all three selects system trust.
Client certificates use both certfile and keyfile (PEM path binaries), with
optional password => Binary for an encrypted key. Files are loaded at
construction or explicit TLS replacement; malformed/unreadable material returns
invalid_argument without its contents. Peer and hostname verification cannot
be disabled. For example, with existing PEM files:
{ok, Client} = openai:new(#{
api_key => <<"fake-key">>,
trust_env => false,
tls => #{
cacertfile => <<"local-ca.pem">>,
certfile => <<"client-cert.pem">>,
keyfile => <<"client-key.pem">>
}
}),
try
ok
after
ok = openai:close(Client)
end.
Explicit CA settings take precedence over SSL_CERT_FILE, then SSL_CERT_DIR,
then system trust. trust_env => false ignores certificate environment. An
empty copy inherits the loaded configuration; explicit tls or trust_env
resolves it again. System trust is loaded lazily at connection time.
The proxy map accepts url, optional auth => {UserBinary, PasswordBinary},
ordered binary headers pairs and a separate tls map for proxy verification
or its client certificate. Proxy URL userinfo is also supported; explicit auth
wins. Target TLS settings never become proxy TLS settings. HTTP/SOCKS proxies
and proxy-environment/NO_PROXY handling remain unsupported; trust_env currently
affects certificate settings only. This is not full HTTPX configuration parity.
See transport contracts for credential isolation, CA-directory differences, cleanup and compatibility limits.
OpenAI and AsyncOpenAI
Python OpenAI and AsyncOpenAI map to one Erlang Client; there is no separate
AsyncClient. A synchronous call waits for its result in the calling process.
Concurrent requests run in separate Erlang processes sharing a Client as allowed
by its lifecycle contract. A sync/async mapping records matching verified behavior,
not two separate implementations. See the runnable
concurrent Client GET example.
Error values
Errors are extensible maps with kind (atom) and message (UTF-8 binary).
Optional diagnostic fields include operation, phase, close_state and
cause; callers must tolerate extra fields. Match the fields needed, rather
than requiring an exact map. SDK-generated diagnostic messages do not append
configured credentials; avoid printing handles, configuration or arbitrary
callback data. Explicit HTTP data fields retain untrusted server data and may
contain information reflected by the server; do not log the whole error.
The response layer maps HTTP status errors to bad_request (400),
authentication_error (401), permission_denied (403), not_found (404),
conflict (409), unprocessable_entity (422), rate_limit (429),
internal_server_error (5xx) or api_status_error (other non-success statuses).
Transport connection_error and timeout remain distinct. Internal raw HTTP
requests still return every HTTP status as a result; classification is a separate
layer used by the public Client request functions.
Available HTTP error fields are status, request_id, headers, selected API
body, type, code and param. Optional raw_body is an Erlang extension
retaining the original HTTP body bytes independently of the error map’s body key.
The body key in the error map may be the value extracted from the decoded response's error field.
Missing fields are omitted; explicit API null stays null.
code preserves its JSON type: string → binary, number → integer/float,
boolean → boolean, array → list, object → map. For example,
{"x":[true,null]} becomes #{<<"x">> => [true,null]}. This deliberately differs
from the Python SDK's string projection for non-string codes.
message is a safe status summary, not the API message/body or response headers.
Inspect data fields explicitly; do not log whole errors automatically. See
error/value contracts and the
Python error counterpart.
case openai:new(#{api_key => <<>>}) of
{error, #{kind := invalid_argument}} -> ok;
{ok, Client} -> openai:close(Client)
end.
Media resources
All methods return {ok, Value} | {error, openai:error()} and reuse the Client's
credentials, retry, timeout and TLS settings. Client is openai:client(), IDs are
unescaped nonempty binaries, Params is the module's exported params() map, and Options
is its options() type. Named parameters accept atom/binary keys; conflicting
spellings are rejected. Extra body/query/headers use existing resource precedence.
No model, voice, size or other server default is inserted for omitted parameters.
Modules also export finite per-method types such as create_params(),
update_params() and list_params(); params() is their namespace union.
Specs list named fields and source types. Binary keys are equivalent spellings of
those names, not unrestricted extras. Required groups are documented beside the
types; omit/undefined omit a value, while null remains a supplied JSON value.
Normal model results are openai_response:response() (with the existing non-strict
JSON/text fallback). Use openai_response:to_map/1,2 or to_json/1,2; metadata is
separate. response_mode => {raw, Mode} returns an immutable raw Response;
{body, Mode} returns openai_body:body(), which must be released in try/after.
Raw parse preserves bytes/metadata and is repeatable; a raw semantic stream parses
to the same cursor, without rewind or another request. Materialized values survive
Client close and Body release. Binary outputs contain Content-Encoding decoded
bytes; raw stores the original entity bytes separately.
Audio
| Public signature (default-options form) | Required / optional named parameters | Default result / mode |
|---|---|---|
openai_audio_speech:create(Client, Params, Options) (/2) |
input, model, voice; instructions, response_format, speed, stream_format | decoded binary(); binary |
openai_audio_transcriptions:create(Client, Params, Options) (/2) |
file, model; chunking_strategy, include, keywords, known_speaker_names, known_speaker_references, language, languages, prompt, response_format, stream, temperature, timestamp_granularities | Transcription / Verbose / Diarized Response; text or semantic Stream according to format |
openai_audio_voice_consents:create(Client, Params, Options) (/2) |
language, name, recording | VoiceConsent Response; voice_consent |
openai_audio_voice_consents:retrieve(Client, ID, Options) (/2) |
ID | VoiceConsent Response |
openai_audio_voice_consents:update(Client, ID, Params, Options) (/3) |
name | VoiceConsent Response |
openai_audio_voice_consents:delete(Client, ID, Options) (/2) |
ID | VoiceConsentDeleted Response; voice_consent_deleted |
openai_audio_voice_consents:list(Client, Params, Options) (/2) |
optional after, limit | cursor Page; page |
openai_audio_voices:create(Client, Params, Options) (/2) |
name + audio_sample + consent or name + prompt + type; optional model, script_hint | Voice Response; voice |
openai_audio_voices:delete(Client, ID, Options) (/2) |
ID | VoiceDeleted Response; voice_deleted |
Counterparts are the identically named methods under Python client.audio.
Files/recordings use finite upload sources, not
filename strings. Custom sample voices require an enabled account and genuine
consent/sample recordings; examples use controlled local fixtures.
Transcription modes: default/json → transcription, verbose_json →
transcription_verbose, diarized_json → transcription_diarized;
text/srt/vtt → text (UTF-8 binary). Unknown formats follow the base-model non-strict
fallback; model-specific support remains a service decision. stream=true on
transcriptions selects transcription_event.
Speech stream_format=sse still returns binary/raw/Body bytes, not typed events.
Text/srt/vtt transcriptions use the same media materialization and
optional body_limits in normal, raw, header-selected raw and Body modes.
Voice creation checks the alternative required groups before credentials or HTTP;
enum values and other server policy remain the server's responsibility.
{ok, RawResponse} = openai_audio_speech:create(
Client,
#{model => <<"gpt-4o-mini-tts">>, input => <<"Hello.">>, voice => <<"coral">>},
#{response_mode => {raw, binary}}
),
{ok, Audio} = openai_response:parse(RawResponse),
{ok, Audio} = openai_response:parse(RawResponse),
Metadata = openai_response:metadata(RawResponse).
Speech model availability and deprecations must be checked before real use; the SDK does not silently substitute a Realtime workflow.
Images
openai_images:generate(Client, Params, Options) and openai_images:edit(Client, Params, Options) each
have /2 forms. Generate requires prompt; edit requires image and prompt. File arrays preserve repeated image fields. All named
options in the module's function docs are supported, including model, n, quality,
size, response_format, output_format, background, compression, stream/partial_images,
and finite SVG/markup/GIF settings where present in the pinned method signature.
Model-specific restrictions remain with the server.
Default mode images_response returns an ImagesResponse Response. Base64 strings
and URLs are data; neither is automatically decoded or downloaded. stream=true
selects image_gen_event for generate and image_edit_event for edit. next/1
returns event Response values, eos, or a safe error; non-model scalar events
retain the reference non-strict JSON fallback. No Chat/Responses accumulator is used.
{ok, RawResponse} = openai_images:generate(
Client,
#{prompt => <<"A blue square on white.">>, model => <<"gpt-image-2.6-flare">>, stream => true},
#{response_mode => {raw, image_gen_event}}
),
{ok, Stream} = openai_response:parse(RawResponse),
{ok, Stream} = openai_response:parse(RawResponse),
try
openai_stream:next(Stream)
after
openai_stream:close(Stream)
end.
Partial images may be absent even when requested. Preserve the actual terminal event/usage; a heartbeat or partial image is not completion.
Uploads
| Signature (default-options form) | Parameters | Result |
|---|---|---|
openai_uploads:create(Client, Params, Options) (/2) |
bytes, filename, mime_type, purpose; optional expires_after | Upload Response; upload |
openai_uploads_parts:create(Client, ID, Params, Options) (/3) |
data (finite upload part) | UploadPart Response; upload_part |
openai_uploads:complete(Client, ID, Params, Options) (/3) |
ordered part_ids; optional md5 | Upload Response |
openai_uploads:cancel(Client, ID, Options) (/2) |
ID | Upload Response |
See chunked upload helper for sequential parts, source handling, request overrides and remote ownership. Completed Uploads contain a File that must be deleted separately when no longer needed.
See media contracts and runnable local examples.
Batches, fine-tuning and vector stores
All methods below use the existing Client pipeline, errors, retries and timeouts.
Client is openai:client(), each ID is a nonempty binary, Params is the module's
finite METHOD_params() map, and Options is openai_request:resource_options().
The final Options argument may be omitted. Atom or binary parameter spellings
are accepted; conflicting spellings are rejected. Required fields are listed
in each exported spec's documentation. Nested JSON data is not server-policy validation.
Python counterparts use the resource names in the first column.
Normal returns {ok, Response} or {ok, Page} as indicated; non-JSON successful
model fallback can be binary. Errors return {error, openai:error()}. Options
response_mode => {raw, Mode} return the existing raw Response; {body, Mode}
returns openai_body:body(), which must be released. For list/search/content use
page as Mode; other modes are in the last column. Repeated raw parse preserves
the same materialized result and metadata; Body follows the existing close/release
contract. There is no new wrapper or transport.
| Pinned Python resource method | Erlang signature (with Options) | Result / Mode |
|---|---|---|
batches.create |
openai_batches:create(Client, Params, Options) |
Response / batch |
batches.retrieve |
openai_batches:retrieve(Client, ID, Options) |
Response / batch |
batches.list |
openai_batches:list(Client, Params, Options) |
Page / page |
batches.cancel |
openai_batches:cancel(Client, ID, Options) |
Response / batch |
fine_tuning.alpha.graders.run |
openai_fine_tuning_alpha_graders:run(Client, Params, Options) |
Response / grader_run_response |
fine_tuning.alpha.graders.validate |
openai_fine_tuning_alpha_graders:validate(Client, Params, Options) |
Response / grader_validate_response |
fine_tuning.checkpoints.permissions.create |
openai_fine_tuning_checkpoints_permissions:create(Client, ID, Params, Options) |
Page / page |
fine_tuning.checkpoints.permissions.retrieve |
openai_fine_tuning_checkpoints_permissions:retrieve(Client, ID, Params, Options) |
Response / permission_retrieve_response |
fine_tuning.checkpoints.permissions.list |
openai_fine_tuning_checkpoints_permissions:list(Client, ID, Params, Options) |
Page / page |
fine_tuning.checkpoints.permissions.delete |
openai_fine_tuning_checkpoints_permissions:delete(Client, IDs, Options) |
Response / permission_delete_response |
fine_tuning.jobs.create |
openai_fine_tuning_jobs:create(Client, Params, Options) |
Response / fine_tuning_job |
fine_tuning.jobs.retrieve |
openai_fine_tuning_jobs:retrieve(Client, ID, Options) |
Response / fine_tuning_job |
fine_tuning.jobs.list |
openai_fine_tuning_jobs:list(Client, Params, Options) |
Page / page |
fine_tuning.jobs.cancel |
openai_fine_tuning_jobs:cancel(Client, ID, Options) |
Response / fine_tuning_job |
fine_tuning.jobs.list_events |
openai_fine_tuning_jobs:list_events(Client, ID, Params, Options) |
Page / page |
fine_tuning.jobs.pause |
openai_fine_tuning_jobs:pause(Client, ID, Options) |
Response / fine_tuning_job |
fine_tuning.jobs.resume |
openai_fine_tuning_jobs:resume(Client, ID, Options) |
Response / fine_tuning_job |
fine_tuning.jobs.checkpoints.list |
openai_fine_tuning_jobs_checkpoints:list(Client, ID, Params, Options) |
Page / page |
vector_stores.create |
openai_vector_stores:create(Client, Params, Options) |
Response / vector_store |
vector_stores.retrieve |
openai_vector_stores:retrieve(Client, ID, Options) |
Response / vector_store |
vector_stores.update |
openai_vector_stores:update(Client, ID, Params, Options) |
Response / vector_store |
vector_stores.list |
openai_vector_stores:list(Client, Params, Options) |
Page / page |
vector_stores.delete |
openai_vector_stores:delete(Client, ID, Options) |
Response / vector_store_deleted |
vector_stores.search |
openai_vector_stores:search(Client, ID, Params, Options) |
Page / page |
vector_stores.files.create |
openai_vector_stores_files:create(Client, ID, Params, Options) |
Response / vector_store_file |
vector_stores.files.retrieve |
openai_vector_stores_files:retrieve(Client, IDs, Options) |
Response / vector_store_file |
vector_stores.files.update |
openai_vector_stores_files:update(Client, IDs, Params, Options) |
Response / vector_store_file |
vector_stores.files.list |
openai_vector_stores_files:list(Client, ID, Params, Options) |
Page / page |
vector_stores.files.delete |
openai_vector_stores_files:delete(Client, IDs, Options) |
Response / vector_store_file_deleted |
vector_stores.files.content |
openai_vector_stores_files:content(Client, IDs, Options) |
Page / page |
vector_stores.file_batches.create |
openai_vector_stores_file_batches:create(Client, ID, Params, Options) |
Response / vector_store_file_batch |
vector_stores.file_batches.retrieve |
openai_vector_stores_file_batches:retrieve(Client, IDs, Options) |
Response / vector_store_file_batch |
vector_stores.file_batches.cancel |
openai_vector_stores_file_batches:cancel(Client, IDs, Options) |
Response / vector_store_file_batch |
vector_stores.file_batches.list_files |
openai_vector_stores_file_batches:list_files(Client, IDs, Params, Options) |
Page / page |
Composite IDs are typed maps, not positional tuples:
FileIDs = #{vector_store_id => <<"vs_example">>, file_id => <<"file_example">>},
BatchIDs = #{vector_store_id => <<"vs_example">>, batch_id => <<"vsfb_example">>},
PermissionIDs = #{
fine_tuned_model_checkpoint => <<"ft_checkpoint">>,
permission_id => <<"perm_example">>
},
{ok, RawResponse} = openai_vector_stores_files:retrieve(
Client,
FileIDs,
#{response_mode => {raw, vector_store_file}}
),
{ok, File} = openai_response:parse(RawResponse),
{ok, File} = openai_response:parse(RawResponse),
#{request_id := RequestID} = openai_response:metadata(RawResponse).
See vector-store upload and polling workflows for create_and_poll, upload, upload_and_poll, poll and upload_summary.
Checkpoint permission requests use bearer selection; provide an appropriately authorized bearer credential. The SDK does not switch to the admin credential. Grader content may be a string, one text/image/audio item, or an array. For example, with a caller-authorized grader model (placeholder below):
Grader = #{
type => <<"score_model">>,
name => <<"score">>,
model => <<"authorized-grader-model">>,
range => [0.0, 1.0],
input => [
#{
role => <<"user">>,
content =>
[#{type => <<"output_text">>, text => <<"hello">>}]
}
]
},
{ok, RawResponse} = openai_fine_tuning_alpha_graders:validate(
Client,
#{grader => Grader},
#{response_mode => {raw, grader_validate_response}}
),
{ok, Value} = openai_response:parse(RawResponse),
{ok, Value} = openai_response:parse(RawResponse),
Data = openai_response:to_map(Value, #{mode => native, exclude_unset => false}).
Training/Batch jobs and permissions require caller-owned prerequisites; examples do not create training or inference jobs automatically. See the runnable local vector-store example and detailed contracts.