LlmCall

CI codecov Elixir License: MIT Hex.pm

A call-oriented SDK for LLM APIs: a canonical IR, dialect codecs, and a one-call client on Finch whose JSON layer you can replace.

defmodule MyApp.OpenAI do
  use LlmCall.Provider,
    base_url: "https://api.openai.com",
    auth: :bearer,
    codecs: [chat: LlmCall.Dialect.OpenAI.Chat]
end

client = MyApp.OpenAI.client(api_key: System.fetch_env!("OPENAI_API_KEY"))

request = %LlmCall.Request{
  model: "gpt-4o",
  messages: [%LlmCall.Message{role: :user, content: [%LlmCall.Content.Text{text: "Hello"}]}]
}

{:ok, response} = LlmCall.complete(client, request)
LlmCall.Response.text(response)

complete/3 validates, encodes, sends, and decodes. stream/3 does the same and returns a lazy Enumerable of events. generate/3 and poll/3 cover dedicated image and video endpoints, including long-running jobs.

Installation

def deps do
  [
    {:llm_call, "~> 0.4.0"}
  ]
end

Requires Elixir 1.18+ on OTP 27.1+. Runtime dependencies are Finch, mint, mint_web_socket and tool_call (which brings no runtime dependency of its own); everything else is dev/test only.

Providers

A provider is a module you write: endpoint, auth shape, and the codecs it serves. There is no built-in catalog — examples/ carries reference definitions. They are compiled in :dev and :test, so they cannot rot, and kept out of the Hex package; the link is how they are reached from the docs.

Cryptographic auth is a shape too. auth: {:sigv4, service: "bedrock", region: "us-east-1"} signs every request from the client's credentials: — a map, or a function that returns one — and region: overrides the declared region per client. Signing runs after the body is serialized, in the transport, so a codec never learns it exists.

defmodule MyApp.Groq do
  use LlmCall.Provider,
    base_url: "https://api.groq.com/openai",
    auth: :bearer,
    codecs: [chat: LlmCall.Dialect.OpenAI.Chat]
end

client = MyApp.Groq.client(api_key: System.fetch_env!("GROQ_API_KEY"))

codecs: is a named map because one endpoint can serve several request shapes. An endpoint that returns text and images is still one chat codec (modalities: [:text, :image]); a different request shape — Imagen's predict, OpenAI Images — is a second codec selected per call, declared alongside the first under the same base_url:

media_request = %LlmCall.Media.Request{
  modality: :image,
  model: "gpt-image-1",
  prompt: "a cat, watercolor"
}

{:ok, %LlmCall.Media.Response{assets: _assets}} =
  LlmCall.generate(client, media_request, codec: :images)

The client must declare :images — MyApp.OpenAI above declares only :chat, so this returns an error naming the codecs it does declare. The media section below shows a provider that declares the image codec.

Auth shapes: :none, :bearer, :x_api_key, {:header, name}, {module, function}, or {:sigv4, opts}. The key is always passed in; nothing reads the environment.

query: adds URL parameters to every request, for vendors that key on one — MiniMax's GroupId, Azure OpenAI's api-version. A codec's own parameter still wins on the same key, and the Responses WebSocket handshake gets them too. A query already written into base_url is folded into query: when the client is built, so pasting https://…/openai?api-version=2024-02-01 works.

defmodule MyApp.MiniMax do
  use LlmCall.Provider,
    base_url: "https://api.minimax.io",
    auth: :bearer,
    codecs: [video: LlmCall.Media.Dialect.MiniMax.Video]
end

minimax =
  MyApp.MiniMax.client(
    api_key: System.fetch_env!("MINIMAX_API_KEY"),
    query: %{"GroupId" => System.fetch_env!("MINIMAX_GROUP_ID")}
  )

The declaration only takes literals, so a value read at runtime belongs on client/1.

Streaming

openai = MyApp.OpenAI.client(api_key: System.fetch_env!("OPENAI_API_KEY"))

