OpenAI Erlang SDK – Native OpenAI API Integration for Erlang/OTP Scalicon (SCALICON INC.) released version 0.1.0 of openai_erlang, an unofficial Erlang/OTP SDK that gives Erlang applications access to the OpenAI API, covering Responses, Chat Completions, streaming, structured outputs, tool calling, file uploads, audio, images and organization administration. The Hex package openai_erlang is not yet published, so Hex installation is unverified; Scalicon directs developers to build from a local checkout with rebar3 compile and rebar3 shell, and the documentation website is planned but not published. The SDK reads OPENAI_API_KEY by default via openai:new/1, and startup and Client construction open no network connections. 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. - Official OpenAI REST API reference https://platform.openai.com/docs/api-reference . - Official OpenAI OpenAPI specification https://github.com/openai/openai-openapi . - Erlang API https://github.com/scalicon/openai-erlang/blob/main/docs/API.md : direct resource operations and common SDK APIs. - Public helpers https://github.com/scalicon/openai-erlang/blob/main/docs/HELPERS.md : parsing, polling, upload and iteration workflows. - Release notes https://github.com/scalicon/openai-erlang/blob/main/docs/RELEASE NOTES.md : version 0.1.0 scope, features and limitations. - Detailed contracts https://github.com/scalicon/openai-erlang/blob/main/docs/CONTRACTS.md : authentication, transport, serialization, lifecycle and limitations. - Python → Erlang API mapping https://github.com/scalicon/openai-erlang/blob/main/docs/PYTHON-ERLANG-API-MAPPING.md : resource operations, public helpers and common SDK APIs. - Runnable examples https://github.com/scalicon/openai-erlang/blob/main/examples/README.md , including controlled local fixtures. - Documentation website: planned, not published at https://scalicon.github.io/sdk/openai/ https://scalicon.github.io/sdk/openai/ . 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 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 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: js {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 handling-errors and Compatibility 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 https://github.com/scalicon/openai-erlang/blob/main/examples/README.md media-resources , API https://github.com/scalicon/openai-erlang/blob/main/docs/API.md media-resources | | Batches, fine-tuning, Vector Stores | Upload/poll workflows https://github.com/scalicon/openai-erlang/blob/main/docs/HELPERS.md vector-store-workflows , example https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/vector stores.erl , API https://github.com/scalicon/openai-erlang/blob/main/docs/API.md batches-fine-tuning-and-vector-stores | | Containers, Conversations, Decisions, Skills, Safety, signaling and provenance | Platform examples https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/platform resources.erl , API https://github.com/scalicon/openai-erlang/blob/main/docs/API.md platform-resources | | Organization administration | Admin example https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/admin organization.erl , API https://github.com/scalicon/openai-erlang/blob/main/docs/API.md organization-administration | 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: js {ok, Admin} = openai:new {api key = << } , try openai admin organization groups:list Admin, {} after ok = openai:close Admin end. 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. 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. 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 . 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. js {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 . 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. php 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 . 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 . 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. js 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 transport-configuration . 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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md subject-workload-authentication and X.509 contracts https://github.com/scalicon/openai-erlang/blob/main/docs/API.md x509-workload-authentication for refresh and cleanup. Vertex supports supplied callbacks and native Google credential subsets through openai providers:vertex/1 ; see provider options https://github.com/scalicon/openai-erlang/blob/main/docs/API.md http-providers . 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. 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} } } . 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: php 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. 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. js {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 : js {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 https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/responses stream.erl and Chat streaming examples https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/chat completions stream.erl . 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: js {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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md realtime-raw-wss . 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. 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 : js 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 https://github.com/scalicon/openai-erlang/blob/main/docs/HELPERS.md buffered-structured-parsing . 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 js {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 js {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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md pagination-and-list-resources and the runnable example https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/pagination.erl . 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: js {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. Prerequisites: an open Client , Files access and a readable input.jsonl . This preserves the pinned fine-tune purpose and eager path upload: js {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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md multipart-and-upload-sources . 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 https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/multipart upload.erl . 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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md webhooks and the synthetic local example https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/webhook signature.erl . TODO: webhook unwrap and typed event models are not implemented. 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: js 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. 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. 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: js {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 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: js {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 https://github.com/scalicon/openai-erlang/blob/main/docs/CONTRACTS.md timeouts-and-retries for phase semantics and current transport restrictions. Use Erlang/OTP Logger in your application. An SDK-specific logging configuration switch is not provided. 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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md response-values for exact presence/alias rules. 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 https://github.com/scalicon/openai-erlang/blob/main/docs/HELPERS.md buffered-structured-parsing . 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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md lazy-http-bodies and example https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/http body.erl . 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 : js {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: js 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. 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: js {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: js 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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md tls-proxy-and-redirects , including the current HTTPS-only URL policy and credential isolation rules. 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 https://github.com/scalicon/openai-erlang/blob/main/docs/CONTRACTS.md lifetime-ownership-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. 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. 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: js {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: js {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 https://github.com/scalicon/openai-erlang/blob/main/docs/API.md http-providers and examples https://github.com/scalicon/openai-erlang/blob/0.1.0/examples/providers.erl . The SDK follows the request and response behavior of the official OpenAI Python SDK 3.52.0 , pinned to 311924f055110122991cc23b988a1836793551a1 https://github.com/openai/openai-python/tree/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 https://github.com/scalicon/openai-erlang/blob/main/docs/PYTHON-ERLANG-API-MAPPING.md , API reference https://github.com/scalicon/openai-erlang/blob/main/docs/API.md , public helpers https://github.com/scalicon/openai-erlang/blob/main/docs/HELPERS.md and contracts https://github.com/scalicon/openai-erlang/blob/main/docs/CONTRACTS.md for supported behavior, intentional differences and known limitations. 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. 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. Scalicon maintains this library and is committed to reviewing bug reports and pull requests. Please use GitHub Issues https://github.com/scalicon/openai-erlang/issues to report bugs or request features, and submit pull requests https://github.com/scalicon/openai-erlang/pulls for proposed improvements. See the contribution guide https://github.com/scalicon/openai-erlang/blob/main/docs/CONTRIBUTING.md 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 https://github.com/scalicon/openai-erlang/blob/main/docs/TRANSPORT.md . 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. Apache-2.0. See LICENSE.md https://github.com/scalicon/openai-erlang/blob/0.1.0/LICENSE.md .