LlmCore includes an in-process agentic tool-calling loop that runs entirely inside the BEAM VM — no subprocess, no CLI overhead.

Overview

The agent loop implements the standard agentic pattern:

┌──────────────────────────────────────────┐
│           LlmCore.Agent.Loop             │
│                                          │
│  1. Call LLM with messages + tools       │
│  2. LLM responds with tool calls?        │
│     YES → dispatch tools, collect results │
│            append to messages → goto 1    │
│     NO  → return final text response     │
│                                          │
│  [Iteration Pipeline processes each turn] │
└──────────────────────────────────────────┘

The loop is transport-agnostic — it doesn't know about HTTP, CLIs, or specific providers. It calls a user-supplied llm_send_fn and a resolve_tool function. This makes it work with any LLM backend.

Basic Usage

alias LlmCore.Agent.Loop

# Define your LLM send function
llm_send = fn messages, opts ->
  LlmCore.LLM.Provider.dispatch(LlmCore.LLM.Anthropic, messages, opts)
end

# Define your tool resolver
resolve_tool = fn tool_call ->
  case tool_call.function_name do
    "search" -> {:ok, "search results..."}
    "calculate" -> {:ok, "42"}
    _ -> {:error, "unknown tool"}
  end
end

# Run the loop
{:ok, final_response, messages} =
  Loop.run(
    [%{role: :user, content: "What is 6 × 7?"}],
    llm_send,
    tools: [
      %LlmToolkit.Tool{
        name: "calculate",
        description: "Evaluate a mathematical expression",
        parameters: %{type: "object", properties: %{expr: %{type: "string"}}}
      }
    ],
    resolve_tool: resolve_tool,
    max_iterations: 10
  )

final_response.content
#=> "6 × 7 = 42"

Options

OptionRequiredDefaultDescription
:toolsYes—List of LlmToolkit.Tool.t() definitions
:resolve_toolYes—fn(Call.t()) -> {:ok, String.t()} | {:error, String.t()}
:resolver_moduleNonilModule implementing ToolResolver behaviour for dispatch recipes
:tool_timeoutNo:infinityMaximum time in ms for one tool dispatch, including all recipe sub-calls. With no value there is no deadline. A finite timeout returns a bounded Tool call timed out after Nms result carrying the configured budget.
:terminal_toolNonilTool name that stops the loop when called. The call is not dispatched — its raw arguments land on response.metadata.terminal_args and the full call on response.metadata.terminal_tool_call. Sibling tool calls in the same response are dispatched first and their transcript is appended to the final messages. Useful for letting the model select a structured result (e.g. citations) as its final turn.
:terminal_requiredNofalseWith :terminal_tool: a no-tool-call response with prose does not end the loop. The prose is appended as an assistant message, :terminal_nudge follows as a user message, and the turn is retried. Narrated stops are budgeted per run by :max_nonterminal_stops. Exhausting that budget, or the iteration budget before the terminal tool is called, returns {:error, {:terminal_missing, details}} with the last prose, so the caller chooses how to degrade. A completion that needed retries carries response.metadata.terminal_recovery_attempts.
:terminal_nudgeNonames the toolUser-message text for the non-terminal retry.
:terminal_content_keyNonilArgument of the terminal call whose string value becomes response.content; the model's own prose, if any, is kept under response.metadata.terminal_prose. A blank or missing argument leaves the content untouched; a present non-string value is logged at warning level and leaves it untouched.
:max_nonterminal_stopsNo3Narrated stops tolerated per run under :terminal_required.
:max_blank_stopsNo3Consecutive blank stops (no tool calls, blank content) tolerated per iteration before {:error, {:empty_stop, details}}. Retries do not consume iterations.
:blank_stop_nudgeNonilOptional user-message text appended before a blank-stop retry.
:max_iterationsNo10Hard iteration ceiling
:on_iterationNonilCallback fn(Context.t()) -> :ok invoked after each iteration
:pipeline_optsNo[sync: true]Options forwarded to the ALF pipeline
:llm_optsNo[]Extra options forwarded to llm_send_fn

Return Values