request = %LlmCall.Request{
  model: "gpt-4o",
  messages: [%LlmCall.Message{role: :user, content: [%LlmCall.Content.Text{text: "hi"}]}]
}

{:ok, stream} = LlmCall.stream(openai, %{request | stream: true})

stream
|> Stream.each(&IO.inspect({&1.type, &1.delta}))
|> Stream.run()

The library parses SSE and provider terminators. A failure while the body is being read raises LlmCall.HTTP.Error, whose error/1 returns the canonical %LlmCall.Error{} with the HTTP status; {:halt, acc} from a reducer closes the connection. complete/3 rejects stream: true rather than silently flipping it.

To observe events without owning the reduce, pass on_event::

{:ok, _stream} =
  LlmCall.stream(openai, request, on_event: &MyApp.Audit.stream_event/1)

It runs before the reducer, including for finish_stream/2 output; the return value is ignored, and it is not called after the reducer halts. LlmCall.HTTP is the only HTTP transport, so raw bytes are not exposed as a hook.

A reasoning block spans several events. The text arrives incrementally, and a provider that signs its thinking blocks sends the signature in its own event, with an empty text — Anthropic on every block, Gemini on the thought parts before a function call. Keep both when you fold the stream into an assistant turn, or the block cannot be replayed in the next request:

def merge(%LlmCall.Content.Thinking{} = block, %LlmCall.StreamDelta.Thinking{} = delta) do
  %{block | text: block.text <> delta.text, signature: delta.signature || block.signature}
end

Responses over WebSocket

The Responses protocol also has a multiplexed WebSocket connection: named stream_id lanes, decoded events, and reconnect before the 60-minute limit.

{:ok, connection} = LlmCall.Dialect.OpenAI.Responses.Connection.start_link(client: client)
{:ok, stream} = LlmCall.Dialect.OpenAI.Responses.Connection.create(connection, request, stream_id: "main")

Enum.to_list(stream)

An in-flight response cannot resume across a reconnect; its stream raises LlmCall.WS.Error. The connection reconnects with exponential backoff and does not stop on failure: while disconnected, create/3 returns a :transport error and Connection.reconnect/1 retries immediately. Connection.response_id/2 returns the provider id for previous_response_id.

Tool-call fragments are assembled into complete calls by a pure helper, which never runs them:

def assemble(events) do
  assembler = LlmCall.StreamAssembler.new(json_decoder: &JSON.decode/1)

  {_assembler, calls} =
    Enum.reduce(events, {assembler, []}, fn event, {acc, calls} ->
      {:ok, acc, new_calls} = LlmCall.StreamAssembler.feed(acc, event)
      {acc, calls ++ new_calls}
    end)

  calls
end

events is the stream's events in order (Enum.to_list/1), and the return value holds every tool call that completed. A stream that ends without a stop event — a truncated response, a provider that closes the lane — leaves a call pending, so LlmCall.StreamAssembler.finish/1 returns it before you act on the list.

Media generation

A completion can ask for image output; generated parts arrive in Response.content. Only a protocol that accepts modalities: [:text, :image] serves it — Gemini does, OpenAI Chat and Anthropic reject it:

defmodule MyApp.Gemini do
  use LlmCall.Provider,
    base_url: "https://generativelanguage.googleapis.com",
    auth: {:header, "x-goog-api-key"},
    codecs: [chat: LlmCall.Dialect.Gemini.GenerateContent]
end

gemini = MyApp.Gemini.client(api_key: System.fetch_env!("GEMINI_API_KEY"))

request = %LlmCall.Request{
  model: "gemini-2.5-flash-image",
  modalities: [:text, :image],
  messages: [%LlmCall.Message{role: :user, content: [%LlmCall.Content.Text{text: "a cat"}]}]
}

{:ok, _response} = LlmCall.complete(gemini, request)
# the response content may contain %LlmCall.Content.Image{}

Dedicated endpoints take a prompt and media parameters instead of messages:

defmodule MyApp.Images do
  use LlmCall.Provider,
    base_url: "https://api.openai.com",
    auth: :bearer,
    codecs: [images: LlmCall.Media.Dialect.OpenAI.Images]
