# `LlmCore.Agent.Loop`
[🔗](https://github.com/fosferon/llm_core/blob/v0.9.7/lib/llm_core/agent/loop.ex#L1)

Agentic tool-calling loop.

Iterates: call LLM → feed response through the iteration pipeline →
if the pipeline says `:continue`, append messages and call the LLM again;
if `:done`, return the final response.

A no-tool-call response with blank content (`:blank_stop`) is never
accepted as completion. The loop retries the turn under a separately
bounded recovery policy (`:max_blank_stops`) and terminates with a
typed `{:empty_stop, details}` error when blanks repeat.

With `:terminal_tool` and `:terminal_required`, a no-tool-call response
with prose (`:nonterminal_stop`) is not accepted either: the model's prose
is appended as an assistant message, a nudge follows as a user message,
and the turn is retried. Narrated stops are budgeted per RUN
(`:max_nonterminal_stops`), so a model that narrates, is nudged into one
tool call and narrates again cannot reset the budget. Exhaustion — of that
budget or of the iteration budget while the terminal tool was never called
— terminates with the typed `{:terminal_missing, details}` error carrying
the last prose, so the caller decides how to degrade.

The loop owns iteration control and message accumulation. The pipeline
(`LlmCore.Agent.Pipeline.Iteration`) owns per-iteration processing logic.

## Usage

    {:ok, response, messages} =
      LlmCore.Agent.Loop.run(
        [%{role: :user, content: "Research Elixir ALF"}],
        &my_llm_send/2,
        tools: my_tools,
        resolve_tool: &MyResolver.resolve/1,
        max_iterations: 10
      )

# `llm_send_fn`

```elixir
@type llm_send_fn() :: ([map()], keyword() -&gt;
                    {:ok, LlmCore.LLM.Response.t()} | {:error, term()})
```

# `opts`

```elixir
@type opts() :: [
  tools: [LlmToolkit.Tool.t()],
  resolve_tool: (LlmToolkit.Tool.Call.t() -&gt;
                   {:ok, String.t()} | {:error, String.t()}),
  resolver_module: module() | nil,
  tool_timeout: pos_integer() | :infinity,
  max_iterations: pos_integer(),
  on_iteration: (LlmCore.Agent.Context.t() -&gt; :ok) | nil,
  pipeline_opts: keyword(),
  llm_opts: keyword(),
  terminal_tool: String.t() | nil,
  terminal_required: boolean(),
  terminal_nudge: String.t() | nil,
  terminal_content_key: String.t() | nil,
  max_nonterminal_stops: pos_integer(),
  max_blank_stops: pos_integer(),
  blank_stop_nudge: String.t() | nil
]
```

# `run`

```elixir
@spec run([map()], llm_send_fn(), opts()) ::
  {:ok, LlmCore.LLM.Response.t(), [map()]} | {:error, term()}
```

Runs the agentic loop.

Calls `llm_send_fn` with the current messages and tool definitions.
If the LLM responds with tool calls, the response flows through the
iteration pipeline which dispatches tools, collects results, and
builds new messages. The loop repeats until the LLM produces a text-only
response or the iteration budget is exhausted.

## Parameters

  * `messages` — Initial message list (system prompt, history, user message)
  * `llm_send_fn` — `fn(messages, opts) -> {:ok, Response.t()} | {:error, term()}`
  * `opts` — Configuration keyword list:
    * `:tools` — (required) list of `LlmToolkit.Tool.t()` definitions
    * `:resolve_tool` — (required) `fn(Call.t()) -> {:ok, string} | {:error, string}`
    * `:resolver_module` — optional module implementing `ToolResolver` behaviour.
      When set, `DispatchTools` checks for dispatch recipes via
      `resolver_module.dispatch_recipe/1`.
    * `:tool_timeout` — maximum time in milliseconds for one tool dispatch,
      including all recipe sub-calls. Defaults to `:infinity`: when the
      caller passes no budget, there is no deadline.
    * `:max_iterations` — iteration ceiling (default: 10)
    * `:on_iteration` — optional callback invoked with the pipeline context
      after each iteration
    * `:pipeline_opts` — options forwarded to `Pipeline.Iteration.ensure_started/1`
    * `:llm_opts` — extra options forwarded to `llm_send_fn`
    * `:terminal_tool` — optional tool name that stops the loop when called.
      The tool is not dispatched; its raw arguments are attached to
      `response.metadata.terminal_args`, with the call under
      `response.metadata.terminal_tool_call`. Sibling tool calls in the
      same response are dispatched before the loop returns, and their
      transcript is appended to the final messages.
    * `:terminal_required` — when `true` (requires `: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
      `{:terminal_missing, %{iteration:, attempts:, last_content:,
      finish_reasons:, terminal_tool:, provider:, model:}}` (the iteration
      case adds `reason: :max_iterations`). A completion that needed retries
      is marked `response.metadata.terminal_recovery_attempts`.
    * `:terminal_nudge` — user-message text for the non-terminal retry.
      Defaults to a sentence naming the terminal tool.
    * `:terminal_content_key` — argument name 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 and leaves it untouched.
    * `:max_nonterminal_stops` — max narrated stops tolerated per run
      under `:terminal_required` (default: 3).
    * `:max_blank_stops` — max consecutive blank-stop responses tolerated
      per iteration before the typed `{:empty_stop, details}` error
      (default: 3). Blank-stop retries do not
      consume the iteration budget.
    * `:blank_stop_nudge` — optional user-message text appended to the
      messages before a blank-stop retry, to break a degenerate provider
      mode. When unset (default), the turn is retried with unchanged
      messages.

## Returns

  * `{:ok, final_response, final_messages}` — LLM produced a text response
    (or called the terminal tool). Nudges pushed during recovery remain in
    `final_messages` as ordinary user messages.
  * `{:error, reason}` — Budget exceeded, LLM error, pipeline error,
    repeated blank stops (`{:empty_stop, %{iteration:, attempts:,
    finish_reasons:, provider:, model:}}`), or repeated narrated stops
    under a required terminal tool (`{:terminal_missing, details}`)

## Telemetry

Emits `[:llm_core, :agent, :complete]` on loop exit with measurements
`%{total_iterations: N}` and metadata `%{tool_calls_count: N}`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
