Skip to content

About

Elixir-native LangChain, LangGraph, and DeepAgents for traceable LLM apps: OTP workflows, tools, memory, human-in-the-loop, streaming, custom clients/adapters, minimal deps, and WeaveScope tracing.

Topics

Resources

Stars

65 stars

Watchers

1 watching

Forks

Repository files navigation

BeamWeaver

ci Hex.pm HexDocs License

Production AI agents and durable workflows for Elixir & OTP.

BeamWeaver goes beyond basic chat wrappers and linear tool loops. In one Elixir-native library, you get declarative agents, typed tools, structured output, stateful graph workflows, Ecto-backed durable checkpointing, human-in-the-loop approvals, composable middleware, deep-agent workspaces, deterministic testing, and end-to-end tracing—with no Python sidecar and no hosted control plane.

Add {:beam_weaver, "~> 1.0"} to deps in mix.exs (Elixir 1.19+) and see Installation for provider credentials and formatter setup.

Why BeamWeaver?

Wiring a single prompt and tool loop is easy. Shipping AI features in production means handling multi-step workflows, crash recovery, human approvals, cost and PII guardrails, context limits, multi-agent delegation, and deterministic CI tests—without hand-rolling Ecto state machines, resume logic, and custom mocks.

BeamWeaver ships the full agent and workflow runtime on one execution engine, built for OTP supervision, Ecto, and :telemetry:

Capability What you get out of the box
Declarative DSLs & runtime builders Agent, Tool, Schema, and Middleware modules with compile-time argument validation, defaults, structured output with automatic retries, and trusted injected caller context invisible to the model—plus BeamWeaver.Agent.build/1 and BeamWeaver.Core.Tool.from_function!/1 for dynamic setups
Explicit state graphs Built-in Graph DSL with parallel fan-out, join, map-reduce Send, guarded edges, bounded loops, agents-as-subgraphs, static validation (BeamWeaver.Graph.validation_report/2), and Mermaid/ASCII rendering
Durable checkpoints & time travel Checkpoint.Ecto (PostgreSQL & SQLite) and Checkpoint.ETS with versioned BeamWeaver.Migrations, partial-failure recovery without rerunning completed steps, thread inspection, replay, and state forking
Human-in-the-loop (HITL) Declarative interrupt_on (batch or per-call), durable pauses across restarts, and :approve / :edit / :reject / :respond decisions via resume_review/2—propagating automatically through nested subagents
Middleware & guardrails Composable hook pipeline with built-ins for ModelRetry, cross-provider ModelFallback, call limits, PII (including live stream redaction), OpenAIModeration, AutoMode, ContextEditing, Summarization, and OverflowRecovery
Deep agents & workspaces Filesystem backends with symlink-aware permissions, Sandbox.Docker and Sandbox.Local with strict ShellPolicy, TodoList, on-demand skills, memory files, and sync/async subagents
Memory & retrieval Cross-thread namespaced Memory.Ecto / Memory.ETS with TTL, text splitters, embeddings, and VectorStore.EctoPostgres (pgvector)
Deterministic testing Built-in "fake:chat" with multi-turn tool scripts, parent: self() call assertions, deterministic streaming, ToolEmulator, "fake:embedding", and YAML HTTP Transport.Replay cassettes
Observability & tracing Hierarchical local trace trees, automatic credential redaction, model-profile cost estimates, :telemetry, and background export to WeaveScope
Strict provider contracts Checked-in model capability profiles that reject unsupported parameters locally before hitting the wire, with one normalized set of Core.Error types across every provider

Built for Elixir & OTP

  • Fits your existing supervision tree: No Python runtime, no external orchestrator, and no forced GenServer wrappers around your agents. Run agents and graphs under your own Task.Supervisor, Oban workers, or Phoenix LiveViews—stream_events/2 with live: true cancels cleanly when the consumer exits.
  • Your Ecto repo, your database: Checkpoint.Ecto (PostgreSQL and SQLite), Memory.Ecto, Cache.Ecto, and VectorStore.EctoPostgres (pgvector) share your supervised Ecto.Repo via versioned BeamWeaver.Migrations, with process-owned ETS adapters for fast local and ephemeral runs.
  • Strict provider contracts and normalized errors: Checked-in model profiles catch unsupported parameters before sending an HTTP request, and every provider maps failures to one consistent set of BeamWeaver.Core.Error types (:rate_limit, :authentication, :timeout, :server_error, and more).
  • Security by default: Credentials are hidden from inspect/1, traces, and crash logs; trusted caller context: stays outside model-visible tool schemas; Sandbox and ShellPolicy start from a minimal environment so host API keys do not leak to shell commands; Filesystem.Permission rules see through symlinks; and TextSplitter.split_url/3 blocks SSRF to private networks.

Your first agent

Follow Installation to configure OpenAI, then define a typed tool and agent module under lib/my_app/ and run the call in iex -S mix. Notice how injected :context, :context passes the trusted customer_id under an atom key without exposing it in the model-visible schema:

