Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 28 — LLM Integration & Agents

LLM inference doesn’t mean rewriting your application outside the BEAM. The winning architecture: BEAM orchestrates; a specialized runtime computes.

28.1 The Division of Labor

flowchart TD
    APP["Elixir Application"]
    APP --> PHX["Phoenix<br/>sessions · streaming UI"]
    APP --> OTP["OTP<br/>queues · supervision"]
    APP --> AI["AI calls"]
    PHX --> ADP["LLM Adapter"]
    OTP --> ADP
    AI --> ADP
    ADP --> RT["llama.cpp / vLLM / Ollama"]
    RT --> LLM["LLM"]

The BEAM handles (your existing strengths):

  • User sessions & authentication
  • Networking (HTTP, WebSocket, gRPC)
  • Streaming responses (chunked, SSE, WebSocket)
  • Rate limiting & quotas
  • Request queues & backpressure (GenStage)
  • Supervision & fault isolation
  • Distributed orchestration
  • Observability (telemetry, metrics, tracing)

The specialized runtime handles: model loading & quantization, tensor computation, token generation/sampling, KV cache management.

The BEAM doesn’t need to do every computation itself. It orchestrates specialized runtimes extremely well.

That thesis is Chapter 29’s subject, developed as the five-layer chain and the deployment consequences. This chapter is the concrete version: adapters, streaming, RAG, and an agent loop you can run today.

28.2 The Adapter Pattern

One interface, swappable transports (Port to llama.cpp binary, NIF into its library, HTTP to Ollama/vLLM/TGI, or local Nx/Bumblebee):

defmodule LLM do
  @type backend :: :port | :http | :nx

  def complete(prompt, opts \\ []) do
    case Keyword.get(opts, :backend, :http) do
      :http -> complete_http(prompt, opts)
      :port -> complete_port(prompt, opts)
      :nx   -> complete_nx(prompt, opts)
    end
  end

  defp complete_http(prompt, opts) do
    url = Keyword.get(opts, :url, "http://localhost:11434/api/generate")
    model = Keyword.get(opts, :model, "llama3")

    # Pass the map directly — Req encodes JSON for you.
    # (A classic bug is calling Jason.encode! here AND passing json:,
    #  which double-encodes into a JSON string body.)
    case Req.post(url, json: %{model: model, prompt: prompt, stream: false}) do
      {:ok, %{status: 200, body: %{"response" => response}}} ->
        {:ok, response}

      {:ok, %{status: status, body: body}} ->
        {:error, {:http_error, status, body}}

      {:error, reason} ->
        {:error, reason}
    end
  end

  defp complete_port(prompt, _opts) do
    # Port.open({:spawn_executable, "llama-cli"}, ...) → talk stdin/stdout
    {:ok, "port-based response for: #{prompt}"}
  end

  defp complete_nx(_prompt, _opts) do
    # Bumblebee.Text.generation serving started locally (Ch 20)
    {:ok, "nx-based response"}
  end
end

# Runnable against a local Ollama:
# LLM.complete("Explain OTP supervision in one sentence",
#   backend: :http, url: "http://localhost:11434/api/generate", model: "llama3")

This is the Erlang pattern you know — gen_server calling a Port/NIF — applied to LLM runtimes.

From a case Clause to a Behaviour

The case works until you need a second transport, tests without a network, or per-environment selection. The upgrade is the contract tool you know from -callback in Erlang — a behaviour plus adapters:

defmodule LLM.Provider do
  @callback complete(String.t(), keyword()) ::
              {:ok, String.t()} | {:error, term()}
end

defmodule LLM.Providers.Mock do
  @behaviour LLM.Provider

  @impl true
  def complete(prompt, _opts), do: {:ok, "echo: #{prompt}"}
end

An HTTP adapter wraps the Req code above; local inference wraps Nx.Serving (Ch 20). Selection becomes configuration, not code:

# config/test.exs — no sockets in CI
config :my_app, :llm_provider, LLM.Providers.Mock

# config/runtime.exs — real transport
config :my_app, :llm_provider, LLM.Providers.HTTP

defmodule LLM do
  def complete(prompt, opts \\ []) do
    default = Application.get_env(:my_app, :llm_provider, LLM.Providers.Mock)
    provider = Keyword.get(opts, :provider, default)
    provider.complete(prompt, opts)
  end
