Multi-agent Composition
Astromesh lets you compose agents into multi-agent systems where one agent can invoke another as a tool. A supervisor agent can delegate sub-tasks to specialist agents, a supervisor can coordinate workers, and any agent can call another agent the same way it would call any other tool.
This page covers the agent-as-tool mechanism, context transforms for reshaping data between agents, and how the Supervisor pattern builds on them. The Swarm pattern is also described.
Agent-as-Tool
Section titled “Agent-as-Tool”An agent registered as a tool appears in the parent agent’s tool schema like any other function. When the LLM decides to call it, the ToolRegistry invokes the target agent’s full execution pipeline — memory, guardrails, orchestration, and all.
Basic Configuration
Section titled “Basic Configuration”In the parent agent’s YAML, add a tool entry with type: agent:
apiVersion: astromesh/v1kind: Agentmetadata: name: sales-manager version: "1.0.0"
spec: identity: description: "Manages the sales pipeline by delegating to specialist agents"
model: primary: provider: openai model: "gpt-4o"
orchestration: pattern: react max_iterations: 15
tools: - name: qualify-lead type: agent agent: sales-qualifier description: "Qualify a sales lead using BANT methodology"
- name: draft-proposal type: agent agent: proposal-writer description: "Draft a sales proposal for a qualified lead"
- name: web_search type: builtin config: provider: tavilyThe agent field references the metadata.name of the target agent, which must be defined in its own *.agent.yaml file in the same config/agents/ directory.
Agent Tool Fields
Section titled “Agent Tool Fields”| Field | Required | Default | Description |
|---|---|---|---|
name | Yes | — | Tool name as seen by the LLM |
type | Yes | — | Must be agent |
agent | Yes | — | metadata.name of the target agent |
description | No | "Invoke agent '<name>'" | Description shown to the LLM in the tool schema |
parameters | No | {query: string} | Custom JSON Schema for the tool’s parameters |
context_transform | No | — | Jinja2 template to reshape data before passing to the target agent |
rate_limit | No | — | Per-tool rate limit (max_calls, window_seconds) |
Default Parameters
Section titled “Default Parameters”When no custom parameters are specified, the agent tool exposes a single query parameter:
{ "type": "object", "properties": { "query": { "type": "string", "description": "The query or task to send to the agent" } }, "required": ["query"]}You can override this with a custom schema when the target agent expects structured input:
tools: - name: analyze-financials type: agent agent: financial-analyst description: "Analyze financial data for a company" parameters: type: object properties: query: type: string description: "The analysis question" company: type: string description: "Company ticker symbol" fiscal_year: type: integer description: "Fiscal year to analyze" required: ["query", "company"]Context Transforms
Section titled “Context Transforms”Context transforms let you reshape data between agents using Jinja2 templates. This is useful when the parent agent collects information in one shape and the target agent expects it in another.
How It Works
Section titled “How It Works”When a context transform is defined, the ToolRegistry:
- Takes the arguments the LLM passed to the tool call
- Wraps them in a
_DotDict(enabling dot-notation access likedata.companyinstead ofdata["company"]) - Renders the Jinja2 template with the arguments available as
data - Parses the rendered JSON and passes it as the
contextparameter to the target agent’srun()method
The transformed context is then available in the target agent’s Jinja2 system prompt template.
Syntax
Section titled “Syntax”The context_transform value is a Jinja2 expression that produces a JSON object. Arguments from the LLM’s tool call are available under the data variable:
tools: - name: qualify-lead type: agent agent: sales-qualifier context_transform: '{"company": "{{ data.company }}", "budget": "{{ data.budget }}"}'You can use any Jinja2 features — conditionals, filters, defaults:
context_transform: > { "company": "{{ data.company | default('Unknown') }}", "priority": "{% if data.deal_size|int > 100000 %}high{% else %}normal{% endif %}" }Example: Sales Pipeline
Section titled “Example: Sales Pipeline”Consider a sales manager agent that delegates lead qualification to a specialist:
Parent agent (sales-manager.agent.yaml):
spec: tools: - name: qualify-lead type: agent agent: sales-qualifier description: "Qualify a lead. Provide company name, contact, and deal size." context_transform: > { "company": "{{ data.company }}", "contact_name": "{{ data.contact }}", "estimated_value": "{{ data.deal_size }}" }Target agent (sales-qualifier.agent.yaml):
spec: prompts: system: | You are a sales lead qualifier using BANT methodology. {% if company %}Company: {{ company }}{% endif %} {% if contact_name %}Contact: {{ contact_name }}{% endif %} {% if estimated_value %}Deal value: ${{ estimated_value }}{% endif %}
Evaluate Budget, Authority, Need, and Timeline.When the sales manager’s LLM calls qualify-lead with arguments {"query": "Qualify this lead", "company": "Acme Corp", "contact": "Jane Doe", "deal_size": "50000"}, the context transform produces {"company": "Acme Corp", "contact_name": "Jane Doe", "estimated_value": "50000"}, which is injected into the qualifier’s prompt template.
What the parent gets back
Section titled “What the parent gets back”When the parent’s model calls an agent tool, the observation fed back into its history is the child’s answer — not the child’s whole run:
{ "answer": "Lead is qualified: budget confirmed, timeline Q3." }If the child declares an output_schema, its data and data_error come back
alongside the answer. A child that produces no answer at all returns a short
notice saying so, rather than an empty string.
The child’s steps and trace do not come back. They used to, until
0.55.0: the whole run dict was stringified into the calling model’s message
history, so every sub-agent call injected that child’s prompts and tool results
— measured at roughly 13,000 extra input tokens per call — into every later turn
of the parent’s own loop. The parent pays for those tokens on each turn, and it
has no use for them: the answer is what it asked for.
Nothing is lost by the trim. The child’s full run is still recorded — see below.
Tracing across agents
Section titled “Tracing across agents”The child agent’s run is traced in full: agent.run, memory, prompt render,
orchestration, each llm.complete, each tool.call. Agent.run emits that
trace to the collector itself, for every run, whether it was started by a person
or by another agent’s tool call. You query it at GET /v1/traces/{trace_id} and
it is forwarded to OTLP when that is enabled.
On the parent’s side, the tool.call span for the agent tool records the call’s
arguments and a truncated string of what came back, so the parent’s own trace
still shows what it asked and what it got.
Trace: parent-abc Trace: child-defagent.run (sales-manager) agent.run (sales-qualifier)├── memory_build ├── memory_build├── prompt_render ├── prompt_render├── orchestration (react) ├── orchestration (react)│ ├── llm.complete │ ├── llm.complete│ ├── tool.call (qualify) │ └── llm.complete│ └── llm.complete └── memory_persist└── memory_persistCircular Reference Detection
Section titled “Circular Reference Detection”Astromesh prevents infinite loops by detecting circular agent references at bootstrap time. Before any agents are instantiated, AgentRuntime.bootstrap() builds a dependency graph from all agent YAML files and runs a depth-first search (DFS) for cycles.
What Gets Checked
Section titled “What Gets Checked”The detection builds an adjacency list where each agent points to the agents it references via type: agent tools. If the DFS finds a back-edge (a node that is currently being visited), it raises a ValueError with the full cycle path.
flowchart LR
a["agent-a"]
b["agent-b"]
c["agent-c"]
a --> b
b --> c
c -- "cycle!" --> a
Error: "Circular agent reference detected: agent-a -> agent-b -> agent-c -> agent-a"When It Runs
Section titled “When It Runs”Circular reference detection runs once during AgentRuntime.bootstrap(), before any agents are created. If a cycle is detected, bootstrap fails immediately with a clear error message. This is a fail-fast safety check — you will see the error in your logs as soon as the runtime starts.
Allowed Topologies
Section titled “Allowed Topologies”Any directed acyclic graph (DAG) is valid:
flowchart TB
subgraph Valid
vA["A"]
vB["B"]
vC["C"]
vD["D"]
vA --> vB
vA --> vC
vB --> vD
vC -- "diamond, OK" --> vD
end
subgraph Invalid
iA["A"]
iB["B"]
iC["C"]
iA --> iB
iB --> iC
iC -- "cycle!" --> iA
end
Multiple agents can reference the same target agent (diamond pattern). An agent can be both a standalone agent and a tool for other agents.
Calling remote A2A agents
Section titled “Calling remote A2A agents”An agent can also call an agent that is not in your runtime: any server that speaks the A2A protocol. Declare it with type: a2a. It needs the extra pip install "astromesh[a2a]"; without it the agent stays in draft with an “install astromesh[a2a]” error at load time, not on the first call.
tools: - name: agenda_externa type: a2a card_url: https://agentes.ejemplo.com/.well-known/agent-card.json auth: {api_key_env: AGENDA_KEY} # or {bearer_env: AGENDA_TOKEN}; optional policy: {max_bytes: 262144, timeout: 30, accept_parts: [text, data]} # optional description: "Company meeting scheduler" # optional| Key | Required | Notes |
|---|---|---|
card_url | yes | Remote Agent Card. https only unless policy.allow_insecure_http: true. Its host is the only host the tool may reach. |
auth | no | Exactly one of api_key_env (sent as X-API-Key) or bearer_env (Authorization: Bearer). The value is the name of an environment variable, never the secret; a literal api_key: fails at load. |
policy.max_bytes | no | Max remote response size, integer 1 to 16 MiB. |
policy.timeout | no | Seconds, greater than 0 and at most 600. |
policy.accept_parts | no | Non-empty subset of text, data, file. |
policy.allow_insecure_http | no | Allow an http:// card. Off by default. |
description | no | If omitted, it is built from the remote card. |
rate_limit, max_result_tokens | no | Same as other tool types. |
There is no parameters key: the tool always takes {query: string}. Unknown keys, including unknown policy keys, fail at load.
What the model gets back
Section titled “What the model gets back”The tool returns {answer, status, task_id?, pending?}:
- Untrusted output.
answeris the remote reply wrapped as untrusted content, with remotedataparts folded inside it as[data] {...}lines. The model is told not to follow instructions found there, and a remote cannot close the wrapper early (the closing tag is escaped). input_requiredand replies. If the remote asks for more information,pending: trueand the task is remembered per(session_id, tool). The next call to that tool in the same session answers that task instead of starting a new one. Two sessions with the same pending tool each resume their own task.- Failures. A remote that is down or a failed task comes back as an error observation; the parent run continues.
- Origin. The tool always runs with origin
agent, so a remote can never trigger aconfirm-gated action on the user’s behalf.
Remote usage convention
Section titled “Remote usage convention”If the remote reports its own consumption, it does so with a data part whose only key is usage ({"usage": {...}}). Astromesh keeps a sanitized copy in the tool’s trace span (a2a.usage_remoto), hides it from the model, and never adds it to usage.by_model or the run totals: it is not one of your models.
The client side is the astromesh-a2a library (PyPI). Lifecycle, trace span attributes and the ADK equivalent: A2A in Astromesh. To publish your own agents over A2A, see Nexus as an A2A server.
Supervisor Pattern
Section titled “Supervisor Pattern”The Supervisor pattern uses a central coordinating agent that decomposes tasks and delegates sub-tasks to worker agents. Workers are invoked via the agent-as-tool mechanism.
Configuration
Section titled “Configuration”apiVersion: astromesh/v1kind: Agentmetadata: name: project-manager
spec: orchestration: pattern: supervisor max_iterations: 10
tools: - name: researcher type: agent agent: research-agent description: "Research a topic and return findings"
- name: writer type: agent agent: writing-agent description: "Write content based on research findings"
- name: reviewer type: agent agent: review-agent description: "Review content for accuracy and quality"How It Works
Section titled “How It Works”Since core 0.65.0 the supervisor runs on native tool calling, the same tool loop react uses:
- The workers are the manifest’s
type: agenttools, and they are the only tools offered to the model. A call to any other tool is not executed. - The supervisor model (role
supervisor) receives the task and decides which worker to call, with the tool’s arguments as a normal tool call - The call goes through the ToolRegistry, which invokes the target agent
- The worker’s result goes back to the model as the tool result
- The model calls another worker, or answers with plain text, which is the final answer
- The loop stops at the final answer or at
max_iterations
A supervisor with no type: agent tool fails at load time with AgentConfigError.
flowchart TB
sup["`**Supervisor Agent**
Research X, then write a report`"]
researcher["researcher"]
writer["writer"]
reviewer["reviewer"]
final["final answer: compiled report"]
sup -- delegate --> researcher
researcher -- "returns findings" --> sup
sup -- delegate --> writer
writer -- "returns draft" --> sup
sup -- delegate --> reviewer
reviewer -- "returns feedback" --> sup
sup --> final
Worker Agents
Section titled “Worker Agents”Worker agents are standard Astromesh agents with their own YAML definitions. They can use any orchestration pattern, have their own tools, memory, and guardrails. The only requirement is that they exist in config/agents/ and are referenced by name.
Swarm Pattern
Section titled “Swarm Pattern”The Swarm pattern lets an agent hand the conversation to another agent. The targets are the agent’s type: agent tools: passing control means calling one of them. If the target answers, its answer is the final answer; it does not come back to the agent that delegated. An error from the target (rate limit, permission, confirmacion_requerida…) goes back to the model like any other tool result. A swarm agent with no type: agent tool fails to load, as supervisor does.
Configuration
Section titled “Configuration”apiVersion: astromesh/v1kind: Agentmetadata: name: customer-support
spec: orchestration: pattern: swarm max_iterations: 10 max_handoffs: 3 # chained handoffs allowed (default 3)
tools: - name: billing-agent type: agent agent: billing-specialist description: "Handle billing and payment questions"How It Runs
Section titled “How It Runs”- The agent receives the query with the conversation history and
prompts.context(as a message) and sees itstype: agenttools; tool results are capped bymax_tool_result_tokens. - If the model calls a
type: agenttool, the target agent runs with the conversation history (the newest 20 turns, at most 8000 characters) in itsquery. When it answers, that answer ends the run. The target stores only the request in its memory, under its own session<session_id>::<target>, so the person’s history is not duplicated. - If the model calls any other tool, the tool runs and its result goes back to the model.
- A plain text response ends the run.
orchestration.max_handoffs (integer >= 1, default 3) caps chained handoffs. The runtime passes the counter to the child agent, so every sub-agent inherits it, and the model cannot lower it. Once the cap is reached, handoffs are no longer offered or executed.
| Supervisor | Swarm | |
|---|---|---|
| Coordination | Central supervisor decomposes and delegates | The model decides which type: agent tool to hand off to |
| Control flow | Supervisor always gets results back | Control transfers to the target, whose answer is final |
| Best for | Complex tasks requiring planning and synthesis | Routing-style workflows (support triage, handoffs) |
| Final response | Supervisor synthesizes from all worker results | The handoff target’s answer |
Real-World Example: Customer Support Pipeline
Section titled “Real-World Example: Customer Support Pipeline”Here is a complete multi-agent setup for a customer support system:
Triage agent (triage.agent.yaml):
apiVersion: astromesh/v1kind: Agentmetadata: name: triage version: "1.0.0"
spec: identity: description: "Routes customer queries to the right specialist"
model: primary: provider: openai model: "gpt-4o-mini"
orchestration: pattern: react max_iterations: 5
prompts: system: | You are a customer support triage agent. Analyze the customer's question and either answer simple questions directly or hand off to the appropriate specialist.
tools: - name: billing-specialist type: agent agent: billing description: "Handles billing, invoices, refunds, and payment issues"
- name: technical-specialist type: agent agent: tech-support description: "Handles technical issues, bugs, and troubleshooting" context_transform: '{"issue_category": "{{ data.query | truncate(100) }}"}'
- name: knowledge_base type: builtin config: provider: tavilyBilling agent (billing.agent.yaml):
apiVersion: astromesh/v1kind: Agentmetadata: name: billing version: "1.0.0"
spec: identity: description: "Specialist for billing and payment queries"
model: primary: provider: openai model: "gpt-4o"
orchestration: pattern: react max_iterations: 8
prompts: system: | You are a billing specialist. Help customers with invoices, refunds, payment methods, and subscription changes.
tools: - name: sql_query type: builtin config: connection_string: "postgresql://billing_ro@db:5432/billing" read_only: true
guardrails: output: - type: pii_detection action: redactThis setup routes customers to the right agent automatically. The triage agent calls the specialists as type: agent tools, while each specialist uses ReAct with its own tools and guardrails.