defmodule MyApp.OrderStatus do
  use BeamWeaver.Tool

  name "order_status"
  description "Look up the shipping status for the authenticated customer's order."
  injected :context, :context

  schema do
    field :order_id, :string, description: "Order ID, for example A-1001"
  end

  @impl true
  def invoke(_tool, %{"order_id" => order_id, context: %{customer_id: customer_id}}, _opts) do
    orders = %{{"cus_ada", "A-1001"} => %{status: "shipped", delivery_day: "Thursday"}}

    case Map.fetch(orders, {customer_id, order_id}) do
      {:ok, order} -> {:ok, Map.put(order, :order_id, order_id)}
      :error -> {:error, "Order not found for this customer"}
    end
  end
end

defmodule MyApp.SupportAgent do
  use BeamWeaver.Agent

  model "openai:gpt-5.4-mini", max_tokens: 512, timeout: 60_000
  system_prompt "Always call order_status for order questions. Answer briefly using its result."
  tools [MyApp.OrderStatus]

  context_schema do
    field :customer_id, :string, required: true
  end

  middleware [
    {BeamWeaver.Agent.Middleware.ModelRetry, max_retries: 2}
  ]

  validate_tools true
  recursion_limit 10
  run_timeout 60_000
end

{:ok, result} =
  MyApp.SupportAgent.invoke(
    %{messages: ["When will order A-1001 arrive?"]},
    context: %{customer_id: "cus_ada"}
  )

tool_result = Enum.find(result.messages, &(&1.role == :tool and &1.name == "order_status"))
true = tool_result != nil and BeamWeaver.Core.Message.text(tool_result) =~ "Thursday"
answer = result.messages |> List.last() |> BeamWeaver.Core.Message.text()
true = is_binary(answer) and byte_size(answer) > 0
IO.puts(answer)

Need a dynamic agent or tool at runtime? Use BeamWeaver.Agent.build/1 and BeamWeaver.Core.Tool.from_function!/1. Start with the Quickstart (including a Google Gemini alternative), walk through Build a Support Agent, or read How BeamWeaver Works.

Durable workflows with the Graph DSL

Use an agent when the model should choose the next action. Use BeamWeaver.Graph when your application owns the workflow—parallel branches, joins, bounded loops, map-reduce fan-out, and crash recovery.

This self-contained workflow needs no API key. Two checks run in parallel and checkpoint their results; when :notify fails, continuing the thread resumes from :notify without rerunning the completed checks:

defmodule MyApp.OrderWorkflow do
  use BeamWeaver.Graph

  graph do
    state do
      channel :checks, merge: :map
      channel :log, merge: :list
    end

    node :inventory, fn %{order_id: id} -> %{checks: %{in_stock: true}, log: ["checked #{id}"]} end
    node :fraud, fn %{amount: amount} -> %{checks: %{low_risk: amount <= 500}, log: ["scored risk"]} end
    node :notify, &__MODULE__.notify/2

    edge start(), :inventory
    edge start(), :fraud
    join [:inventory, :fraud], :notify
    edge :notify, finish()
  end

  def notify(%{checks: %{in_stock: true, low_risk: true}}, runtime) do
    if runtime.context.mail_available do
      %{status: :confirmed, log: ["notified customer"]}
    else
      {:error, BeamWeaver.Core.Error.new(:mail_unavailable, "Notification service unavailable")}
    end
  end
end

saver = BeamWeaver.Checkpoint.ETS.new()
opts = [checkpointer: saver, config: %{"configurable" => %{"thread_id" => "order-A-1001"}}]

# Parallel branches finish and checkpoint; :notify fails before completing.
{:error, %{type: :mail_unavailable}} =
  MyApp.OrderWorkflow.invoke(%{order_id: "A-1001", amount: 120}, [context: %{mail_available: false}] ++ opts)

{:ok, snapshot} = MyApp.OrderWorkflow.get_state(opts)
["notify"] = snapshot.next

# Continue the thread: completed branches do not rerun.
{:ok, recovered} = MyApp.OrderWorkflow.invoke(%{}, [context: %{mail_available: true}] ++ opts)
:confirmed = recovered.status
["checked A-1001", "notified customer", "scored risk"] = Enum.sort(recovered.log)

Swap Checkpoint.ETS for Checkpoint.Ecto.new(repo: MyApp.Repo) (PostgreSQL or SQLite) to recover across restarts, embed BeamWeaver.Agent modules directly as graph nodes, inspect topology with Compiled.draw_mermaid/2, or replay and fork earlier checkpoints. See Graphs, Checkpoints, and Durable Execution.

Human-in-the-loop and deterministic testing

Pause high-risk tools before they execute with interrupt_on, inspect the exact arguments the model proposed, and resume with :approve, :edit, :reject, or :respond.

In tests, swap the model for "fake:chat" to exercise the entire tool loop, approval flow, retries, and state transitions in milliseconds without API keys or flaky mocks:

