Skip to content

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.

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.

In the parent agent’s YAML, add a tool entry with type: agent:

apiVersion: astromesh/v1
kind: Agent
metadata:
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: tavily

The 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.

FieldRequiredDefaultDescription
nameYes—Tool name as seen by the LLM
typeYes—Must be agent
agentYes—metadata.name of the target agent
descriptionNo"Invoke agent '<name>'"Description shown to the LLM in the tool schema
parametersNo{query: string}Custom JSON Schema for the tool’s parameters
context_transformNo—Jinja2 template to reshape data before passing to the target agent
rate_limitNo—Per-tool rate limit (max_calls, window_seconds)

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 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.

When a context transform is defined, the ToolRegistry:

  1. Takes the arguments the LLM passed to the tool call
  2. Wraps them in a _DotDict (enabling dot-notation access like data.company instead of data["company"])
  3. Renders the Jinja2 template with the arguments available as data
  4. Parses the rendered JSON and passes it as the context parameter to the target agent’s run() method

The transformed context is then available in the target agent’s Jinja2 system prompt template.

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 %}"
}

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.


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.

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-def
agent.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_persist

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.

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.

Error: "Circular agent reference detected: agent-a -> agent-b -> agent-c -> agent-a"

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.

Any directed acyclic graph (DAG) is valid:

Multiple agents can reference the same target agent (diamond pattern). An agent can be both a standalone agent and a tool for other 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
KeyRequiredNotes
card_urlyesRemote Agent Card. https only unless policy.allow_insecure_http: true. Its host is the only host the tool may reach.
authnoExactly 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_bytesnoMax remote response size, integer 1 to 16 MiB.
policy.timeoutnoSeconds, greater than 0 and at most 600.
policy.accept_partsnoNon-empty subset of text, data, file.
policy.allow_insecure_httpnoAllow an http:// card. Off by default.
descriptionnoIf omitted, it is built from the remote card.
rate_limit, max_result_tokensnoSame as other tool types.

There is no parameters key: the tool always takes {query: string}. Unknown keys, including unknown policy keys, fail at load.

The tool returns {answer, status, task_id?, pending?}:

  • Untrusted output. answer is the remote reply wrapped as untrusted content, with remote data parts 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_required and replies. If the remote asks for more information, pending: true and 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 a confirm-gated action on the user’s behalf.

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.


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.

apiVersion: astromesh/v1
kind: Agent
metadata:
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"

Since core 0.65.0 the supervisor runs on native tool calling, the same tool loop react uses:

  1. The workers are the manifest’s type: agent tools, and they are the only tools offered to the model. A call to any other tool is not executed.
  2. The supervisor model (role supervisor) receives the task and decides which worker to call, with the tool’s arguments as a normal tool call
  3. The call goes through the ToolRegistry, which invokes the target agent
  4. The worker’s result goes back to the model as the tool result
  5. The model calls another worker, or answers with plain text, which is the final answer
  6. The loop stops at the final answer or at max_iterations

A supervisor with no type: agent tool fails at load time with AgentConfigError.

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.


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.

apiVersion: astromesh/v1
kind: Agent
metadata:
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"
  1. The agent receives the query with the conversation history and prompts.context (as a message) and sees its type: agent tools; tool results are capped by max_tool_result_tokens.
  2. If the model calls a type: agent tool, the target agent runs with the conversation history (the newest 20 turns, at most 8000 characters) in its query. 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.
  3. If the model calls any other tool, the tool runs and its result goes back to the model.
  4. 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.

SupervisorSwarm
CoordinationCentral supervisor decomposes and delegatesThe model decides which type: agent tool to hand off to
Control flowSupervisor always gets results backControl transfers to the target, whose answer is final
Best forComplex tasks requiring planning and synthesisRouting-style workflows (support triage, handoffs)
Final responseSupervisor synthesizes from all worker resultsThe 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/v1
kind: Agent
metadata:
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: tavily

Billing agent (billing.agent.yaml):

apiVersion: astromesh/v1
kind: Agent
metadata:
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: redact

This 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.

Built by FAiNANSU