OpenAI Erlang SDK
OpenAI Erlang SDK is an unofficial library that gives Erlang/OTP applications access to the OpenAI API. Developed by Scalicon (SCALICON INC.), it supports Responses, Chat Completions, streaming, structured outputs, tool calling, file uploads, audio, images and organization administration.
Contents
- Documentation
- Installation
- Usage
- Concurrency
- Streaming responses
- Realtime API
- Using types
- Pagination
- Nested params
- File uploads
- Webhook verification
- Handling errors
- Request IDs
- Retries
- Timeouts
- Advanced
- Microsoft Azure OpenAI
- Amazon Bedrock
- Compatibility
- Versioning
- Requirements
- Contributing
- License
Documentation
- Official OpenAI REST API reference.
- Official OpenAI OpenAPI specification.
- Erlang API: direct resource operations and common SDK APIs.
- Public helpers: parsing, polling, upload and iteration workflows.
- Release notes: version 0.1.0 scope, features and limitations.
- Detailed contracts: authentication, transport, serialization, lifecycle and limitations.
- Python → Erlang API mapping: resource operations, public helpers and common SDK APIs.
- Runnable examples, including controlled local fixtures.
- Documentation website: planned, not published at https://scalicon.github.io/sdk/openai/.
Installation
Hex installation will be available after publication of version 0.1.0. These configurations describe that release; Hex installation has not been verified because the package is not published yet.
The Hex package is openai_erlang; the OTP application and module prefix
remain openai.
For rebar3, add to rebar.config:
{deps, [
{openai, "0.1.0", {pkg, openai_erlang}}
]}.
For Erlang.mk, put this before include erlang.mk:
DEPS = openai
dep_openai = hex 0.1.0 openai_erlang
include erlang.mk
For Mix, add the dependency to deps/0 in mix.exs (keep your other entries):
defp deps do
[
{:openai, "~> 0.1.0", hex: :openai_erlang}
]
end
Append openai to the existing applications list in your consuming Erlang
application's .app.src. This is a configuration excerpt, not a runnable shell
command. Preserve kernel, stdlib and all your other applications:
{applications, [
kernel,
stdlib,
%% ... keep the rest of your existing applications here ...
openai
]}
Before publication, build and try the SDK from a local checkout. Run these commands from the root of that checkout:
rebar3 compile
rebar3 shell
Usage
Set your API key before starting the Erlang node:
export OPENAI_API_KEY='your-api-key'
rebar3 shell
From the Erlang shell, start the application, create a Client and make a Responses request:
{ok, _} = application:ensure_all_started(openai),
{ok, Client} = openai:new(#{}),
{ok, Response} = openai_responses:create(Client, #{
model => <<"gpt-5.5">>,
instructions => <<"You are a coding assistant that talks like a pirate.">>,
input => <<"How do I check if a Python object is an instance of a class?">>
}),
io:format("~ts~n", [openai_response:output_text(Response)]).
new/1 reads OPENAI_API_KEY by default; api_key can also be an explicit
binary or zero-arity credential callback. Startup and Client construction do
not open network connections. Model availability depends on your account.
Unless stated otherwise, request examples below use this open Client and a
fresh set of shell bindings; they are not one continuous paste. Paths and
environment-dependent examples list their prerequisites. See
Managing resources for ownership and closing Clients.
Paired examples retain the pinned README's models and payloads, including the
omission of store; no store => false is silently added. Model access and
service defaults still depend on your account.
Chat Completions is also available:
{ok, Completion} = openai_chat_completions:create(Client, #{
model => <<"gpt-5.5">>,
messages => [
#{
<<"role">> => <<"developer">>,
<<"content">> => <<"Talk like a pirate.">>
},
#{
<<"role">> => <<"user">>,
<<"content">> => <<"How do I check if a Python object is an instance of a class?">>
}
]
}),
#{<<"choices">> := [#{<<"message">> := Message} | _]} =
openai_response:to_map(Completion),
io:format("~ts~n", [maps:get(<<"content">>, Message)]).
These introductory examples expect successful model responses. See Handling errors and Compatibility for other outcomes. Additional SDK-specific examples use the same Client:
{ok, Models} = openai_models:list(Client),
{ok, Embeddings} = openai_embeddings:create(Client, #{
model => <<"text-embedding-3-small">>,
input => <<"Hello">>
}),
{ok, Moderation} = openai_moderations:create(Client, #{
model => <<"omni-moderation-latest">>,
input => <<"Hello">>
}).
| More implemented resources | Examples / API |
|---|---|
| Audio, Images, Uploads | Media examples, API |
| Batches, fine-tuning, Vector Stores | Upload/poll workflows, example, API |
| Containers, Conversations, Decisions, Skills, Safety, signaling and provenance | Platform examples, API |
| Organization administration | Admin example, API |
Polling/upload helpers can make multiple requests; they do not automatically
execute tools or roll back remote uploads. Retired endpoints retain their pinned
request contract; that does not make the remote service available.
Admin methods use admin_api_key / OPENAI_ADMIN_KEY; an admin-only Client is
allowed. An admin key is not a fallback for ordinary bearer-only resources.
For a read-only example with OPENAI_ADMIN_KEY set:
{ok, Admin} = openai:new(#{api_key => <<>>}),
try
openai_admin_organization_groups:list(Admin, #{})
after
ok = openai:close(Admin)
end.
Workload identity authentication
Workload identity exchanges short-lived subject tokens lazily. The helper
functions return {ok, Provider}; pass that descriptor to openai:new/1.
Construction does not obtain a subject token or prove cloud authentication.
The metadata helpers' optional timeout is in milliseconds (default 10000);
null disables that timer. Token refresh buffers use seconds instead.
For real requests, configure the identity provider and service account in your
organization; idp-123 and sa-456 below are the reference's illustrative IDs.
Start the application as in Usage before running these independent examples.
Kubernetes
Prerequisites: a mounted, readable service-account token with the configured audience/issuer, and an OpenAI workload identity mapping for that subject.
{ok, Provider} = openai_auth:k8s_service_account_token_provider(
<<"/var/run/secrets/kubernetes.io/serviceaccount/token">>
),
{ok, WorkloadClient} = openai:new(#{
workload_identity => #{
identity_provider_id => <<"idp-123">>,
service_account_id => <<"sa-456">>,
provider => Provider
}
}),
try
openai_chat_completions:create(WorkloadClient, #{
model => <<"gpt-5.5">>,
messages => [#{<<"role">> => <<"user">>, <<"content">> => <<"Hello!">>}]
})
after
ok = openai:close(WorkloadClient)
end.
Azure managed identity
Prerequisites: a supported Azure managed-identity metadata endpoint and an identity mapped to the OpenAI provider/account. This constructor-only example performs no metadata request; a later API call obtains the token lazily.
{ok, Provider} = openai_auth:azure_managed_identity_token_provider(#{
resource => <<"https://management.azure.com/">>
}),
{ok, AzureClient} = openai:new(#{
workload_identity => #{
identity_provider_id => <<"idp-123">>,
service_account_id => <<"sa-456">>,
provider => Provider
}
}),
ok = openai:close(AzureClient).
GCP metadata identity
Prerequisites: Google Compute metadata access and a service account able to obtain an ID token with this audience, mapped to OpenAI. No metadata request is made by this constructor-only example.
{ok, Provider} = openai_auth:gcp_id_token_provider(#{
audience => <<"https://api.openai.com/v1">>
}),
{ok, GCPClient} = openai:new(#{
workload_identity => #{
identity_provider_id => <<"idp-123">>,
service_account_id => <<"sa-456">>,
provider => Provider
}
}),
ok = openai:close(GCPClient).
Custom subject token callback
Prerequisite: implement a callback returning a real subject JWT trusted by your configured identity provider. The literal below preserves the reference example; it is not a usable credential. The callback is not invoked at construction.
Provider = #{
token_type => jwt,
get_token => fun() -> <<"your-jwt-token">> end
},
{ok, CustomClient} = openai:new(#{
workload_identity => #{
identity_provider_id => <<"idp-123">>,
service_account_id => <<"sa-456">>,
provider => Provider
}
}),
ok = openai:close(CustomClient).
Refresh buffer
Prerequisite: a readable subject-token file at /var/token and the same identity
mapping. refresh_buffer_seconds is in seconds, default 1200; HTTP timeout
options use milliseconds. As in the pinned example, this sets 120.0 seconds:
{ok, Provider} = openai_auth:k8s_service_account_token_provider(<<"/var/token">>),
{ok, RefreshClient} = openai:new(#{
workload_identity => #{
identity_provider_id => <<"idp-123">>,
service_account_id => <<"sa-456">>,
provider => Provider,
refresh_buffer_seconds => 120.0
}
}),
ok = openai:close(RefreshClient).
X.509 workload identity
Prerequisites: X.509 federation enabled for your organization, matching provider
and service-account IDs, a leaf-first certificate-chain PEM and matching private
key. Set OPENAI_IDENTITY_PROVIDER_ID, OPENAI_SERVICE_ACCOUNT_ID,
OPENAI_MTLS_CERTIFICATE_CHAIN and OPENAI_MTLS_PRIVATE_KEY. Optional
OPENAI_MTLS_CA_BUNDLE supplies server trust and
OPENAI_MTLS_PRIVATE_KEY_PASSWORD unlocks an encrypted key. These environment
values are read by this application example, not additional automatic SDK options.
CertificateTLSOptions = #{
certfile => unicode:characters_to_binary(os:getenv("OPENAI_MTLS_CERTIFICATE_CHAIN")),
keyfile => unicode:characters_to_binary(os:getenv("OPENAI_MTLS_PRIVATE_KEY"))
},
TrustedTLSOptions =
case os:getenv("OPENAI_MTLS_CA_BUNDLE") of
false -> CertificateTLSOptions;
CAFile -> CertificateTLSOptions#{cacertfile => unicode:characters_to_binary(CAFile)}
end,
TLSOptions =
case os:getenv("OPENAI_MTLS_PRIVATE_KEY_PASSWORD") of
false -> TrustedTLSOptions;
Password -> TrustedTLSOptions#{password => unicode:characters_to_binary(Password)}
end,
{ok, X509Client} = openai:new(#{
workload_identity => #{
type => x509,
identity_provider_id => unicode:characters_to_binary(
os:getenv("OPENAI_IDENTITY_PROVIDER_ID")
),
service_account_id => unicode:characters_to_binary(
os:getenv("OPENAI_SERVICE_ACCOUNT_ID")
)
},
tls => TLSOptions,
follow_redirects => false
}),
ok = openai:close(X509Client).
Tokens are exchanged lazily at the fixed
https://mtls.auth.openai.com/oauth/token endpoint, then cached/refreshed. The
default API base is https://mtls.api.openai.com/v1 unless explicitly configured
or set by OPENAI_BASE_URL. API requests must remain HTTPS on that configured
origin, with peer/hostname verification. This is certificate-backed token
exchange, not merely transport mTLS.
Ordinary copies use independent lazy auth caches retained until the shared HTTP
context closes. Explicit openai_auth handles are shared and separately owned.
See subject authentication and
X.509 contracts for refresh and cleanup.
Vertex supports supplied callbacks and native Google credential subsets through
openai_providers:vertex/1; see provider options.
TODO: executable credential providers (AWS credential_process
and Google executable sources), AWS AssumeRole with MFA, and
automatic provider/workload authentication for WebSocket connections
are not implemented.
Application-supplied credential callbacks are supported separately.
Vision
Prerequisites: an open Client, model access, and an image accessible to the
service. The SDK passes the URL to OpenAI without fetching it locally. This
retains the pinned example's image URL, prompt and payload:
Prompt = <<"What is in this image?">>,
ImageURL =
<<"https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg">>,
{ok, Vision} = openai_responses:create(Client, #{
model => <<"gpt-5.5">>,
input => [
#{
<<"role">> => <<"user">>,
<<"content">> => [
#{<<"type">> => <<"input_text">>, <<"text">> => Prompt},
#{<<"type">> => <<"input_image">>, <<"image_url">> => ImageURL}
]
}
]
}).
Alternatively, provide a readable PNG at path/to/image.png. This complete
example sends the same prompt with a data URI:
Prompt = <<"What is in this image?">>,
{ok, PNG} = file:read_file("path/to/image.png"),
Base64Image = base64:encode(PNG),
ImageURL = <<"data:image/png;base64,", Base64Image/binary>>,
{ok, Vision} = openai_responses:create(Client, #{
model => <<"gpt-5.5">>,
input => [
#{
<<"role">> => <<"user">>,
<<"content">> => [
#{<<"type">> => <<"input_text">>, <<"text">> => Prompt},
#{<<"type">> => <<"input_image">>, <<"image_url">> => ImageURL}
]
}
]
}).
Concurrency
A request blocks its calling Erlang process, not the entire VM. Run independent requests in separate processes; separate async/await APIs are not required. For example:
Parent = self(),
Ref = make_ref(),
{Worker, Monitor} = spawn_monitor(fun() ->
Result = openai_responses:create(Client, #{
model => <<"gpt-5.5">>,
input => <<"Explain disestablishmentarianism to a smart five year old.">>
}),
Parent ! {Ref, self(), Result}
end),
receive
{Ref, Worker, Result} ->
erlang:demonitor(Monitor, [flush]),
case Result of
{ok, Response} ->
io:format("~ts~n", [openai_response:output_text(Response)]);
{error, Error} ->
{error, maps:get(kind, Error)}
end;
{'DOWN', Monitor, process, Worker, Reason} ->
{error, {worker_down, Reason}}
end.
The reference and worker PID correlate replies; only the matching monitor/PID
handles termination before a result. The result branch releases the monitor
with demonitor(..., [flush]). Unrelated mailbox messages are left untouched;
the example adds no HTTP deadline.
A Client survives its creating process. Keep its shared HTTP context open until
workers finish; use openai:close/1 when their work is complete. Concurrent
requests use separate connections; sequential HTTP/1.1 requests can reuse one.
Capacity refusal is immediate rather than a waiting pool. A Stream must be
opened and read by the same owner process.
Streaming responses
Responses and Chat support pull-based SSE. This is the pinned raw SSE example
with the same model/prompt. Prerequisites: an open Client and model access.
{ok, Stream} = openai_responses:create(Client, #{
model => <<"gpt-5.5">>,
input => <<"Write a one-sentence bedtime story about a unicorn.">>,
stream => true
}),
try
openai_stream:consume(Stream, fun(Event) ->
io:format("~p~n", [Event])
end)
after
ok = openai_stream:close(Stream)
end.
The SDK-specific openai_responses:stream/2,3 helper additionally accumulates
state. For example, to collect a final Response (same payload, new request):
{ok, Stream} = openai_responses:stream(Client, #{
model => <<"gpt-5.5">>,
input => <<"Write a one-sentence bedtime story about a unicorn.">>
}),
try
case openai_responses_stream:get_final_response(Stream) of
{ok, Final} -> openai_response:output_text(Final);
{error, Error} -> {error, maps:get(kind, Error)}
end
after
ok = openai_stream:close(Stream)
end.
next/1 returns {ok, Event}, eos or {error, Error}. Read metadata before
closing. consume/2 and fold/3 always close, including on callback exceptions.
The final helper drains its cursor and requires response.completed.
Failed/incomplete responses remain events followed by eos. Open streams are
not automatically replayed. See Responses and
Chat streaming examples.
Realtime API
Direct WSS supports raw text/binary exchange. Prerequisites: an open Client,
Realtime model access and a direct WSS-compatible network configuration.
The following adapts the reference's gpt-realtime-2 text conversation to raw
JSON messages; typed session/conversation methods are not available:
{ok, Connection} = openai_realtime:connect(Client, #{model => <<"gpt-realtime-2">>}),
Send = fun(Event) ->
Bytes = iolist_to_binary(json:encode(Event)),
openai_realtime_connection:send_raw(Connection, {text, Bytes})
end,
Read = fun Next() ->
case openai_realtime_connection:recv_bytes(Connection, 15000) of
{ok, Bytes} ->
case json:decode(Bytes) of
#{<<"type">> := <<"response.output_text.delta">>, <<"delta">> := Delta} ->
io:format("~ts", [Delta]),
Next();
#{<<"type">> := <<"response.output_text.done">>} ->
io:format("~n"),
Next();
#{<<"type">> := <<"response.done">>, <<"response">> := Response} ->
case maps:get(<<"status">>, Response) of
<<"completed">> -> ok;
_ -> {error, incomplete_response}
end;
#{<<"type">> := <<"error">>} ->
{error, realtime_error};
_ ->
Next()
end;
{error, Error} ->
{error, maps:get(kind, Error)}
end
end,
try
ok = Send(#{
<<"type">> => <<"session.update">>,
<<"session">> => #{
<<"type">> => <<"realtime">>,
<<"output_modalities">> => [<<"text">>]
}
}),
ok = Send(#{
<<"type">> => <<"conversation.item.create">>,
<<"item">> => #{
<<"type">> => <<"message">>,
<<"role">> => <<"user">>,
<<"content">> => [#{<<"type">> => <<"input_text">>, <<"text">> => <<"Say hello!">>}]
}
}),
ok = Send(#{<<"type">> => <<"response.create">>}),
Read()
after
ok = openai_realtime_connection:close(Connection)
end.
Only the opening owner may receive. Successful send is not proof of server
receipt; inspect server messages for protocol errors. An opened Connection
survives Client close; Connection close does not close the HTTP Client.
Owner death and application shutdown release it. See WSS contracts.
The 15000ms receive timeout is an explicit Erlang example choice, not a reference
default. A first session.created message is not a completed answer.
TODO: typed Realtime events/helpers and automatic reconnect are not implemented. HTTP SDP signaling is available; the SDK does not include a WebRTC media engine.
Using types
Resources export Erlang types/specs for params, options and results. Client,
Response, Body, Stream and Page handles are opaque; use their public functions.
JSON objects use maps, arrays lists, strings UTF-8 binaries and JSON null null.
Structured parsing uses a strict wire schema and an application validator. This
SDK-specific example intentionally sets store => false:
Schema = #{
<<"type">> => <<"object">>,
<<"properties">> => #{
<<"ok">> => #{<<"type">> => <<"boolean">>}
},
<<"required">> => [<<"ok">>],
<<"additionalProperties">> => false
},
Validator = fun(Bytes) ->
case json:decode(Bytes) of
#{<<"ok">> := Flag} = Value when is_boolean(Flag) -> {ok, Value};
_ -> {error, invalid}
end
end,
Format = #{
name => <<"flag">>,
schema => Schema,
parse => Validator
},
{ok, ParsedResponse} = openai_responses:parse(Client, #{
model => <<"gpt-5.5">>,
input => <<"Return ok=true.">>,
store => false,
text_format => Format
}),
{ok, #{values := Values}} = openai_response:parsed(ParsedResponse).
The SDK sends your schema; your application validates returned values. It does
not perform arbitrary JSON Schema validation or automatic class conversion.
Values contains {Path, Value} pairs, retaining false/0/empty/null without
overwriting server extras. Chat uses response_format => {typed, Format} with
openai_chat_completions:parse/2,3. Validator failures return safe errors.
See structured parsing.
Pagination
List methods return immutable Pages. Prerequisites: an open Client and read
access to fine-tuning jobs. This preserves the reference's resource and limit;
no following page is prefetched:
Manual next page
{ok, Page} = openai_fine_tuning_jobs:list(Client, #{limit => 20}),
Items = openai_page:items(Page),
Next =
case openai_page:has_next_page(Page) of
true ->
io:format("Next page: ~p~n", [openai_page:next_page_info(Page)]),
openai_page:get_next_page(Page);
false ->
done;
{error, Error} ->
{error, Error}
end.
Alternatively, fold all pages
{ok, Page} = openai_fine_tuning_jobs:list(Client, #{limit => 20}),
{ok, JobsReversed} = openai_page:fold(Page, fun(Job, Acc) -> [Job | Acc] end, []),
Jobs = [openai_response:to_map(Job) || Job <- lists:reverse(JobsReversed)],
io:format("~p~n", [Jobs]).
fold/3 visits items, fold_pages/3 visits pages, fetching only as needed. Early
halt, for example fun(Item, _) -> {halt, Item} end, sends no next request.
Choose one of the alternatives above; they are independent traversals.
Loaded data/metadata survive Client close; fetching another page requires its
open HTTP context. See pagination
and the runnable example.
Nested params
Use atom keys for named top-level params and binary wire keys for nested JSON.
With an open Client, the pinned nested-parameter example becomes:
{ok, NestedResponse} = openai_responses:create(Client, #{
input => [
#{<<"role">> => <<"user">>, <<"content">> => <<"How much ?">>}
],
model => <<"gpt-5.5">>,
text => #{
<<"format">> => #{<<"type">> => <<"json_object">>}
}
}).
Function tools are likewise nested data; the application explicitly handles returned tool calls. The SDK never executes them automatically.
File uploads
Prerequisites: an open Client, Files access and a readable input.jsonl.
This preserves the pinned fine-tune purpose and eager path upload:
{ok, Uploaded} = openai_files:create(Client, #{
file => {path, <<"input.jsonl">>},
purpose => <<"fine-tune">>
}),
#{<<"id">> := FileID} = openai_response:to_map(Uploaded).
For in-memory audio, provide a readable audio.wav; this preserves the reference
model, multipart filename and MIME. The SDK accepts bytes rather than a foreign
file-like object:
{ok, AudioBytes} = file:read_file("audio.wav"),
{ok, Transcription} = openai_audio_transcriptions:create(Client, #{
model => <<"gpt-4o-transcribe">>,
file => {<<"audio.wav">>, AudioBytes, <<"audio/wav">>}
}).
Use {Filename, Bytes, ContentType} for overrides, or {file, Path} for an
SDK-owned lazy file. The SDK opens/closes that source; arbitrary IO devices are
not accepted. Finite producer descriptors are supported, with explicit errors
for non-replayable body-preserving redirect/auth replay.
See multipart.
The remote File remains yours to delete with openai_files:delete(Client, FileID)
when no longer needed. Client close is local cleanup, not remote deletion.
openai_files:content/2,3 returns decoded binary bytes; raw/Body add metadata and
streaming download helpers. Download permissions depend on the service/purpose.
See upload examples.
Webhook verification
Verification is local: pass original body bytes, not decoded/re-encoded
JSON. Prerequisites: a Client configured with webhook_secret or
OPENAI_WEBHOOK_SECRET, and your HTTP server's exact body/header values.
This handler fragment expects OriginalBody and IncomingHeaders from that
server; it does not start a web server:
case openai_webhooks:verify_signature(Client, OriginalBody, IncomingHeaders) of
ok ->
Event = json:decode(OriginalBody),
{200, Event};
{error, _} ->
{400, <<"Invalid signature">>}
end.
OriginalBody is a binary; headers are an ordered list of binary name/value pairs.
The result is ok or {error, Error}. Tolerance is in seconds, default 300.
The secret snapshot works after Client close and is never an API credential.
See webhooks and the synthetic local example.
TODO: webhook unwrap and typed event models are not implemented.
Handling errors
Calls return error maps rather than API-error exception classes. Match the
fields needed, not an exact map. The reference example below needs fine-tuning
access and a valid training File; file-abc123 is illustrative. A real successful
call creates a training job:
case
openai_fine_tuning_jobs:create(Client, #{
model => <<"gpt-4o">>,
training_file => <<"file-abc123">>
})
of
{ok, Job} -> {ok, Job};
{error, #{kind := rate_limit}} -> {error, try_later};
{error, #{kind := Kind} = Error} -> {error, Kind, maps:get(request_id, Error, undefined)}
end.
| HTTP status / failure | Error kind |
|---|---|
| 400 / 401 / 403 / 404 | bad_request / authentication_error / permission_denied / not_found |
| 409 / 422 / 429 | conflict / unprocessable_entity / rate_limit |
| 5xx / other non-success status | internal_server_error / api_status_error |
| Transport failure / timeout | connection_error / timeout |
message is a safe summary; HTTP errors retain body, raw bytes, headers and
request ID when available. code retains its JSON type. Server data can contain
reflected sensitive input; do not log the entire error.
Request IDs
Prerequisite: the Response obtained in Usage. This metadata-only adaptation
reuses that value instead of issuing another reference example request.
Metadata is separate from API data:
RequestID = openai_response:request_id(Response),
Metadata = openai_response:metadata(Response).
Page, Body and Stream have their own metadata/1; read Stream metadata before
close. Error maps expose request_id when provided by the server.
Retries
The default is two retries, up to three attempts. Eligible connection/phase timeout failures and HTTP 408/409/429/5xx use backoff and supported server hints, subject to replayability. Open streams are not replayed after delivery.
With API credentials/model access, configure zero Client retries but override this Chat request to five, preserving the reference's model and prompt:
{ok, RetryClient} = openai:new(#{max_retries => 0}),
try
openai_chat_completions:create(
RetryClient,
#{
model => <<"gpt-5.5">>,
messages => [
#{
<<"role">> => <<"user">>,
<<"content">> => <<"How can I get the name of the current day in JavaScript?">>
}
]
},
#{max_retries => 5}
)
after
ok = openai:close(RetryClient)
end.
Per-request Options are the Erlang mapping used here for the reference's
per-call with_options override. A handle derived with openai:with_options/2
shares its original HTTP context; closing either closes both.
Timeouts
Timeouts are milliseconds, not seconds. Defaults: connect 5000,
read/write/pool 600000. A scalar applies to all four phases; a phase map must
specify all four. null disables timers. No total deadline is enabled by default:
With API credentials/model access, this preserves the reference's 20-second Client setting, granular 2/5/10/60-second settings and 5-second request override, converted to milliseconds:
{ok, TimedClient} = openai:new(#{timeout => 20000}),
{ok, Granular} = openai:with_options(TimedClient, #{
timeout => #{
connect => 2000,
read => 5000,
write => 10000,
pool => 60000
}
}),
try
openai_chat_completions:create(
Granular,
#{
model => <<"gpt-5.5">>,
messages => [
#{
<<"role">> => <<"user">>,
<<"content">> => <<"How can I list all files in a directory using Python?">>
}
]
},
#{timeout => 5000}
)
after
ok = openai:close(TimedClient)
end.
total_timeout_ms is a separate optional Erlang extension. Timeouts may retry
according to max_retries. See timeouts for
phase semantics and current transport restrictions.
Advanced
Logging
Use Erlang/OTP Logger in your application. An SDK-specific logging configuration switch is not provided.
Null and missing values
Omitted named params and undefined/omit generally omit a wire field;
explicit null is JSON null where accepted. Constructor/copy options have their
own inheritance rules; do not apply one omission rule to every Client option.
Use openai_response:to_map/1,2 and to_json/1,2 for serialization.
exclude_unset defaults true, exclude_null false. On the serialized map,
maps:is_key/2 distinguishes an absent key from a key whose value is null.
Finite descriptors can apply defaults/coercion; raw bytes remain separate.
Default/API-name serialization retains extras. Keep API names to avoid
collisions in the optional named-view projection. Use mode => native or
mode => json for supported model families and exclude_null => true to omit
applicable nulls.
See serialization for exact presence/alias rules.
Raw responses
Prerequisites: an open Client and Chat model access. Raw methods expose bytes,
headers and repeatable parsing. This preserves the reference's raw Chat payload:
{ok, RawResponse} = openai_chat_completions:create(
Client,
#{
messages => [
#{<<"role">> => <<"user">>, <<"content">> => <<"Say this is a test">>}
],
model => <<"gpt-5.5">>
},
#{response_mode => {raw, chat_completion}}
),
Bytes = openai_response:body(RawResponse),
Metadata = openai_response:metadata(RawResponse),
Header = proplists:get_value(<<"x-my-header">>, [
{string:lowercase(Name), Value}
|| {Name, Value} <- maps:get(headers, Metadata)
]),
io:format("X-My-Header: ~p~n", [Header]),
{ok, Completion} = openai_response:parse(RawResponse),
{ok, Completion} = openai_response:parse(RawResponse),
io:format("~p~n", [openai_response:to_map(Completion)]).
Parse sends no new HTTP request. Raw SSE parse returns the same cursor without rewind. Parsed-raw methods instead return a Body handle with buffered bytes, lazy validation and cached successful parse; errors are not cached. See structured parsing.
Streaming HTTP bodies
Body mode returns after headers, then supports bytes/text/lines and file helpers.
This is HTTP body streaming, not semantic SSE. With an open Client and Chat
model access, read chunks without first materializing the body. The request
payload matches the reference; this variant uses byte chunks instead of its line
iterator. The explicit 64-byte reading unit is not a default or a response limit:
{ok, Body} = openai_chat_completions:create(
Client,
#{
messages => [
#{<<"role">> => <<"user">>, <<"content">> => <<"Say this is a test">>}
],
model => <<"gpt-5.5">>
},
#{response_mode => {body, chat_completion}}
),
ReadChunks = fun Next(Reader) ->
case openai_body:next(Reader) of
{ok, Chunk, NextReader} ->
io:format("Read ~B bytes~n", [byte_size(Chunk)]),
Next(NextReader);
eos ->
ok;
{error, Error} ->
{error, maps:get(kind, Error)}
end
end,
try
{ok, Reader} = openai_body:iter_bytes(Body, #{chunk_size => 64}),
ReadChunks(Reader)
after
ok = openai_body:release(Body)
end.
iter_bytes/1, iter_text/1 and iter_lines/1 return {ok, Reader}.
openai_body:next(Reader) returns {ok, Chunk, NextReader}, eos or an error;
continue with NextReader. Partial reading does not create a replay cache.
Full reads/parses materialize the body. Optional request body_limits set
explicit raw/decoded byte limits, without a hidden common cap.
See Body API and example.
Custom requests and extra fields
Generic verb calls reuse the authenticated pipeline and require a response mode.
The reference's custom POST becomes a buffered raw JSON result; foreign HTTP
response objects are intentionally not exposed. Prerequisites: a server at your
configured base URL implementing /foo, and an open Client:
{ok, RawResponse} = openai:post(Client, <<"/foo">>, #{
response_mode => {raw, json},
security => #{bearer_auth => true},
json => #{<<"my_param">> => true}
}),
#{headers := Headers} = openai_response:metadata(RawResponse),
FooHeader = proplists:get_value(<<"x-foo">>, Headers).
An additional SDK-specific example shows request extras. With an open Client
and model access:
openai_responses:create(
Client,
#{
model => <<"gpt-5.5">>,
input => <<"Hello">>
},
#{
extra_headers => [{<<"X-App-Name">>, <<"my-app">>}],
extra_query => #{<<"trace">> => <<"enabled">>},
extra_body => #{<<"metadata">> => #{<<"source">> => <<"readme">>}}
}
).
Resource Options accept extra_headers, extra_query and extra_body; body
extras shallowly override named fields. Binary-key response extras remain
available through to_map. Generic security flags and resource authentication
are explicit, never inferred from URL text.
Transport configuration
The SDK owns its Gun transport; HTTP-client injection and arbitrary foreign
transport options are unsupported. Configure typed tls, proxy, base_url,
default_headers and default_query settings instead. HTTPS peer/hostname
verification remains enabled.
The reference's test host/proxy are retained, with HTTPS instead of HTTP to
fit this SDK's URL policy. This snippet configures Clients only; requests need
reachable servers/proxy and trusted certificates at those addresses. Foreign
local_address/HTTP transport objects are intentionally not translated:
{ok, ProxyClient} = openai:new(#{
base_url => <<"https://my.test.server.example.com:8083/v1">>,
proxy => <<"https://my.test.proxy.example.com">>
}),
{ok, DirectCopy} = openai:with_options(ProxyClient, #{
proxy => null,
default_headers => [{<<"X-App-Name">>, <<"my-app">>}]
}),
ok = openai:close(DirectCopy).
Closing the copy also closes ProxyClient. To change routing per request,
derive a Client with with_options/2, keeping credential/origin restrictions in
mind; request Options are for documented per-call settings, not transport objects.
For API-key transport mTLS, prerequisites are the service's mTLS enrollment,
OPENAI_API_KEY, certificate-chain/key files and optional CA/password environment
variables listed in the X.509 section. This is a separate, complete setup; it
does not configure workload identity:
CertificateTLSOptions = #{
certfile => unicode:characters_to_binary(os:getenv("OPENAI_MTLS_CERTIFICATE_CHAIN")),
keyfile => unicode:characters_to_binary(os:getenv("OPENAI_MTLS_PRIVATE_KEY"))
},
TrustedTLSOptions =
case os:getenv("OPENAI_MTLS_CA_BUNDLE") of
false -> CertificateTLSOptions;
CAFile -> CertificateTLSOptions#{cacertfile => unicode:characters_to_binary(CAFile)}
end,
TLSOptions =
case os:getenv("OPENAI_MTLS_PRIVATE_KEY_PASSWORD") of
false -> TrustedTLSOptions;
Password -> TrustedTLSOptions#{password => unicode:characters_to_binary(Password)}
end,
{ok, TLSClient} = openai:new(#{
api_key => unicode:characters_to_binary(os:getenv("OPENAI_API_KEY")),
base_url => unicode:characters_to_binary(
os:getenv(
"OPENAI_BASE_URL", "https://mtls.api.openai.com/v1"
)
),
tls => TLSOptions,
follow_redirects => false
}),
ok = openai:close(TLSClient).
Server trust is independent of the client certificate. Keep certificate-bearing Clients dedicated to the configured API origin; do not repurpose a copy for another origin. Keep redirects disabled. Rotate certificates by constructing a new Client and closing the old one after its requests finish. See TLS/proxy/redirect options, including the current HTTPS-only URL policy and credential isolation rules.
Managing resources
A Client's HTTP context survives its creating process. Close it explicitly with
openai:close/1; application shutdown also closes SDK contexts.
openai:with_options/2 and openai:copy/2 share that context: closing any copy
closes all of them. Use openai:new/1 for independent lifetimes. Request, Body,
Stream and Realtime Connection ownership is separate; see
lifetime and cleanup.
Use try/after in application code:
{ok, OwnedClient} = openai:new(#{}),
try
{ok, Response} = openai_responses:create(OwnedClient, #{
model => <<"gpt-5.5">>,
input => <<"Say this is a test">>
}),
io:format("~ts~n", [openai_response:output_text(Response)])
after
ok = openai:close(OwnedClient)
end.
Active close success confirms cleanup; an already dead context is a safe no-op, not historical cleanup proof. Buffered Responses and loaded Page data remain usable after close; future requests/page fetches do not.
Body close confirms network cleanup while retaining full cache/parser buffers.
Body release also closes associated cursors, frees cache and confirms owner
DOWN. Complete cached read/parse survives Body/Client close until release;
materialized values survive release. Stream close finally closes its cursor.
Use try/after or openai_body:with/2 for release. Local cleanup never deletes
remote Files, Vector Stores or other API objects.
Microsoft Azure OpenAI
TODO: a dedicated Azure OpenAI client with deployment routing, API-version handling and Azure-specific authentication options is not implemented. Azure managed identity as a workload subject provider is available; it is not an Azure OpenAI client.
Amazon Bedrock
Prerequisites: AWS credentials with access to Bedrock's OpenAI-compatible API,
the selected model in us-west-2, and the application started as in Usage.
The default-chain example preserves the reference's region/model/prompt. Leave
AWS_BEARER_TOKEN_BEDROCK unset to exercise AWS credentials rather than its
higher-priority bearer mode:
{ok, Bedrock} = openai_providers:bedrock(#{region => <<"us-west-2">>}),
{ok, BedrockClient} = openai:new(#{provider => Bedrock}),
try
{ok, Response} = openai_responses:create(BedrockClient, #{
model => <<"openai.gpt-5.4">>,
input => <<"Say hello!">>
}),
io:format("~ts~n", [openai_response:output_text(Response)])
after
ok = openai:close(BedrockClient)
end.
For a named profile, configure my-profile (including region and supported
credentials) in your AWS files. The request below uses the same payload:
{ok, Bedrock} = openai_providers:bedrock(#{profile => <<"my-profile">>}),
{ok, BedrockClient} = openai:new(#{provider => Bedrock}),
try
{ok, Response} = openai_responses:create(BedrockClient, #{
model => <<"openai.gpt-5.4">>,
input => <<"Say hello!">>
}),
io:format("~ts~n", [openai_response:output_text(Response)])
after
ok = openai:close(BedrockClient)
end.
Supported modes include supplied bearer credentials, SigV4 static/callback
credentials and native AWS discovery subsets. Executable credential discovery
and AssumeRole MFA remain unsupported. AWS controls endpoint/model availability.
Routing/credentials belong inside the factory, not top-level api_key/base_url.
See provider limits and examples.
Compatibility
The SDK follows the request and response behavior of the official
OpenAI Python SDK 3.52.0, pinned to
311924f055110122991cc23b988a1836793551a1.
Verification combines local integration tests, comparisons against the pinned SDK, and live end-to-end requests through the public Erlang API. Live checks compare requests and results with curl and the official Python SDK; offline comparisons also check how the clients process the same captured responses.
Paired examples preserve reference request data. Erlang tuples, JSON maps, process concurrency and explicit resource ownership provide the corresponding Erlang interface. Intentional differences are documented.
Live coverage varies by operation and mode. Some scenarios remain unverified because they require additional permissions, cloud infrastructure or available services. Local tests and constructor checks are recorded separately from live end-to-end results.
See the API mapping, API reference, public helpers and contracts for supported behavior, intentional differences and known limitations.
Versioning
Version 0.1.0 is the planned first Hex release; public API changes are still possible before release. Inspect the loaded OTP application version with:
application:get_key(openai, vsn).
Source checkouts derive their version from Git; that is not a published Hex release. Endpoint availability and model access are controlled by OpenAI.
Requirements
Erlang/OTP 27 or later, including the built-in json module. The CI matrix is
OTP 27/28/29. The SDK repository's development commands use rebar3.
Contributing
Scalicon maintains this library and is committed to reviewing bug reports and pull requests. Please use GitHub Issues to report bugs or request features, and submit pull requests for proposed improvements. See the contribution guide for reporting, development and review guidelines.
Run local build commands from the root of the repository checkout.
Build and run local checks without an OpenAI key:
rebar3 compile
rebar3 fmt --check
rebar3 as test do compile,xref,dialyzer
rebar3 as test ct
Use rebar3 fmt for formatting. rebar3 coverage runs EUnit, Common Test and
cover reporting; see transport/build details.
Keep API docs, mappings and runnable examples in sync with API changes.
External reference checkouts/comparisons belong in ignored _checkout/;
ordinary SDK builds/tests do not require Python.
License
Apache-2.0. See LICENSE.md.