# `PtcRunner.SubAgent.Chaining`
[🔗](https://github.com/andreasronge/ptc_runner/blob/main/lib/ptc_runner/sub_agent/chaining.ex#L1)

Chaining functions for SubAgent pipelines.

Provides `then!/3` and `then/3` for composing SubAgent executions,
where each agent receives the previous agent's return value as context.

## Usage

These functions are re-exported from `PtcRunner.SubAgent` for convenience:

    SubAgent.run!(agent1, llm: llm, context: %{x: 1})
    |> SubAgent.then!(agent2, llm: llm)
    |> SubAgent.then!(agent3, llm: llm)

Or with error handling:

    SubAgent.run(agent1, llm: llm, context: %{x: 1})
    |> SubAgent.then(agent2, llm: llm)
    |> SubAgent.then(agent3, llm: llm)

# `then`

```elixir
@spec then(
  {:ok, PtcRunner.Step.t()} | {:error, PtcRunner.Step.t()},
  PtcRunner.SubAgent.Definition.t()
  | PtcRunner.SubAgent.CompiledAgent.t()
  | String.t(),
  keyword()
) :: {:ok, PtcRunner.Step.t()} | {:error, PtcRunner.Step.t()}
```

Chains SubAgent/CompiledAgent executions with error propagation.

Unlike `then!/3`, this returns `{:ok, Step}` or `{:error, Step}`
instead of raising on chain validation failures.

## Examples

    SubAgent.run(agent1, llm: llm, context: %{x: 1})
    |> SubAgent.then(agent2, llm: llm)
    |> SubAgent.then(compiled)  # No LLM needed if pure

# `then!`

```elixir
@spec then!(
  PtcRunner.Step.t(),
  PtcRunner.SubAgent.Definition.t()
  | PtcRunner.SubAgent.CompiledAgent.t()
  | String.t(),
  keyword()
) :: PtcRunner.Step.t()
```

Chains agents in a pipeline, passing the previous step as context.

Equivalent to `run!(agent, Keyword.put(opts, :context, step))`. Enables
pipeline-style composition where each agent receives the previous agent's
`return` value as input.

## Examples

    iex> doubler = PtcRunner.SubAgent.new(
    ...>   prompt: "Double {{n}}",
    ...>   signature: "(n :int) -> {result :int}",
    ...>   max_turns: 1
    ...> )
    iex> adder = PtcRunner.SubAgent.new(
    ...>   prompt: "Add 10 to {{result}}",
    ...>   signature: "(result :int) -> {final :int}",
    ...>   max_turns: 1
    ...> )
    iex> mock_llm = fn %{messages: msgs} ->
    ...>   content = msgs |> List.last() |> Map.get(:content)
    ...>   cond do
    ...>     content =~ "Double" -> {:ok, "```clojure\n{:result (* 2 data/n)}\n```"}
    ...>     content =~ "Add 10" -> {:ok, "```clojure\n{:final (+ data/result 10)}\n```"}
    ...>   end
    ...> end
    iex> result = PtcRunner.SubAgent.run!(doubler, llm: mock_llm, context: %{n: 5})
    ...> |> PtcRunner.SubAgent.then!(adder, llm: mock_llm)
    iex> result.return["final"]
    20

---

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