end

Forget a callback and the compiler warns — exactly as -behaviour does in Erlang. Same public API, open for extension without touching dispatch.

28.3 Streaming Into LiveView

Ollama streams NDJSON. With Req, into: :self makes the response body a lazy enumerable — a perfect fit. Two things to know about the modern Req shape: the body becomes a %Req.Response.Async{} struct (which implements Enumerable, so you iterate it rather than pattern-matching a “stream”), and into: :self delivers messages to the calling process, so consume it there or in a process that stays alive.

defmodule LLM.Stream do
  @spec stream_complete(String.t(), keyword()) :: Enumerable.t()
  def stream_complete(prompt, opts \\ []) do
    url = Keyword.get(opts, :url, "http://localhost:11434/api/generate")
    model = Keyword.get(opts, :model, "llama3")

    case Req.post(url,
           json: %{model: model, prompt: prompt, stream: true},
           into: :self
         ) do
      {:ok, %Req.Response{status: 200, body: body}} ->
        body
        |> to_chunks()
        # reassemble FIRST: TCP chunks are not lines (see LLM.Lines below)
        |> LLM.Lines.to_lines()
        |> Stream.map(&parse_ollama_line/1)
        |> Stream.reject(&(&1 == ""))

      {:ok, resp} ->
        [{:error, {:http_error, resp.status}}]

      {:error, reason} ->
        [{:error, reason}]
    end
  end

  # with into: :self the body is %Req.Response.Async{} — enumerable, and
  # each element is whatever Req hands over (bytes or already-decoded
  # chunks depending on the response content-type). Handle both:
  defp to_chunks(%Req.Response.Async{} = async), do: Enumerable.to_list(async)
  defp to_chunks(binary) when is_binary(binary), do: [binary]

  # A COMPLETE line looks like:
  # {"response":"Hel","done":false}
  defp parse_ollama_line(line) do
    case Jason.decode(line) do
      {:ok, %{"response" => text}} -> text
      _ -> ""
    end
  end
end

Two contract details this shape gets right, both of which are easy to get wrong:

  • stream_complete/2 returns an Enumerable.t(), not {:ok, stream}. An HTTP request either succeeds and yields a stream, or fails — there is no “stream plus an error tag” middle. Failures are elements in the stream ([{:error, reason}]), so a consumer can handle them mid-stream. Writing {:ok, stream} = LLM.Stream.stream_complete(msg) raises MatchError.
  • Reassemble before parsing. Decoding a raw TCP chunk with Jason.decode/1 fails for any chunk that ends mid-JSON, which is most of them — the partial pieces get silently dropped by parse_ollama_line’s catch-all and your output arrives with holes in it. LLM.Lines.to_lines/1 buffers the partial tail; only complete lines reach the parser.

Consuming it in a LiveView — note the stream is pulled, not assigned:

def handle_event("chat", %{"message" => msg}, socket) do
  owner = self()

  Task.start(fn ->
    LLM.Stream.stream_complete(msg)
    |> Enum.each(&send(owner, {:token, &1}))
  end)

  {:noreply, assign(socket, :response, "")}
end

def handle_info({:token, text}, socket) do
  # streams are the right tool for a growing list; plain append is fine here
  {:noreply, update(socket, :response, &(&1 <> text))}
end

Assigning the lazy Stream to the socket would work but never consume it — nothing pulls, so nothing renders.

Backpressure, Made Explicit

into: :self builds exactly the Stream.resource machine you would hand-roll around a socket: acquire the request, yield a chunk only when the consumer pulls, and run cleanup even when the consumer halts early. Slow rendering therefore pauses HTTP reads — demand flows upstream to the socket, exactly like GenStage demand.

One catch the convenience hides: TCP chunks are not lines, so NDJSON and SSE need reassembly across chunk boundaries — SSE just adds a "data: " prefix and a data: [DONE] sentinel:

defmodule LLM.Lines do
  # Raw chunks → complete lines; a partial tail stays buffered.
  def to_lines(chunks) do
    Stream.transform(chunks, "", fn chunk, buffer ->
      parts = String.split(buffer <> chunk, "\n")
      {Enum.drop(parts, -1), List.last(parts)}
    end)
  end
end

28.4 Production Patterns