ResultMeaning
{:ok, response, messages}LLM produced a text-only response. response is LlmCore.LLM.Response.t(), messages is the full conversation history.
{:error, :max_iterations_reached}Iteration budget exhausted without a text-only response.
{:error, :budget_exceeded}BudgetGuard refused to dispatch tools on the last allowed iteration.
{:error, {:empty_stop, details}}Repeated blank stops; details carries iteration, attempts, finish_reasons, provider, model.
{:error, {:terminal_missing, details}}Under :terminal_required, the terminal tool was never called: narrated stops exhausted the run budget, or the iteration budget ran out (reason: :max_iterations); details adds last_content (the full prose, unbounded — truncate before logging) and terminal_tool.
{:error, {:circuit_breaker, msg}}Same tool error repeated 3+ times — systematic bug, not transient.
{:error, {:llm_error, reason}}The llm_send_fn returned an error.
{:error, {:pipeline_error, reason}}The ALF iteration pipeline crashed.

Iteration Pipeline

Each iteration flows through LlmCore.Agent.Pipeline.Iteration, an ALF pipeline with these stages:

parse_tool_calls       — Extract tool calls from the LLM response
     ↓
validate_calls         — Check calls against tool definitions
     ↓
loop_decision          — Text-only? → :done. Tool calls? → :continue
     ↓
dispatch_tools         — Execute tool calls (serial at the top level; recipe
                          sub-tools fan out concurrently through ToolDispatch)
     ↓
inject_results         — Build tool result messages
     ↓
budget_guard           — Check iteration budget

The pipeline produces a LlmCore.Agent.Context with a decision field that the outer loop reads.

Context Struct

LlmCore.Agent.Context carries data through the pipeline:

  • Input fields (set by the loop): messages, tools, response, resolve_tool, iteration, max_iterations
  • Intermediate fields (populated by stages): tool_calls, tool_results, result_messages, validation_errors
  • Output fields (read by the loop): decision, status, error, trace

Circuit Breaker

The loop detects when the same tool error repeats 3+ consecutive times. This indicates a systematic bug (wrong arguments, missing resource) rather than a transient failure — the model can't fix it by varying arguments. The loop breaks out with {:error, {:circuit_breaker, msg}}.

Telemetry

The loop emits these events:

[:llm_core, :agent, :loop_iteration]          # per iteration
[:llm_core, :agent, :tool_call, :start | :stop]
[:llm_core, :agent, :complete]                # loop exit

The completion event carries %{total_iterations: N} with metadata %{tool_calls_count: N}. Recipe sub-calls additionally emit [:llm_core, :tool_dispatch, :sub_call, :start].

Tool dispatch timeout

Recipe-backed tool calls run on the shared async ToolDispatch pipeline. DispatchTools passes the caller's :tool_timeout as the per-call ALF timeout. The default is :infinity, which means no deadline and prevents ALF's 10 s default from cutting long calls. A finite timeout is enforced around each sub-call and returns the typed reason {:timeout, configured_ms}; the loop surfaces it as Tool call timed out after Nms. A genuine timeout is never retried through the direct-execution fallback; that fallback is only for a pipeline that cannot be started, and it applies the same finite budget when one is set.

Timeout handling is all-or-nothing across a fan-out. When a finite :tool_timeout expires for one call in a fan-out, the whole tool step reports the timeout; successful sibling results are not returned. Callers never receive a partially composed result from a timed-out step.

Integration Example

A real-world consumer uses the agent loop for conversational LLM calls that need tool access:

# From a consumer adapter
# (resolves provider, wraps LlmCore.LLM.Provider.dispatch/3 as the send function)
defp send_via_agent_loop(messages, opts, tools, resolve_tool) do
  {:ok, provider, call_opts} = resolve_provider(opts)

  llm_send_fn = fn loop_messages, loop_opts ->
    LlmCore.LLM.Provider.dispatch(provider, loop_messages, Keyword.merge(call_opts, loop_opts))
  end

  case LlmCore.Agent.Loop.run(messages, llm_send_fn,
         tools: tools,
         resolve_tool: resolve_tool,
         max_iterations: 5
       ) do
    {:ok, response, _final_messages} ->
      {:ok, response.content || "", response.usage || %{}}
    {:error, reason} ->
      {:error, reason}
  end
end

This pattern — resolve a provider, build a send function, pass it to the loop — is the recommended integration path for any application that needs tool-calling LLM interactions.