Legion.Tools.AgentTool (Legion v0.4.0)

View Source

Built-in tool for delegating tasks to sub-agents.

The calling agent must explicitly list allowed sub-agents via tool_config/1:

def tool_config(Legion.Tools.AgentTool), do: [agents: [MyApp.WorkerAgent, MyApp.ResearchAgent]]
def tool_config(_), do: []

Only listed agents can be invoked. Attempts to call unlisted agents raise an error.

Usage example from agent code (executed in sandbox)

AgentTool.call(WorkerAgent, "Summarize this data")

Listed sub-agents are aliased into the sandbox automatically, so their short names (the last segment of the module) resolve to the full module atom - no need to spell out MyApp.Agents.WorkerAgent.

Summary

Functions

Executes a one-off task on a module, or sends a synchronous message to a running agent pid.

Sends a fire-and-forget message to a running agent pid.

Runs multiple sub-agent tasks in parallel and collects results.

Runs sub-agent tasks sequentially, threading each result to the next step.

Starts a long-lived sub-agent process and dispatches task to it asynchronously via cast/2. Returns {:ok, pid} once the process is started — the task runs in the background and its result is not returned. Use call/2 if you need the result, or start_link/2 followed by additional cast/2 calls to queue more messages on the same process.

Chains a sub-agent call after a previous {:ok, result}. Passes {:cancel, reason} through unchanged.

Functions

call(agent_module, task)

Executes a one-off task on a module, or sends a synchronous message to a running agent pid.

When called with a module, the sub-agent runs to completion and returns {:ok, result} or {:cancel, reason}. Raises if the agent is not in the allowed list.

When called with a pid, sends a message to the running agent and blocks for the reply.

cast(pid, message)

Sends a fire-and-forget message to a running agent pid.

parallel(tasks, timeout \\ :infinity)

Runs multiple sub-agent tasks in parallel and collects results.

Returns {:ok, [result1, result2, ...]} when every task succeeds, or the first {:cancel, reason}. Raises if any agent is not in the allowed list.

pipeline(steps)

Runs sub-agent tasks sequentially, threading each result to the next step.

Each step is {agent, task_or_fn}. If task_or_fn is a 1-arity function, it receives the previous step's result and must return the task for the next call. Halts early on the first {:cancel, reason}.

start_link(agent_module, task)

Starts a long-lived sub-agent process and dispatches task to it asynchronously via cast/2. Returns {:ok, pid} once the process is started — the task runs in the background and its result is not returned. Use call/2 if you need the result, or start_link/2 followed by additional cast/2 calls to queue more messages on the same process.

Raises if the agent is not in the allowed list.

then(prev, agent, fun)

Chains a sub-agent call after a previous {:ok, result}. Passes {:cancel, reason} through unchanged.