Condukt.Tool behaviour (Condukt v3.0.0)

Copy Markdown View Source

Behaviour for defining tools that agents can use.

Tools are functions that agents can call to interact with the world: reading files, running commands, making HTTP requests, etc.

Defining a Tool

defmodule MyApp.Tools.Weather do
  use Condukt.Tool

  @impl true
  def name, do: "get_weather"

  @impl true
  def description do
    "Gets the current weather for a location"
  end

  @impl true
  def parameters do
    %{
      type: "object",
      properties: %{
        location: %{
          type: "string",
          description: "City name, e.g. 'San Francisco, CA'"
        }
      },
      required: ["location"]
    }
  end

  @impl true
  def call(%{"location" => location}, _context) do
    case WeatherAPI.get(location) do
      {:ok, data} -> {:ok, format_weather(data)}
      {:error, reason} -> {:error, reason}
    end
  end
end

Tool Context

The call/2 function receives a context map with:

  • :agent - The agent PID
  • :agent_module - The agent module for the session
  • :sandbox - The active Condukt.Sandbox struct (use this for any filesystem or process-execution work)
  • :cwd - Project working directory (kept for tools that need to refer to the host project root for non-sandbox concerns; tools that read/write files or run commands should go through :sandbox)
  • :secrets - Resolved session secrets. Built-in command tools expose these as environment variables. Custom trusted tools can use Condukt.Secrets.env/1 when they need the same values.
  • :opts - Options passed when adding the tool to the agent
  • :assigns - A map of session-scoped assigns visible to every tool in the run. A tool can return {:ok, result, %{key: value}} to merge new entries into this map for the next turn.

Waiting Without Holding a Process

A tool that waits for the outside world, such as a CI webhook, a person's answer, or a slow job, returns {:park, state, opts} instead of a result, much as a GenServer returns {:noreply, state, timeout}. No tool code runs and the tool timeout does not apply while the call is parked. When a signal or its deadline arrives, the session calls wake/3 with the event and state, and cancel/2 with state if the turn is aborted first. See Condukt.Park and the Waiting for Events guide.

Sharing State Between Tools

Use the third element of the success tuple to share facts across tool calls within a session, ExUnit-style:

def call(args, ctx) do
  case ctx.assigns[:found_account_id] do
    nil ->
      {:ok, account} = lookup(args)
      {:ok, render(account), %{found_account_id: account.id}}

    id ->
      {:ok, render(get_account(id))}
  end
end

Returned maps are merged into the session's :assigns last-write-wins. Within a single batch of tool calls all tools see the same start-of-batch snapshot; updates take effect in the next turn.

Aborts

Each call runs in its own process, linked to the turn that made it. Aborting the turn shuts the turn down, and the link takes the call with it, along with any processes the call linked to itself, such as a sub-agent's session. A call that must not stop halfway, because it would leave a side effect half done, opts out with on_abort/1:

@impl true
def on_abort(_opts), do: :finish

Its process then traps exits while it runs, so the abort arrives as an {:EXIT, pid, :shutdown} message. The call can ignore it and run to the end, or receive it, clean up, and stop. Either way its result reaches nobody, because the turn is over.

Streaming output

A tool that runs for a while can show its progress before it returns: output/2 sends a chunk of text as a {:tool_output, tool_call_id, chunk} event to the turn's stream subscribers and notifier, and into the call's output in the session's view. Condukt.Tools.Bash streams a command's output this way.

Concurrency

The calls in one model response run in call order, one at a time, except that consecutive calls of tools that only read run together. A tool that does not change the sandbox or anything else a later call could observe says so with read_only?/1:

@impl true
def read_only?(_opts), do: true

Inline tools take read_only: true. Condukt.Tools.Read, Tools.Glob, and Tools.Grep are read-only. A sub-agent call runs with them when its role cannot change what a later call observes: it starts a sandbox of its own, or has only read-only tools and no sub-agents of its own. A sub-agent that shares the parent's sandbox and can change it runs alone. A call that parks holds its place in the order until it wakes and returns.

Sandbox-aware tools

If your tool reads or writes files, or runs subprocesses, route through Condukt.Sandbox.read/2, Condukt.Sandbox.write/3, Condukt.Sandbox.exec/3, etc. Direct File.* or MuonTrap.cmd/3 calls bypass the sandbox and break the consumer's ability to swap one in (e.g. an in-memory virtual sandbox). Tools that touch unrelated systems (HTTP APIs, databases, in-process state) have nothing to sandbox and are unaffected.

Replay after a crash

When a session's store keeps a journal (see Condukt.SessionStore), each tool call's intent is recorded before the tool runs. If the process dies before the result is recorded, Condukt.Session.resume/2 cannot know whether the call took effect. By default it does not run the tool again: the model gets an error result saying the call was interrupted and decides what to do. A tool whose call can safely run twice with the same arguments, such as a read or a write of the same content to the same path, declares it:

@impl true
def replay_safe?, do: true

Parameterized tools can implement replay_safe?/1 instead. Inline tools pass replay_safe: true to Condukt.tool/1.

Parameterized Tools

Tools can be parameterized when added to an agent:

defmodule MyApp.Tools.Database do
  use Condukt.Tool

  @impl true
  def name(opts), do: "query_#{opts[:table]}"

  @impl true
  def description(opts) do
    "Query the #{opts[:table]} table"
  end

  @impl true
  def call(args, context) do
    table = context.opts[:table]
    Repo.all(from r in table, where: ^build_where(args))
  end