defmodule MyApp.IssueRefund do
  use BeamWeaver.Tool

  name "issue_refund"
  description "Issue a customer refund."
  injected :context, :context

  schema do
    field :order_id, :string
    field :amount, :number
  end

  @impl true
  def invoke(_tool, %{"order_id" => order_id, "amount" => amount, context: %{observer: pid}}, _opts) do
    send(pid, {:refund_issued, order_id, amount})
    {:ok, %{order_id: order_id, amount: amount, status: "refunded"}}
  end
end

defmodule MyApp.RefundAgent do
  use BeamWeaver.Agent
  alias BeamWeaver.Models.FakeChatModel

  model "fake:chat",
    responses: [
      FakeChatModel.tool_call("issue_refund", %{"order_id" => "A-1001", "amount" => 25}),
      "Refund for A-1001 completed."
    ]

  tools [MyApp.IssueRefund]
  interrupt_on %{"issue_refund" => true}
end

alias BeamWeaver.Agent.HITL

saver = BeamWeaver.Checkpoint.ETS.new()
opts = [checkpointer: saver, config: %{"configurable" => %{"thread_id" => "refund-A-1001"}}, context: %{observer: self()}]

# The run pauses before issue_refund executes; inspect the proposed arguments.
{:interrupted, interrupt} = MyApp.RefundAgent.invoke(%{messages: ["Refund $25 for order A-1001."]}, opts)

{:ok, %{action_requests: [%{name: "issue_refund", args: %{"order_id" => "A-1001", "amount" => 25}}]}} =
  HITL.from_interrupt(interrupt)

receive do
  {:refund_issued, _, _} -> raise "Refund executed before approval"
after
  0 -> :ok
end

# Approve (or :edit, :reject, :respond) and resume the checkpointed run.
{:ok, completed} = MyApp.RefundAgent.resume_review([HITL.decision(:approve)], opts)

receive do
  {:refund_issued, "A-1001", 25} -> :ok
after
  1_000 -> raise "Expected approved refund to run"
end

"Refund for A-1001 completed." = completed.messages |> List.last() |> BeamWeaver.Core.Message.text()

For deeper test coverage, "fake:chat" supports parent: self() call assertions and deterministic token streaming, ToolEmulator safely stubs side-effecting tools, and BeamWeaver.Transport.Replay tests real provider encoding and decoding against YAML cassettes. See Human Review and Testing.

Debug and monitor agents with WeaveScope

Find the tool that stalled or the model call that drove up cost. BeamWeaver records local hierarchical trace trees (BeamWeaver.Tracing) out of the box, and WeaveScope renders each agent run as a trace tree or waterfall. Open any step to inspect its inputs, outputs, and timing, and track p95 latency, error rates, token usage, and estimated cost across runs.

BeamWeaver's built-in exporter sends traces in the background once you configure an endpoint and API key. Explore WeaveScope · Set up trace export

WeaveScope tracing view

Providers

Built-in adapters cover OpenAI (Responses, Chat Completions, Embeddings, Images, Decisions), Anthropic, Google Gemini (including Decisions and Gemini 4 long-decode continuation), xAI, DeepSeek, Moonshot (Kimi), SubQ (chat and Decisions), Z.ai, and TypeSafe (typed Decisions).

Need a local or third-party OpenAI-compatible server, or a custom provider? Use BeamWeaver.OpenAI.chat_completions_model/1 or register a custom BeamWeaver.Provider.Adapter. The provider guides and Models explain capability profiles, reasoning effort, cost estimates, and cross-provider fallbacks.

Learn, extend and operate

Capability Guide
Declare agents, typed tools and structured answers Agents, Tools, Structured Output
Stream tokens and tool progress (incl. LiveView) Streaming, Runtime Context
Keep conversation history and cross-thread memory Short-Term Memory, Long-Term Memory
Review actions before they run and enforce guardrails Human-in-the-Loop, Guardrails
Add filesystems, sandboxes, planning, skills and subagents Deep Agents, Filesystem, Sandboxes, Subagents
Control workflow steps, branches, joins and subgraphs Graphs, Workflow Patterns, Subgraphs
Persist checkpoints, time-travel and recover interrupted work Storage, Checkpoints, Durable Execution
Search documents with embeddings and pgvector Retrieval
Apply retries, fallbacks, limits, caching and compaction Built-in Middleware, Context Management
Test offline and operate in production Testing, Tracing, Going to Production

Documentation and examples

When contributing to BeamWeaver, run mix test for deterministic checks and mix docs.verify --all for isolated documentation execution, including required live providers and services. The verification report identifies failures and unmet prerequisites; compilation alone is not reported as executed coverage.

Apache-2.0. See LICENSE.

About

Elixir-native LangChain, LangGraph, and DeepAgents for traceable LLM apps: OTP workflows, tools, memory, human-in-the-loop, streaming, custom clients/adapters, minimal deps, and WeaveScope tracing.

Topics

Resources

Stars

65 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages