SubAgentTool — bind a stateless sub-agent to an executor¶
Orqest agents often build compound tools: LLM-facing callables that delegate a structured decision to a stateless sub-agent, execute the decision against a real system (MCP pipeline, sandbox, HTTP API, …), commit the result back onto long-lived session state, and optionally refine the result when a quality check fails.
Before SubAgentTool, every consumer hand-wrote that pipeline — tens
of lines per tool, with hand-rolled refinement loops, manual state
mutations, and inconsistent reporting of "did a refinement fire?".
SubAgentTool captures the pattern in a single class so consumers
only write the domain-specific executor, state updater, and (optional)
evaluator.
Minimal example¶
import asyncio
from pydantic import BaseModel
from orqest.agents import BaseAgent
from orqest.compound import SubAgentTool
from orqest.compound.sub_agent_tool import SubAgentEvalResult
class GeoOutput(BaseModel):
code: str
class State:
def __init__(self):
self.mesh_code = ""
self.quality = 0.0
# Sub-agent (stateless; produces a structured output)
class GeometryAgent(BaseAgent[State, GeoOutput]):
async def _run_implementation(self, state: State, **kwargs) -> GeoOutput:
# In real code this calls an LLM; here we fake it.
note = kwargs.get("note", "")
return GeoOutput(code=f"// mesh for: {note}")
async def run_pipeline(out: GeoOutput, state: State) -> dict:
# Imagine MCP calls here producing a quality score
return {"code": out.code, "quality": 0.8}
def update_state(result: dict, state: State) -> None:
state.mesh_code = result["code"]
state.quality = result["quality"]
def check_quality(result: dict) -> SubAgentEvalResult:
return SubAgentEvalResult(passed=result["quality"] >= 0.5)
def refine_prompt(result: dict, prompt: str) -> str:
return f"{prompt}\n\nPREVIOUS QUALITY {result['quality']} — improve."
tool = SubAgentTool(
agent=GeometryAgent(...),
executor=run_pipeline,
state_updater=update_state,
evaluator=check_quality,
max_refinements=1,
build_refinement_prompt=refine_prompt,
)
async def main() -> None:
state = State()
outcome = await tool.run(state, prompt="square plate")
print(outcome.result, outcome.refined, outcome.iterations)
When to reach for this¶
- You have a structured sub-agent that produces a plan/code/spec, and a deterministic executor that acts on that spec.
- You want quality-based refinement without hand-rolling a retry loop.
- You want best-effort semantics: a failed refinement keeps the original result rather than propagating an exception.
- You compose with
run_with_retryat the outer tool boundary to handle exceptions separately from quality failures.
Semantics — what SubAgentTool does and doesn't do¶
- Does run one (agent → executor → state updater) cycle per pass.
- Does fire up to
max_refinementsadditional passes if an evaluator fails and a refinement-prompt builder is supplied. - Does commit state after every pass so downstream readers see the best result reached, even if a later refinement throws.
- Does not wrap exceptions — raise from the sub-agent or executor
to surface them to the caller (usually inside a
run_with_retryblock that enriches the prompt on failure). - Does not fire
HookRunnerevents by itself. Wire the outer compound-tool boundary withEventBusPublishHookfor observability.
Reference¶
SubAgentTool ¶
SubAgentTool(
agent: BaseAgent,
executor: Callable[[Any, StateT], Awaitable[ResultT]],
state_updater: Callable[[ResultT, StateT], None],
*,
evaluator: Callable[[ResultT], SubAgentEvalResult]
| None = None,
max_refinements: int = 0,
build_refinement_prompt: Callable[[ResultT, str], str]
| None = None,
name: str | None = None,
)
Compose a stateless sub-agent with an executor and optional refinement.
Usage — implement three domain functions and hand them to the tool:
executor(agent_output, state) -> Awaitable[ResultT]— turns the sub-agent's structured output into a real-world outcome (e.g. run the MCP pipeline and return a payload).state_updater(result, state) -> None— mutates the long- lived session state with whatever needs to persist.evaluator(result) -> SubAgentEvalResult(optional) — decides whether the result is good enough or a refinement cycle should fire.
If max_refinements > 0 and the evaluator rejects the first
result, the tool calls build_refinement_prompt(result, prompt)
to construct a new prompt and reruns the sub-agent + executor
cycle. Refinement exceptions are caught and the best prior result
is kept — matching numatics-ai v2's "best effort refinement" rule.
The tool does NOT wrap retry-on-exception; for that, wrap the
run call in :func:orqest.agents.retry.run_with_retry.
Configure the compound flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
BaseAgent
|
A stateless :class: |
required |
executor
|
Callable[[Any, StateT], Awaitable[ResultT]]
|
Async function that runs the real-world action using the sub-agent's output and returns a serializable result payload. |
required |
state_updater
|
Callable[[ResultT, StateT], None]
|
Synchronous mutator that writes the result back onto the state object. |
required |
evaluator
|
Callable[[ResultT], SubAgentEvalResult] | None
|
Optional quality check. When provided with
|
None
|
max_refinements
|
int
|
Number of refinement cycles allowed after
the first pass. |
0
|
build_refinement_prompt
|
Callable[[ResultT, str], str] | None
|
|
None
|
name
|
str | None
|
Optional tool name used in :class: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in orqest/compound/sub_agent_tool.py
run
async
¶
run(
state: StateT,
prompt: str,
*,
use_enriched: bool = False,
**agent_kwargs: Any,
) -> SubAgentResult[ResultT]
Execute one (agent + executor + state-update) cycle, then
optionally refine up to max_refinements times.
The first result is always committed to state before refinement
begins — so a failed refinement leaves the original result in
place (best-effort semantics). Extra keyword arguments are
forwarded verbatim to agent.run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
StateT
|
The agent's state object. |
required |
prompt
|
str
|
The user-facing prompt for the sub-agent. |
required |
use_enriched
|
bool
|
When |
False
|
**agent_kwargs
|
Any
|
Forwarded to the agent. |
{}
|
Source code in orqest/compound/sub_agent_tool.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
SubAgentResult ¶
Outcome of a :meth:SubAgentTool.run invocation.
Captures the final result plus a short history of refinement attempts so consumers (metrics, trace spans, LLM tool returns) can surface "how many passes it took" without re-instrumenting.