PatternUse Case
Oban workersBackground jobs (summarization, embedding backfills)
GenStageBatch requests → one LLM call → fan out
NimblePoolBounded pool of Port/NIF connections to llama.cpp
FinchHTTP connection pools + adaptive limits — the current answer for HTTP, not poolboy
Phoenix ChannelsReal-time streaming to browsers
Nx.ServingBatched local inference for embeddings/classification

On poolboy: it filled a real gap and is now unmaintained. For Erlang migrators it is still the reflex, and for a pool of Port connections it works — but new code should use NimblePool, which is a small supervisor-friendly pool with built-in checkout timeouts. For HTTP specifically, do not hand-roll a pool at all: Finch owns the connections and already handles keepalive and per-host limits:

# in your supervision tree
{Finch, name: MyApp.Finch}

# in the adapter — no Req pool options to configure
Req.new(url: url, finch: [name: MyApp.Finch], json: payload)

Wrong vs Right: Fan-Out Shape

Batch-embedding 500 documents? The naive version opens 500 simultaneous requests — the BEAM shrugs; the provider answers with 429s:

# WRONG — unbounded: every task launches at once.
tasks = Enum.map(prompts, &Task.async(LLM, :complete, [&1]))
results = Enum.map(tasks, &Task.await(&1, 30_000))

# RIGHT — bounded window, per-task timeout, timeouts become values.
results =
  Task.async_stream(prompts, &LLM.complete/1,
    max_concurrency: 16,
    timeout: 30_000,
    on_timeout: :kill_task
  )
  |> Enum.map(fn
    {:ok, result} -> result
    {:exit, reason} -> {:error, reason}
  end)

max_concurrency + timeout: GenStage’s demand-based flow control in one option. (The underlying Task.async_stream failure semantics — laziness over tasks, the {:ok, _}/{:exit, _} contract — are Ch 05 §5.5.2; note max_concurrency bounds parallelism, not provider rate — a 429 still needs the retry policy below.)

Retry Policy: Idempotent, Transient, Deadline-Budgeted

ResponseAction
429Retry — honour Retry-After
500/502/503/504Retry — two or three attempts
400/401/403/404Never — fix the request

Req ships this: retry: :transient retries 5xx/429/timeouts with exponential backoff and jitter by default. Budget the total deadline, not just per attempt. Four guardrails worth bolting on early:

  • Don’t park a GenServer: route LLM calls through delayed replies (Task.start + GenServer.reply/2) — never block handle_call.
  • Rate limits: treat 429 + Retry-After as admission control; an ETS token bucket per user rejects before spend happens.
  • Costs: token spend is prompt-dominated — hoist static prefixes; ~4 characters/token is close enough for quota accounting.
  • Breaker + evaluation: fuse-style counting (N failures ⇒ fail fast for a cooldown, then probe); replay a golden set via Oban to gate every prompt change.

Zero-Shot Intent Routing: Classify Before You Generate

The cheapest request is the one that never needs generation. A zero-shot classifier routes utterances to handlers using labels that are data — no training run, no redeploy when the taxonomy changes:

{:ok, model_info} = Bumblebee.load_model({:hf, "facebook/bart-large-mnli"})
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "facebook/bart-large-mnli"})

labels = ["New booking", "Update booking", "Cancel booking", "Refund", "Complaint"]

serving = Bumblebee.Text.zero_shot_classification(model_info, tokenizer, labels)

Nx.Serving.run(serving, "I need a room with two beds for tomorrow")
#=> %{predictions: [%{label: "New booking", score: 0.92}, ...]}

Mechanically this is natural-language inference: the input becomes the premise, each label becomes a “This text is about {label}” hypothesis, and entailment scores are normalized across labels — one forward pass per label, ~400M params, no fine-tuning ever. Three integration rules:

  1. Gate on confidence — route argmax only above a calibrated threshold; below it, fall through to the LLM or a human queue.
  2. Labels are config — add "Flight status" by appending one string; version the label list like any interface contract.
  3. Compose with the agent loop (§28.7) — classification is the decider’s first stage: known intents dispatch straight to tools; open-ended text escalates to full generation.

Pair with Ch 20 §20.7’s MiniLM embeddings when routing needs semantic similarity rather than fixed labels — same serving pattern, vector outputs, brute-force ranking until pgvector earns its keep.