end

images = MyApp.Images.client(api_key: System.fetch_env!("OPENAI_API_KEY"))

media = %LlmCall.Media.Request{
  modality: :image,
  model: "gpt-image-1",
  prompt: "a cat, watercolor",
  params: %{n: 2, size: "1024x1024"}
}

{:ok, %LlmCall.Media.Response{assets: _assets}} =
  LlmCall.generate(images, media, codec: :images)

Asynchronous video returns an %LlmCall.Operation{} whose next is the request to execute; poll/3 runs it and returns the next state:

video = %LlmCall.Media.Request{
  modality: :video,
  model: "MiniMax-Hailuo-02",
  prompt: "a cat walking on a beach"
}

{:ok, %LlmCall.Media.Response{operation: op}} = LlmCall.generate(minimax, video, codec: :video)
{:ok, %LlmCall.Operation{status: :completed} = _done} = LlmCall.poll(minimax, op, codec: :video)

next_kind: :poll means "execute next and poll"; next_kind: :asset means the body is media bytes — use LlmCall.fetch/2 for it. The library never polls, waits, or downloads on its own.

LlmCall.media_capabilities/3 reports what a codec accepts: max_n: :unsupported means no n, max_references is the reference count. A knob the codec cannot express is a validation error, never a silent drop.

Replaceable JSON layer

HTTP is Finch, one implementation. JSON is a module resolved at client-build time: the call option, the provider declaration, the compile-time application default, then Elixir's built-in JSON.

Layer Module Default
JSON LlmCall.JSON facade Elixir JSON
# config/config.exs of the host application
config :llm_call,
  json_library: Torque,
  capture_raw: :response,
  http_opts: [name: MyApp.Finch],
  timeout: 30_000

Torque, Jason and Poison expose tagged encode/1/decode/1; Elixir JSON exposes encode!/1/decode!/1. The LlmCall.JSON facade accepts either shape and normalizes it, so no adapter module is needed. json_library: is the single configuration key, matching Phoenix.

json_library and capture_raw are read with Application.compile_env/3; changing them requires recompiling the library. Per-client json_library:, capture_raw: (through LlmCall.Config.new/1) and provider declarations still override them without touching the compiled default. An explicit %LlmCall.Config{} uses the compiled default for both.

LlmCall.Application starts a Finch pool named LlmCall.Finch; pass http_opts: [name: MyPool] to use your own. If that name is already taken when :llm_call starts, the existing pool is used and no second one is started. http_opts accepts only :name, :pool_timeout, :request_timeout and :pool_strategy; timeout: is the read timeout, and receive_timeout in http_opts is rejected instead of ignored.

timeout: is Finch's :receive_timeout: each body chunk must arrive within it, not the whole call, so a large response on a slow link can outlive it. Add http_opts: [request_timeout: ...] when you want a wall-clock cap.

The default pool

The default pool is HTTP/2: count: 1, protocols: [:http2], plus a 30 s keep-alive PING. Every provider this library targets answers over h2, and it is the only protocol where one connection multiplexes — count: 1 carries as many concurrent requests as the server's max_concurrent_streams, where an HTTP/1 pool of size: 1 serialises them.

size is ignored on HTTP/2. If you want an HTTP/1 pool instead — a self-hosted gateway, an internal service — say so:

# config/runtime.exs
config :llm_call, pools: %{default: LlmCall.Application.h1_pool_opts()}

An HTTP/1 pool has no multiplexing, so size: 50 is a hard ceiling on concurrent requests per origin — and an LLM call holds its connection for seconds. Size it for your deployment:

config :llm_call,
  pools: %{default: [size: 200, count: 4, protocols: [:http1]]}

The map is handed to Finch.start_link/1 unchanged, so :protocols, :conn_opts, per-origin keys and the :http2 settings all work. It is read at boot, not at compile time — which is why this is a map and not one number: the two protocols count differently.

