Cookbook: Multi-agent orchestration
One agent invokes another via ctx.agents.invoke() — the second agent
runs as a child Temporal workflow of the first. Full audit trail in
the parent's trace; the parent pauses until the child returns.
Reads: parent's input (req.input / req.payload), child's output.
Writes: whatever each agent writes individually.
Composition pattern: specialist agents (forecaster, classifier,
investigator) called by a coordinator agent that stitches results.
Example use case#
A customer-service coordinator agent that:
- Classifies the inbound ticket (calls
triage-classifierchild agent) - If "refund" → calls
refund-eligibilitychild agent + submits to reviewer - If "shipping" → calls
shipment-trackerchild agent + replies
Each child is independently deployable, independently versioned, and independently testable. The coordinator just composes.
manifest.json (coordinator)#
{
"$schema": "https://schemas.konstera.ai/agent-manifest.v3.json",
"id": "io.konstera.cs-coordinator",
"version": "0.1.0",
"name": "Customer Service Coordinator",
"description": "Routes inbound tickets to specialist agents based on category.",
"icon": "🧭",
"autonomy": "autonomous",
"runtime": {
"kind": "container",
"image": "ghcr.io/your-org/cs-coordinator:0.1.0",
"port": 8080,
"timeoutSeconds": 120,
"memoryMi": 256,
"cpuMillis": 300
},
"input": {
"type": "object",
"required": ["ticket_id", "ticket_body"],
"properties": {
"ticket_id": { "type": "string" },
"ticket_body": { "type": "string" }
}
},
"capabilities": {
"needs": [
{ "name": "tickets.reply", "required": true,
"reason": "Send the final reply (coordinated through child agents)" }
]
}
}
No child agents field in the manifest — child agent IDs are passed
to ctx.agents.invoke() at runtime. The platform resolves + grants access
per standard permission rules.
main.py (coordinator)#
from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run
class CoordinatorAgent(Agent):
"""Routes tickets to specialist agents based on triage result."""
async def handle(
self, req: AgentRequest, ctx: AgentContext
) -> AgentResponse:
payload = req.payload or {}
ticket_id = payload.get("ticket_id")
ticket_body = payload.get("ticket_body", "")
if not ticket_id:
return AgentResponse(content="", structured={"error": "ticket_id required"})
await ctx.log.info("coord.start", ticket_id=ticket_id)
# 1. Classify — call the triage specialist as a child workflow
triage = await ctx.agents.invoke(
"io.konstera.triage-classifier",
input=ticket_body,
payload={"ticket_id": ticket_id},
)
# triage.structured = {"category": "refund", "severity": "normal", "confidence": 0.92}
category = (triage.structured or {}).get("category", "unknown")
await ctx.log.info("coord.classified", category=category)
# 2. Dispatch based on category
if category == "refund":
return await self._handle_refund(ticket_id, ticket_body, ctx)
if category == "shipping":
return await self._handle_shipping(ticket_id, ticket_body, ctx)
return await self._handle_generic(ticket_id, triage, ctx)
async def _handle_refund(
self, ticket_id: str, body: str, ctx: AgentContext
) -> AgentResponse:
# Call the refund-eligibility specialist. Blocks until the child
# workflow completes OR hits its manifest timeout.
eligibility = await ctx.agents.invoke(
"io.konstera.refund-eligibility",
input=body,
payload={"ticket_id": ticket_id},
)
decision_payload = eligibility.structured or {}
if decision_payload.get("eligible") is True:
reply = decision_payload.get("suggested_reply", "Refund approved.")
await ctx.capability.call("tickets.reply", ticket_id=ticket_id, body=reply)
return AgentResponse(
content=reply,
structured={
"route": "refund",
"triage_cost": 0, # kernel aggregates this across children
"eligibility_cost": 0,
},
)
# Not eligible — ask a human
decision = await ctx.human.request(
kind="refund-reject",
tier="T1",
summary=f"Ineligible refund for {ticket_id} — human review?",
detail={"ticket_id": ticket_id, "eligibility": decision_payload},
)
await ctx.log.info("coord.refund_rejected", approval=decision.approval_id)
return AgentResponse(content="", structured={"route": "refund", "status": "parked"})
async def _handle_shipping(
self, ticket_id: str, body: str, ctx: AgentContext
) -> AgentResponse:
tracker = await ctx.agents.invoke(
"io.konstera.shipment-tracker",
input=body,
payload={"ticket_id": ticket_id},
)
status = (tracker.structured or {}).get("delivery_status", "unknown")
reply = tracker.content # specialist drafted the whole reply
await ctx.capability.call("tickets.reply", ticket_id=ticket_id, body=reply)
return AgentResponse(
content=reply,
structured={"route": "shipping", "delivery_status": status},
)
async def _handle_generic(
self, ticket_id: str, triage, ctx: AgentContext
) -> AgentResponse:
# No specialist — escalate for human triage
decision = await ctx.human.request(
kind="unrouted",
tier="T1",
summary=f"Unrouted ticket {ticket_id}",
detail={"triage": triage.structured},
)
return AgentResponse(content="", structured={"route": "escalated"})
if __name__ == "__main__":
run(CoordinatorAgent())
What the trace shows#
The invocation trace for the coordinator shows:
coordinator.handle (12s)
├── log.info coord.start
├── agents.invoke io.konstera.triage-classifier (1.2s)
│ └── [full child trace: llm.complete, log, return]
├── log.info coord.classified
├── agents.invoke io.konstera.refund-eligibility (8.4s)
│ └── [full child trace: capability.call × 2, llm.complete, return]
├── capability.call tickets.reply (0.3s)
└── return AgentResponse
Each child's full trace is nested in the parent's. Click through in the portal to see the inner agent's steps, LLM calls, costs.
Cost aggregation#
The portal's cost view attributes each child's spend to the parent's invocation ID. So a single "cs-coordinator" invocation shows the sum of:
- Its own LLM calls (none in this example — pure orchestration)
- Child triage-classifier's LLM calls
- Child refund-eligibility's LLM + tool calls
Admins can slice by parent or by child agent; the data model carries both.
Pitfalls#
- Deep nesting: child → grandchild → great-grandchild compounds latency (each level adds workflow dispatch time) and makes failure modes hard to reason about. Keep nesting ≤ 2 levels in production.
- Child timeout: the child's own
timeoutSecondsapplies. If the parent's budget is tighter than the sum of children, you need to raise the parent'stimeoutSecondsin its manifest or risk the parent timing out while a child is still running. - Circular invocation: don't call back into your own agent via
ctx.agents.invoke(ctx.agent_id, ...). The platform doesn't prevent it, but you'll build infinite workflows that eat Temporal's budget. - Non-deterministic child selection: pick which child to call based on
deterministic logic (triage result). Don't pick based on
random.choice(...)— that breaks Temporal replay.
Common extensions#
- Fan-out: run multiple children in parallel via
await asyncio.gather(ctx.agents.invoke(...), ctx.agents.invoke(...)). Each becomes a parallel child workflow. - Timeout + fallback: wrap a child call in
asyncio.wait_for(...)and fall back to a simpler path if the child takes too long. - Shared state between children: pass through
ctx.statekeys with a shared prefix ("coord:<ticket_id>:state"). Each child reads/writes under the same namespace.
See also#
- Invocation modes — child workflow — the mechanics
- Why Temporal — child workflows explained
- Agent lifecycle — children run their full lifecycle inside the parent