28.5 A Complete RAG Pipeline

Every step runs on the boundary discipline from Ch 18:

defmodule RAGPipeline do
  @doc """
  1. Embed query        (Nx + EXLA/EMLX — Ch 20 text_embedding)
  2. Vector search      (Postgres + pgvector / Redis)
  3. Retrieve docs      (Ecto — Ch 11)
  4. Generate answer    (LLM via Port/HTTP — this chapter)
  5. Stream to user     (Phoenix LiveView — Ch 10)
  """
  def query(question) do
    embedding = Embeddings.embed(question)

    chunks = VectorSearch.top_k(embedding, k: 5)

    context = Enum.map_join(chunks, "\n---\n", & &1.content)

    prompt = build_prompt(question, context)
    stream = LLM.Stream.stream_complete(prompt)

    stream
  end
end

Chunking Decides Retrieval Quality

Vectors cannot fix bad segmentation — chunk thoughtfully at ingest:

StrategyHowBest forWeakness
Fixed sizeN tokens + overlapuniform text, logscuts mid-sentence
Recursiveheading → para → sentencestructured docsseparators per format
Semanticsplit on embedding-distance jumpsprose, chat logsextra embedding passes

Default to fixed-with-overlap; go recursive for structured docs. Store doc_id + chunk_index beside each vector so answers can cite sources.

Rank Fusion Beats Score Fusion

Vector search misses exact tokens — error codes, function names — so run keyword search alongside it and merge the two ranked lists with reciprocal rank fusion: each document scores Σ 1/(k + rank) over every ranking it appears in (k ≈ 60). A dozen-line Enum.flat_map/2 + Enum.reduce/3 into a score map implements it. Ranks are comparable across retrievers where raw similarity scores are not, so consensus wins with zero score-calibration step.

28.6 The Agent Landscape

The BEAM’s primitives map onto agent requirements almost embarrassingly well:

Agent RequirementBEAM PrimitiveFramework Mapping
Persistent state per agentGenServerJido Agent, session state
Supervision & restartSupervisorJido Supervisor
Inter-agent messaging:gen_statem, PubSubJido Signal, LangChain callbacks
Distributed coordination:rpc, :pg, Phoenix.PubSubdistributed agent pools
Backpressure & flow controlGenStage, Broadwaystreaming pipelines

Jido — OTP-native autonomous agents

Agents are immutable state structs with a schema, running (when needed) inside supervised AgentServer processes — the same machinery Ch 14 walked through:

defmodule MyApp.Agents.Researcher do
  use Jido.Agent,
    name: "researcher",
    schema: [
      topic: [type: :string, required: true],
      findings: [type: {:list, :string}, default: []]
    ],
    signal_routes: [
      {"research", MyApp.Actions.Research}
    ]
end

children = [
  MyApp.Jido   # the `use Jido, otp_app:` runtime — start_agent children live here
]

{:ok, pid} = MyApp.Jido.start_agent(MyApp.Agents.Researcher, id: "r-1")
{:ok, agent} =
  Jido.AgentServer.call(pid,
    Jido.Signal.new!("research", %{topic: "BEAM agents"}, source: "/dashboard"))

LangChain Elixir — chains, tools, memory

LangChain for Elixir wires chat models, tool execution, and conversation state into a LLMChain value you drive step by step (LangChain.Chains.LLMChain.new!/1 plus add_message/2 and run/2). Reach for it when you want a ready-made chain/tool loop; reach for §28.7’s hand-rolled version when you want zero framework.

Instructor — structured output via Ecto schemas

defmodule ResearchResult do
  use Ecto.Schema
  @primary_key false
  embedded_schema do
    field :summary, :string
    field :key_points, {:array, :string}
    field :confidence, :float
  end
end

{:ok, %ResearchResult{} = result} =
  Instructor.chat_completion(
    model: "gpt-4o",
    response_model: ResearchResult,
    messages: [%{role: "user", content: "Summarize the BEAM ecosystem"}],
    max_retries: 3
  )

ReqLLM / LlmComposer

  • ReqLLM — unified HTTP clients (OpenAI, Anthropic, Ollama, Mistral) with streaming + retries over Req.
  • LlmComposer — declare workflows as data (steps, parallel branches, loops), compile to executable graphs.