end

# In agent:
def tools do
  [
    {MyApp.Tools.Database, table: "users"},
    {MyApp.Tools.Database, table: "orders"}
  ]
end

Summary

Callbacks

Executes the tool with the given arguments.

Cleans up external work when the turn is aborted while the call is parked.

Returns a description of what the tool does.

Returns the tool name as it will appear to the LLM.

What happens to a running call when its turn is aborted: :kill, the default, stops it, and :finish lets it run to the end. See "Aborts".

Returns the JSON Schema for the tool's parameters.

Whether calls of the tool only read, so they may run alongside other read-only calls of the same response. Defaults to false. See "Concurrency".

Whether an interrupted call may run again when its session is resumed.

Handles the event that wakes a parked call.

Functions

Runs a tool's cancel/2, when it has one.

Executes a tool by name with arguments.

Gets the tool name for a tool spec.

Returns what aborting the turn does to a running call of the tool: :kill unless the tool asks to :finish.

Streams a chunk of a running call's output, from the call's context.

Whether calls of a tool only read: false unless the tool says so.

Whether a tool spec declares its calls safe to run again after a crash.

Builds a tool specification for the LLM provider.

Runs a tool's wake/3 for a parked call.

Whether a tool implements wake/3, which parking requires.

Callbacks

call(args, context)

@callback call(args :: map(), context :: map()) ::
  {:ok, term()}
  | {:ok, term(), map()}
  | {:error, term()}
  | {:park, term(), keyword()}

Executes the tool with the given arguments.

Tools may return:

  • {:ok, result} — the result is sent back to the LLM. Non-binary results are JSON-encoded automatically.
  • {:ok, result, assigns} — same as above, plus a map of values merged into the session's :assigns. Subsequent tool calls in the same run can read them as context.assigns[:key]. Last-write-wins on key collisions, matching Phoenix.Component.assign/3.
  • {:error, reason} — the LLM receives an error.
  • {:park, state, opts} — the call waits for a signal or a time. wake/3 receives the event and state. See Condukt.Park.

Within a single batch of tool calls in one assistant message, each tool starts from the same start-of-batch assigns snapshot; updates are merged after the batch and visible in the next turn.

cancel(state, context)

(optional)
@callback cancel(state :: term(), context :: map()) :: term()

Cleans up external work when the turn is aborted while the call is parked.

Like GenServer.terminate/2, it receives the call's last parked state. It runs in its own process, also for a woken call that is aborted before it parks again or returns, and may run more than once, so keep it idempotent. Its return value is ignored.

description()

@callback description() :: String.t()

Returns a description of what the tool does.

description(opts)

(optional)
@callback description(opts :: keyword()) :: String.t()

name()

@callback name() :: String.t()

Returns the tool name as it will appear to the LLM.

name(opts)

(optional)
@callback name(opts :: keyword()) :: String.t()

on_abort(opts)

(optional)
@callback on_abort(opts :: keyword()) :: :kill | :finish

What happens to a running call when its turn is aborted: :kill, the default, stops it, and :finish lets it run to the end. See "Aborts".

parameters()

@callback parameters() :: map()

Returns the JSON Schema for the tool's parameters.

parameters(opts)

(optional)
@callback parameters(opts :: keyword()) :: map()

read_only?(opts)

(optional)
@callback read_only?(opts :: keyword()) :: boolean()

Whether calls of the tool only read, so they may run alongside other read-only calls of the same response. Defaults to false. See "Concurrency".

replay_safe?()

(optional)
@callback replay_safe?() :: boolean()

Whether an interrupted call may run again when its session is resumed.

Defaults to false. See "Replay after a crash" above.

replay_safe?(opts)

(optional)
@callback replay_safe?(opts :: keyword()) :: boolean()

wake(event, state, context)

(optional)
@callback wake(event :: term(), state :: term(), context :: map()) ::
  {:ok, term()}
  | {:ok, term(), map()}
  | {:error, term()}
  | {:park, term(), keyword()}

Handles the event that wakes a parked call.

event is {:signal, {kind, key}, value}, with the value the signal kind's cast/1 returned, or :timeout when the park's deadline came first. state is the term the call parked with. Returns what call/2 returns, so a call can park again, for example to poll once more.

A tool that parks must implement it.

Functions

cancel(module, state, context)

Runs a tool's cancel/2, when it has one.

execute(module, args, context)

Executes a tool by name with arguments.

name(module)

Gets the tool name for a tool spec.

on_abort(module)

Returns what aborting the turn does to a running call of the tool: :kill unless the tool asks to :finish.

output(context, chunk)

Streams a chunk of a running call's output, from the call's context.

The session publishes it as {:tool_output, tool_call_id, chunk} to the turn's stream subscribers and notifier, and appends it to the call's output in its view, for a turn run with Condukt.run/3 too. Session secrets in chunk are redacted first. Send text a line at a time where you can: each chunk is redacted on its own, so a secret split across two chunks would not be found.

Any process may call it with the call's context, also after the call parked, as long as the turn runs. Outside a session it does nothing.

read_only?(module)

Whether calls of a tool only read: false unless the tool says so.

replay_safe?(module)

Whether a tool spec declares its calls safe to run again after a crash.

to_spec(inline)

Builds a tool specification for the LLM provider.

wake(module, event, state, context)

Runs a tool's wake/3 for a parked call.

wakes?(module)

Whether a tool implements wake/3, which parking requires.