On an HTTP/1 pool, when every connection is checked out a request queues for :pool_timeout (Finch's default: 5 s) and then fails with reason: :pool_timeout, retryable?: true. That is local overload, not a provider failure: raise :size/:count, raise :pool_timeout, or shed load. Finch's HTTP/2 pool never reads :pool_timeout — it is a single multiplexing connection, so saturation shows up as one of the HTTP/2 reasons below instead.

HTTP/2

Nothing in the library knows which protocol the pool speaks — Finch decides from :protocols, so HTTP/2 is a pool setting and no code changes:

# config/runtime.exs
config :llm_call,
  pools: %{
    "https://api.deepseek.com" => [count: 1, protocols: [:http2]],
    default: [size: 50]
  }

A string key matches the request origin (scheme, host and port — a trailing slash is normalised away). :default is optional: an origin with no entry of its own falls back to it, and with no :default at all it falls back to Finch's built-in default (size: 50, count: 1, protocols: [:http1]). That fallback is easy to miss, so list :default explicitly when you are relying on it.

An HTTP/2 pool multiplexes: count: 1 carries as many concurrent requests as the server's max_concurrent_streams, where an HTTP/1 pool of size: 1 serialises them. Measured against a host that answers h2, eight concurrent calls took 1040–1081 ms over HTTP/1 (one at a time) and 142–160 ms over a single HTTP/2 connection. The numbers are wall time for unauthenticated requests — the payload is a 401 — so they measure the transport, not the provider.

A saturated or unusable HTTP/2 connection is reported with Finch's own reasons (:disconnected, :connection_closed, :pool_not_available, :connection_not_ready, and friends). All of them are retryable?: true: the connection dropped or has not been established yet, which a new attempt fixes.

protocols: [:http2] is HTTP/2 only — there is no ALPN fallback, so an HTTP/1 endpoint fails as a :transport error instead of degrading. [:http1, :http2] negotiates, but Finch documents that such a pool does not multiplex, so it is a compatibility setting, not an HTTP/2 one.

A DeepSeek example runs this way: an OpenAI-compatible endpoint that answers over HTTP/2.

Plaintext base URLs, and choosing a protocol

The library starts two pools and routes by scheme, which is what curl does:

base_url pool why
https:// LlmCall.Finch.HTTP2 ALPN negotiates h2; one connection multiplexes
http:// LlmCall.Finch.HTTP1 no ALPN, so HTTP/2 would be h2c prior knowledge

So http://localhost:11434 (Ollama) and https://api.openai.com both work with no configuration. The split matters because HTTP/2 over plaintext sends PRI * HTTP/2.0 to a server that is speaking HTTP/1 text.

A provider can override the choice with pool:, and any Finch pool option is accepted — the library's shape is the base and your keys win:

use LlmCall.Provider,
  base_url: "http://localhost:11434",
  auth: :none,
  codecs: [chat: LlmCall.Dialect.OpenAI.Chat],
  pool: :http1                                   # or :http2

use LlmCall.Provider,
  base_url: "https://api.example.com",
  auth: :bearer,
  codecs: [chat: LlmCall.Dialect.OpenAI.Chat],
  pool: [count: 4, http2: [ping_interval: 10_000]]

http_opts: [name: MyPool] still wins over all of it: a host that supervises its own pool keeps it.

Declared pool: options live as a per-origin entry on the shared instance, not in the application configuration. That has two consequences worth knowing:

One case cannot be detected: https:// against a host whose ALPN offers only http/1.1. Finch fixes a pool's module when it starts, so there is no per-connection negotiation; the request fails with reason: :pool_not_available after :pool_timeout. LlmCall.Protocol.downgrade/2 registers an HTTP/1 pool for that origin, once, when you know a backend is like that. It stops the origin's current pool to do so, which interrupts requests in flight on it.

Settings that suit streaming

An LLM call is not a REST call: the response is a stream that starts after the model thinks, gaps between tokens are normal, and a conversation sends one request every few seconds to a few minutes. Four Finch settings matter, and this library changes exactly one of them.

What it sets. An HTTP/2 pool gets http2: [ping_interval: 30_000] unless you say otherwise. An HTTP/2 pool is a single long-lived connection, so a load balancer or a NAT that drops it without a RST leaves a corpse that the next request discovers. Finch sends the PING only once the connection has been idle that long, and a write onto a dead socket moves the pool to :disconnected, so it reconnects before a request lands on it. An HTTP/1 pool is left alone: Finch already reconnects on a stale connection, which is why this is an HTTP/2-only default. Opt out with http2: [ping_interval: :infinity]; the value is exposed as LlmCall.Application.default_ping_interval/0.

What it already sets. timeout: defaults to 60 s and is Finch's :receive_timeout — the gap allowed between body chunks, not the whole call. That is what keeps a long stream alive: a 40-token-per-second answer is fine under it, and a provider that stalls for a minute is an error. Finch's own default is 15 s, which is short for a model that is thinking. Raise it for slow reasoning models; it is per-chunk, so a large value does not by itself let a call run forever.

What you should set.

What is left at Finch's default on purpose. size/count: capacity is a deployment's business, not a library's (see Pool size). size, count and protocols interplay is documented there.

Telemetry

Calls emit :telemetry events and attach no handler, so there is no cost until you subscribe. LlmCall.Telemetry documents the full shape.

Event Measurements
[:llm_call, :request, :start] system_time
[:llm_call, :request, :stop] duration, the reported token counts
[:llm_call, :request, :exception] duration
[:llm_call, :stream, :start] system_time
[:llm_call, :stream, :first_event] duration
[:llm_call, :stream, :first_text] duration
[:llm_call, :stream, :stop] duration
[:llm_call, :stream, :exception] duration

Every event carries operation, provider, codec and model; :stop adds the outcome (:ok / :error, or :done / :halted for a stream). The token counts are measurements, so they can be summed; a count the provider did not report is omitted rather than zeroed. Metadata never carries a header, a body or a message.

:first_event is time to the first event, :first_text time to the first visible token, so their difference is the provider's skeleton-frame overhead.

import Telemetry.Metrics

def llm_metrics do
  [
    summary("llm_call.request.stop.duration", unit: {:native, :millisecond}),
    sum("llm_call.request.stop.input_tokens"),
    sum("llm_call.request.stop.output_tokens"),
    counter("llm_call.request.stop.outcome", tags: [:outcome, :provider, :model])
  ]
end

execute/2 and fetch/2 emit nothing here: they are Finch requests, already covered by [:finch, :request, ...].

Tools

Request.tools takes a tool_call module, a {module, opts} pair, or a ready %LlmCall.ToolSpec{}; the three forms mix freely in one list. Naming the module is the short form — the schema is derived from its @spec and @doc, and projected into the selected codec's dialect:

defmodule MyApp.Tools.Weather do
  use ToolCall

  @doc """
  Get the forecast for a city.

  ## Parameters
    * `city` - city name
  """
  @spec get_weather(city :: String.t()) :: {:ok, %{temp: float()}}
  def get_weather(city), do: {:ok, %{temp: 21.5}}
end

messages = [%LlmCall.Message{role: :user, content: [%LlmCall.Content.Text{text: "weather in Oslo?"}]}]

{:ok, response} =
  LlmCall.complete(openai, %LlmCall.Request{
    model: "gpt-4o",
    messages: messages,
    tools: [MyApp.Tools.Weather]
  })

for call <- LlmCall.Response.tool_calls(response) do
  {:ok, _result} = ToolCall.run(MyApp.Tools.Weather, call.name, call.arguments)
  # build the %LlmCall.ToolResult{} and send the next request yourself
end

{MyApp.Tools.Weather, strict: true} asks for OpenAI's strict schema. Setting strict: false is treated as absent rather than sent as a flag, and a codec without a per-tool flag rejects true.

Approvals, audits and timeouts stay in tool_call, and the follow-up request stays with you: the library does not run an agent loop.

The projection follows the codec, so no per-provider step is left to the caller: the two OpenAI protocols get the schema ToolCall.emit/3 renders for OpenAI, Gemini the one rendered for Gemini, and any other protocol the neutral ToolCall.describe/2 schema. That is why Gemini needs no manual projection step, and a schema the protocol cannot express is a :validation error instead of a request the provider refuses — Gemini rejects a lowercase type, additionalProperties, $ref/$defs, prefixItems, oneOf, const, allOf or not.

Every entry point that forwards a request to a codec expands tools first: complete/3, stream/3, encode/3, validate_request/3, init_stream/3 and Responses.Connection.create/3. capabilities/3 reads no tools.

Pass a %LlmCall.ToolSpec{} when you already own a dialect-correct schema; LlmCall.Tools.expand/2 keeps it unchanged. Call expand/2 directly when you want the specs before the call:

{:ok, _specs} = LlmCall.Tools.expand([MyApp.Tools.Weather], LlmCall.Dialect.OpenAI.Chat)

What a decoded turn can be sent back as depends on the protocol: text and tool calls always, thinking blocks and Content.Raw only where the request shape allows it. docs/design.md §8.3 has the replay table, and LlmCall.Codec.Conformance.assert_replays/3 pins it for an adapter.

Provider-hosted tools (web search, grounding, server tools) are builtin tools whose name is the vendor's own identifier; the codec forwards them verbatim when it declares builtin_tools: :passthrough:

%LlmCall.ToolSpec{kind: :builtin, name: "web_search_20250305", provider_options: %{"max_uses" => 5}}

Dialect adapters

Five reference adapters — the dialect families the IR is written against:

Dialect Module
OpenAI Chat Completions LlmCall.Dialect.OpenAI.Chat
OpenAI Responses LlmCall.Dialect.OpenAI.Responses
Anthropic Messages LlmCall.Dialect.Anthropic.Messages
Gemini GenerateContent LlmCall.Dialect.Gemini.GenerateContent
Bedrock Converse LlmCall.Dialect.Bedrock.Converse

And four vendored media adapters, which ship with the library but are not part of the stable API surface (see LlmCall.Media):

Dialect Module
OpenAI Images LlmCall.Media.Dialect.OpenAI.Images
Gemini Imagen predict LlmCall.Media.Dialect.Gemini.Predict
Seedance (BytePlus ModelArk) LlmCall.Media.Dialect.Seedance.Video
MiniMax Hailuo LlmCall.Media.Dialect.MiniMax.Video

The library does not promise provider coverage. An adapter outside this repository is a module that uses LlmCall.Dialect.Adapter and supplies @path, @headers, a private body/2, and the protocol's own validate_request/2. A media adapter uses LlmCall.Media.Dialect.Adapter instead and implements encode_submit/2, decode_submit/2 and decode_error/2, plus decode_operation/2 when the codec is asynchronous — the macro injects validate_request/2 and there is no body/2. Share validation through LlmCall.Dialect.Helpers instead of reimplementing it. See CONTRIBUTING.md.

OpenAI-compatible endpoints (Groq, DeepSeek, Together, vLLM, Ollama's OpenAI surface, ...) use the OpenAI Chat codec with their own base URL and provider_options; their capabilities are not uniform.

Two levels

The one-call client is the default. The encode/decode functions stay available for callers that already own a transport:

{:ok, _encoded} = LlmCall.encode(LlmCall.Dialect.Anthropic.Messages, request)
# the struct carries `method`, `path` and `body`; `body` is already a map

body = %{"id" => "msg_1", "type" => "message", "content" => []}
{:ok, _response} = LlmCall.decode_response(LlmCall.Dialect.Anthropic.Messages, body)

Design

See docs/design.md for the canonical IR, the codec contract, the streaming model, the client, and the failure and compatibility policy. docs/roadmap.md records what each release shipped and the order in which further operation families (embeddings, rerank, speech, transcription) would arrive.

Adapters check themselves with LlmCall.Codec.Conformance or LlmCall.Media.Conformance (test support published from lib/, not a runtime dependency). The vendored media adapters run the media suite in this repository's own mix test.