28.7 Minimal Multi-Agent Demo (Pure OTP)

You can build real multi-agent systems with nothing but GenServers:

defmodule ResearchAgent do
  use GenServer
  def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
  def research(topic), do: GenServer.call(__MODULE__, {:research, topic})

  @impl true
  def handle_call({:research, topic}, _from, state) do
    summary = "Summary of #{topic}"       # ← replace with LLM adapter call
    {:reply, summary, state}
  end
end

defmodule WritingAgent do
  use GenServer
  def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
  def write(summary), do: GenServer.call(__MODULE__, {:write, summary})

  @impl true
  def handle_call({:write, summary}, _from, state) do
    article = "Article based on: #{summary}"
    {:reply, article, state}
  end
end

Supervisor.start_link([ResearchAgent, WritingAgent], strategy: :one_for_one)

summary = ResearchAgent.research("Elixir agents")
article = WritingAgent.write(summary)

Each agent is supervised, observable (:sys.get_state), and distributable.

The BEAM is not just a runtime for agents — it is the agent architecture itself.

The Tool-Call Loop as a gen_statem

An agent that plans → calls tools → observes → repeats is a state machine, and you already own the right primitive. Injected funs stand in for the LLM adapter, keeping the loop pure and testable:

defmodule AgentLoop do
  @behaviour :gen_statem

  def start_link(opts), do: :gen_statem.start_link(__MODULE__, opts, [])

  @impl true
  def callback_mode, do: :state_functions

  @impl true
  def init(opts) do
    data = %{question: Keyword.fetch!(opts, :question),
             decider: Keyword.fetch!(opts, :decider),
             executor: Keyword.fetch!(opts, :executor),
             turn: 0, max: Keyword.get(opts, :max_turns, 5), answer: nil}

    {:ok, :thinking, data, [{:next_event, :internal, :step}]}
  end

  # one model turn per :step event; the cap bounds spend
  def thinking(:internal, :step, %{turn: t, max: m} = d) when t >= m do
    {:next_state, :failed, d, []}
  end

  def thinking(:internal, :step, d) do
    case d.decider.(d.question, d.turn) do
      %{tool_calls: [], answer: answer} ->
        {:next_state, :done, %{d | answer: answer}, []}

      %{tool_calls: calls} ->
        {:keep_state, %{d | turn: d.turn + 1},
         [{:next_event, :internal, {:exec, calls}}]}
    end
  end

  def thinking(:internal, {:exec, calls}, d) do
    _results = d.executor.(calls)   # append results to the transcript here
    {:keep_state_and_data, [{:next_event, :internal, :step}]}
  end

  # terminal states absorb stragglers; inspect via :sys.get_state/1
  def done(_e, _c, _d), do: :keep_state_and_data
  def failed(_e, _c, _d), do: :keep_state_and_data
end

Drive it with a decider that returns tool calls until it returns %{tool_calls: [], answer: ...}; {state, data} = :sys.get_state(pid) then shows :done plus the answer. The cap bounds cost, supervision restarts a wedged loop, and :sys traces every transition.

Explore More

  • Req docs — streaming responses (into: :self), retries, and step instrumentation
  • Instructor — structured outputs via Ecto schemas with automatic retry/validation (§28.6)
  • Jido — OTP-native agent framework; read its supervision strategy against §28.7’s hand-rolled version
  • pgvector — the Postgres side of the RAG pipeline; pair with Ch 11’s Ecto knowledge
  • Exercise idea: extend §28.5’s RAGPipeline with real pgvector retrieval — embed documents at write time with an Oban worker, query-time top-k in Ecto, stream answers through a LiveView
  • Practice Lab: Lab 6 — Bumblebee Semantic Search — the retrieval/re-ranking half of this chapter’s RAG pipeline, built on an all-new support-desk example

Checkpoint

  1. Which BEAM primitive gives each agent isolated persistent state?
  2. Name three transports an LLM adapter can hide behind.
  3. In RAG, which steps are numerical vs data vs web?
Answers
  1. GenServer.
  2. Port (external binary), NIF (in-process library), HTTP (Ollama/vLLM/API), plus local Nx/Bumblebee.
  3. Numerical: embedding + generation; Data: vector search/retrieval; Web: LiveView streaming to the user.

Next: Chapter 29 — Architecture Philosophy